body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am learning C++ and socket programming and OpenSSL. As such, I decided to make a simple client that opens a TLS connection and writes some data as practice. It also serves as a base for more complex applications. </p> <p>I'm very new to C++, so I don't know if I'm using good naming conventions or other basic practices. The program is using OpenSSL 1.1.0.</p> <pre><code>#include &lt;errno.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;resolv.h&gt; #include &lt;netdb.h&gt; #include &lt;openssl/ssl.h&gt; #include &lt;openssl/err.h&gt; //Not sure what headers are needed or not //This code (theoretically) writes "Hello World, 123" to a socket over a secure TLS connection //compiled with g++ -Wall -o client.out client.cpp -L/usr/lib -lssl -lcrypto //Based off of: https://www.cs.utah.edu/~swalton/listings/articles/ssl_client.c //The OpenConnection method was heavily based on the answer to this post: https://stackoverflow.com/questions/52727565/client-in-c-use-gethostbyname-or-getaddrinfo const int ERROR_STATUS = -1; SSL_CTX *InitSSL_CTX(void) { const SSL_METHOD *method = TLS_client_method(); /* Create new client-method instance */ SSL_CTX *ctx = SSL_CTX_new(method); if (ctx == nullptr) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } return ctx; } int OpenConnection(const char *hostname, const char *port) { struct hostent *host; if ((host = gethostbyname(hostname)) == nullptr) { perror(hostname); exit(EXIT_FAILURE); } struct addrinfo hints = {0}, *addrs; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; const int status = getaddrinfo(hostname, port, &amp;hints, &amp;addrs); if (status != 0) { fprintf(stderr, "%s: %s\n", hostname, gai_strerror(status)); exit(EXIT_FAILURE); } int sfd, err; for (struct addrinfo *addr = addrs; addr != nullptr; addr = addr-&gt;ai_next) { sfd = socket(addrs-&gt;ai_family, addrs-&gt;ai_socktype, addrs-&gt;ai_protocol); if (sfd == ERROR_STATUS) { err = errno; continue; } if (connect(sfd, addr-&gt;ai_addr, addr-&gt;ai_addrlen) == 0) { break; } err = errno; sfd = ERROR_STATUS; close(sfd); } freeaddrinfo(addrs); if (sfd == ERROR_STATUS) { fprintf(stderr, "%s: %s\n", hostname, strerror(err)); exit(EXIT_FAILURE); } return sfd; } void DisplayCerts(SSL *ssl) { X509 *cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */ if (cert != nullptr) { printf("Server certificates:\n"); char *line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); printf("Subject: %s\n", line); delete line; line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); printf("Issuer: %s\n", line); delete line; X509_free(cert); } else { printf("Info: No client certificates configured.\n"); } } int main(int argc, char const *argv[]) { SSL_CTX *ctx = InitSSL_CTX(); SSL *ssl = SSL_new(ctx); if (ssl == nullptr) { fprintf(stderr, "SSL_new() failed\n"); exit(EXIT_FAILURE); } //Host is hardcoded to localhost for testing purposes const int sfd = OpenConnection("127.0.0.1", argv[1]); SSL_set_fd(ssl, sfd); const int status = SSL_connect(ssl); if (status != 1) { SSL_get_error(ssl, status); ERR_print_errors_fp(stderr); //High probability this doesn't do anything fprintf(stderr, "SSL_connect failed with SSL_get_error code %d\n", status); exit(EXIT_FAILURE); } printf("Connected with %s encryption\n", SSL_get_cipher(ssl)); const char *chars = "Hello World, 123!"; SSL_write(ssl, chars, strlen(chars)); SSL_free(ssl); close(sfd); SSL_CTX_free(ctx); return 0; } </code></pre> <p><a href="https://gist.github.com/vedantroy/d2b99d774484cf4ea5165b200888e414" rel="noreferrer">Here's the same code in a Gist!</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T07:15:20.813", "Id": "396400", "Score": "2", "body": "It seems like a reasonable C solution but its not good C++. You need to study RAII make sure any resource allocation is exception safe. Unfortunately I cant write a review on C c...
[ { "body": "<h1>C++ review</h1>\n<p>You still need a C review!</p>\n<h2>Idioms/Patterns</h2>\n<h3>RAII idiom</h3>\n<p>In C++ we have this concept that an object should clean up its own resources. So when an object is created it will create and hold onto resources and when it is destroyed it will clean up those r...
{ "AcceptedAnswerId": "205504", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T04:21:17.517", "Id": "205478", "Score": "7", "Tags": [ "c++", "socket", "openssl" ], "Title": "A Simple C++ Client That Sends Data Over TLS Using OpenSSL" }
205478
<p>This is a pong game with 4 paddles. The paddles are always on the same height as the mouse. I wrote it in C using SDL. The Makefile works for linux. Do you think the code is readable or should I structure it different? Do i need more comments or is evertything self explanatory?</p> <p><a href="https://github.com/noahhaasis/pong_ultimate" rel="nofollow noreferrer">https://github.com/noahhaasis/pong_ultimate</a></p> <pre><code>#include &lt;stdbool.h&gt; #include &lt;math.h&gt; #include &lt;time.h&gt; #include "SDL2/SDL.h" #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 800 #define PADDLE_HEIGHT 100 #define PADDLE_WIDTH 20 #define BORDER_DISTANCE 10 #define BALL_RADIUS 10 #define BALL_VELOCITY 8 /* In pixel per frame */ #define FPS 30 typedef struct { /* x and y denote the upper left corner */ int x; int y; int width; int height; } paddle_t; typedef struct { paddle_t left_paddle; paddle_t right_paddle; paddle_t top_paddle; paddle_t bottom_paddle; } paddles_t; typedef struct { int x; int y; int radius; int y_velocity; int x_velocity; } ball_t; void initialize_paddles(paddles_t *paddles); void initialize_ball(ball_t *ball); void draw_paddles(paddles_t *paddles, SDL_Renderer *renderer); void draw_paddle(paddle_t *paddle, SDL_Renderer *renderer); void draw_ball(ball_t *ball, SDL_Renderer *renderer); void update_ball(ball_t *ball, paddles_t *paddles); void update_paddles(paddles_t *paddles); int constrain(int n, int low, int heigh); /* Compute the x_velocity so the ball has a total velocity of BALL_VELOCITY */ int compute_x_velocity(int y_velocity); bool intersect(paddle_t *paddle, ball_t *ball); int main(void) { SDL_Init(SDL_INIT_VIDEO); Uint32 flags = SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE; SDL_Window *window = SDL_CreateWindow( "Pong Ultimate", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, flags); SDL_SetRelativeMouseMode(SDL_TRUE); // Trap the mouse SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); int ms_per_frame = 1000/FPS; paddles_t paddles; initialize_paddles(&amp;paddles); srand(time(NULL)); ball_t ball; initialize_ball(&amp;ball); Uint32 last_time = SDL_GetTicks(); bool running = true; SDL_Event e; while (running) { while (SDL_PollEvent(&amp;e)) { bool pressed_esc = e.type == SDL_KEYDOWN &amp;&amp; e.key.keysym.scancode == SDL_SCANCODE_ESCAPE; if (e.type == SDL_QUIT || pressed_esc) { running = false; } } update_ball(&amp;ball, &amp;paddles); update_paddles(&amp;paddles); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); draw_paddles(&amp;paddles, renderer); draw_ball(&amp;ball, renderer); SDL_RenderPresent(renderer); /* Enforce a specified frame-rate */ while (!SDL_TICKS_PASSED(SDL_GetTicks(), last_time + ms_per_frame)); last_time = SDL_GetTicks(); } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } int constrain(int n, int low, int heigh) { if (n &lt; low) { return low; } else if (n &gt; heigh) { return heigh; } return n; } void draw_paddle(paddle_t *paddle, SDL_Renderer *renderer) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderDrawRect(renderer, (SDL_Rect *)paddle); } void initialize_paddles(paddles_t *paddles) { int horizontal_middle = (int)((SCREEN_WIDTH - PADDLE_HEIGHT) / 2); int vertical_middle = (int)((SCREEN_HEIGHT - PADDLE_HEIGHT) / 2); paddles-&gt;left_paddle.x = BORDER_DISTANCE; paddles-&gt;left_paddle.y = vertical_middle; paddles-&gt;left_paddle.width = PADDLE_WIDTH; paddles-&gt;left_paddle.height = PADDLE_HEIGHT; paddles-&gt;right_paddle.x = SCREEN_WIDTH - BORDER_DISTANCE - PADDLE_WIDTH; paddles-&gt;right_paddle.y = vertical_middle; paddles-&gt;right_paddle.width = PADDLE_WIDTH; paddles-&gt;right_paddle.height = PADDLE_HEIGHT; paddles-&gt;top_paddle.x = horizontal_middle; paddles-&gt;top_paddle.y = BORDER_DISTANCE; paddles-&gt;top_paddle.width = PADDLE_HEIGHT; paddles-&gt;top_paddle.height = PADDLE_WIDTH; paddles-&gt;bottom_paddle.x = horizontal_middle; paddles-&gt;bottom_paddle.y = SCREEN_HEIGHT - BORDER_DISTANCE - PADDLE_WIDTH; paddles-&gt;bottom_paddle.width = PADDLE_HEIGHT; paddles-&gt;bottom_paddle.height = PADDLE_WIDTH; } void draw_ball(ball_t *ball, SDL_Renderer *renderer) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); for (int w = 0; w &lt; ball-&gt;radius * 2; w++) { for (int h = 0; h &lt; ball-&gt;radius * 2; h++) { int dx = ball-&gt;radius - w; // horizontal offset int dy = ball-&gt;radius - h; // vertical offset if ((dx*dx + dy*dy) &lt;= (ball-&gt;radius * ball-&gt;radius)) { SDL_RenderDrawPoint(renderer, ball-&gt;x + dx, ball-&gt;y + dy); } } } } /* In the triangle ABC the velocities are the catheti and BALL_VELOCITY is the hypotenuse */ int compute_x_velocity(int y_velocity) { // c**2 = a**2 + b**2 // b = sqrt(c**2 - a**2) return sqrt(BALL_VELOCITY*BALL_VELOCITY - y_velocity*y_velocity); } bool intersect(paddle_t *paddle, ball_t *ball) { bool horizontal_intersect = (ball-&gt;y - ball-&gt;radius) &lt; (paddle-&gt;y + paddle-&gt;height) &amp;&amp; (ball-&gt;y + ball-&gt;radius) &gt; paddle-&gt;y; bool vertical_intersect = (ball-&gt;x - ball-&gt;radius) &lt; (paddle-&gt;x + paddle-&gt;width) &amp;&amp; (ball-&gt;x + ball-&gt;radius) &gt; paddle-&gt;x; return vertical_intersect &amp;&amp; horizontal_intersect; } void initialize_ball(ball_t *ball) { ball-&gt;x = SCREEN_WIDTH/2; ball-&gt;y = SCREEN_HEIGHT/2; ball-&gt;radius = BALL_RADIUS; // -BALL_VELOCITY &lt;= y_velocity &lt;= BALL_VELOCITY ball-&gt;y_velocity = (rand() % (BALL_VELOCITY*2)) - BALL_VELOCITY; ball-&gt;x_velocity = compute_x_velocity(ball-&gt;y_velocity); } void draw_paddles(paddles_t *paddles, SDL_Renderer *renderer) { draw_paddle(&amp;paddles-&gt;left_paddle, renderer); draw_paddle(&amp;paddles-&gt;right_paddle, renderer); draw_paddle(&amp;paddles-&gt;top_paddle, renderer); draw_paddle(&amp;paddles-&gt;bottom_paddle, renderer); } void update_paddles(paddles_t *paddles) { int mouse_x, mouse_y; SDL_GetMouseState(&amp;mouse_x, &amp;mouse_y); int max_x = SCREEN_WIDTH - (BORDER_DISTANCE + PADDLE_WIDTH + PADDLE_HEIGHT); int min_x = BORDER_DISTANCE + PADDLE_WIDTH; int new_x = constrain(mouse_x - PADDLE_HEIGHT/2, min_x, max_x); int min_y = BORDER_DISTANCE + PADDLE_WIDTH; int max_y = SCREEN_HEIGHT - (BORDER_DISTANCE + PADDLE_WIDTH + PADDLE_HEIGHT); int new_y = constrain(mouse_y - PADDLE_HEIGHT/2, min_y, max_y); paddles-&gt;left_paddle.y = new_y; paddles-&gt;right_paddle.y = new_y; paddles-&gt;top_paddle.x = new_x; paddles-&gt;bottom_paddle.x = new_x; } void update_ball(ball_t *ball, paddles_t *paddles) { // Bounce of the paddles if (intersect(&amp;paddles-&gt;right_paddle, ball) || intersect(&amp;paddles-&gt;left_paddle, ball)) { ball-&gt;x_velocity = -ball-&gt;x_velocity; } if (intersect(&amp;paddles-&gt;bottom_paddle, ball) || intersect(&amp;paddles-&gt;top_paddle, ball)) { ball-&gt;y_velocity = -ball-&gt;y_velocity; } // Update ball ball-&gt;x += ball-&gt;x_velocity; ball-&gt;y += ball-&gt;y_velocity; // Reset the ball if it touches the borders if (ball-&gt;x &lt;= 0 || ball-&gt;x &gt;= SCREEN_WIDTH || ball-&gt;y &lt;= 0 || ball-&gt;y &gt;= SCREEN_HEIGHT) { initialize_ball(ball); } } </code></pre>
[]
[ { "body": "<pre><code>/* Compute the x_velocity so the ball has a total velocity of BALL_VELOCITY */\nint compute_x_velocity(int y_velocity);\n...\n// Update ball\nball-&gt;x += ball-&gt;x_velocity;\nball-&gt;y += ball-&gt;y_velocity;\n</code></pre>\n\n<p>These kinds of comments seem redundant, on very self-exp...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T05:14:47.257", "Id": "205480", "Score": "2", "Tags": [ "c", "game", "sdl" ], "Title": "Pong Ultimate - Pong with 4 paddles" }
205480
<p>I'm trying to implement <a href="https://knizia.de/wp-content/uploads/reiner/pdfs/Knizia-Website-Decathlon.pdf" rel="nofollow noreferrer">Reiner Knizia’s Decathlon</a>, a set of 10 solo dice games played with 8 dices named after Decathlon events in Olympics.</p> <p>The first event is called "100 Metres". The player divides 8 dices into two sets of 4, then pick a set and throw. He may keep the dice (freeze) or rethrow. After he is satisfied with the result, he does the same with the other set. He has a total of 5 rethrows. The score is the total of the dice after he freezes all dice.</p> <p>My approach: There are 10 events, so it is going to be a lot of repetitive code. I made a Event class, and each Event will have a self.state dict object keeping tracking of dice rolls and number of rethrows. Each event will also have a self.print_game_state object.</p> <p>Here is the code. Any idea to write this code smarter?</p> <p>common.py</p> <pre><code>import random class DiceRoller: def __new__(cls, num_dice=1): return [random.randint(1, 6) for _ in range(num_dice)] class Event: def __init__(self): if not hasattr(self, 'state'): self.state = dict() def print_game_state(self): for key, value in self.state.items(): print(f'{key}: {value}') print(f'Score: {self.score()}') if self.game_finished(): print('Game Finished') </code></pre> <p>e100metres.py</p> <pre><code>from common import DiceRoller, Event class E100Metres(Event): '''100 metres event.''' def __init__(self): super().__init__() self.state.update({ 'frozen_sets': 0, 'remaining_rerolls': 5, 'frozen_dices': [], 'current_rolls': DiceRoller(4) }) self.print_game_state() def game_finished(self): return self.state['frozen_sets'] &gt;= 2 def no_more_rerolls(self): return self.state['remaining_rerolls'] &lt;= 0 def reroll(self): if self.game_finished(): raise Exception('Game already finished') if self.no_more_rerolls(): raise Exception('No more rerolls') self.state['remaining_rerolls'] -= 1 self.state['current_rolls'] = DiceRoller(4) self.print_game_state() def freeze(self): if self.game_finished(): raise Exception('Game already finished') self.state['frozen_dices'] += self.state['current_rolls'] self.state['frozen_sets'] += 1 if self.game_finished(): self.state['current_rolls'] = list() else: self.state['current_rolls'] = DiceRoller(4) self.print_game_state() def score(self): return sum(self.state['frozen_dices']) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T12:02:43.163", "Id": "396407", "Score": "0", "body": "Please verify your code. The braces don't match." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T16:59:40.593", "Id": "396432", "Score": "...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T09:07:18.797", "Id": "205484", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "dice" ], "Title": "Solo dice game (from Reiner Knizia’s Decathlon)" }
205484
<p>I'm trying to improve performance for a generic function that turns a string into a multidimensional array.</p> <p>Expected input:</p> <ul> <li>A string that was generated by the function <code>Arrays.deepToString()</code>.</li> <li>The original array had no null values and did not contain arrays of length 0.</li> <li>The array can have any number of dimensions from 1 to 200.</li> <li>Sub-arrays may have different length (e.g. <code>arr[0].length != arr[1].length</code>)</li> </ul> <p>The function converts the values into the requested data type, which may be any primitive variable or String.</p> <pre><code>private static String[] arraySeparators; private static Class[] arrayTypes; public static &lt;T&gt; Object reverseDeepToString(String str, Class&lt;T&gt; dataType){ int dimensions = 0; while(str.charAt(dimensions) == '[') dimensions++; arraySeparators = new String[dimensions + 1]; String separator = ", "; for(int x = 2; x &lt;= dimensions; x++) arraySeparators[x] = separator = ']' + separator + "\\["; arrayTypes = new Class[dimensions + 1]; Class temp = arrayTypes[2] = Array.newInstance(dataType, 0).getClass(); for(int x = 3; x &lt;= dimensions; x++) arrayTypes[x] = temp = Array.newInstance(temp, 0).getClass(); str = str.substring(dimensions, str.length() - dimensions); Object r = createArrayRecursive(str, dimensions, dataType); arraySeparators = null; arrayTypes = null; return r; } private static &lt;T&gt; Object createArrayRecursive(String str, int dimension, Class&lt;T&gt; dataType){ if(dimension == 1){ String[] s = str.split(", "); Object result = Array.newInstance(dataType, s.length); for(int x = 0; x &lt; s.length; x++){ if(dataType == String.class) Array.set(result, x, s[x]); else if(dataType == int.class) Array.set(result, x, Integer.parseInt(s[x])); else if(dataType == double.class) Array.set(result, x, Double.parseDouble(s[x])); else if(dataType == float.class) Array.set(result, x, Float.parseFloat(s[x])); else if(dataType == long.class) Array.set(result, x, Long.parseLong(s[x])); else if(dataType == boolean.class) Array.set(result, x, Boolean.parseBoolean(s[x])); else if(dataType == short.class) Array.set(result, x, Short.parseShort(s[x])); else if(dataType == byte.class) Array.set(result, x, Byte.parseByte(s[x])); else if(dataType == char.class) Array.set(result, x, s[x].charAt(0)); } return result; } String[] s = str.split(arraySeparators[dimension]); Object arr = Array.newInstance(arrayTypes[dimension], s.length); for(int x = 0; x &lt; s.length; x++) Array.set(arr, x, createArrayRecursive(s[x], dimension - 1, dataType)); return arr; } </code></pre> <p>The problem is that these workarounds to deal with limitations of generic types are slowing down the function significantly compared to the non-generic equivalent:</p> <pre><code>private static String[] arraySeparators; public static Object reverseDeepToString(String str){ int dimensions = 0; while(str.charAt(dimensions) == '[') dimensions++; arraySeparators = new String[dimensions + 1]; String separator = ", "; for(int x = 2; x &lt;= dimensions; x++) arraySeparators[x] = separator = ']' + separator + "\\["; str = str.substring(dimensions, str.length() - dimensions); return createArrayRecursive(str, dimensions); } private static Object createArrayRecursive(String str, int dimension){ if(dimension == 1){ String[] s = str.split(", "); double[] result = new double[s.length]; for(int x = 0; x &lt; s.length; x++) result[x] = Double.parseDouble(s[x]); return result; } String[] s = str.split(arraySeparators[dimension]); int[] lengths = new int[dimension]; lengths[0] = s.length; Object arr = Array.newInstance(double.class, lengths); for(int x = 0; x &lt; s.length; x++) Array.set(arr, x, createArrayRecursive(s[x], dimension - 1)); return arr; } </code></pre> <p>My question is: is there a way to make a generic function as efficient as a non-generic function, or at least get very close to it?</p> <p>The only alternative I have in mind is creating lots of copies of the non-generic function (one for each variable type), and have a main function choosing which non-generic function to use, but that will be a very long and ugly code that I try to avoid:</p> <pre><code>public static &lt;T&gt; Object reverseDeepToString(String str, Class&lt;T&gt; dataType){ if(dataType == int.class) return reverseDeepToString_int(str); if(dataType == double.class) return reverseDeepToString_double(str); if(dataType == long.class) return reverseDeepToString_long(str); if(dataType == String.class) return reverseDeepToString_string(str); if(dataType == boolean.class) return reverseDeepToString_boolean(str); ... } </code></pre>
[]
[ { "body": "<p>The only option to have this really fast is to use primitive types, which in turn requires to write \"non-generic\" (specialised for every primitive type) function (piece of code) for every primitive type that you would like to use. By \"non-generic\" here I mean code that use specialised types on...
{ "AcceptedAnswerId": "205646", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T09:12:01.527", "Id": "205485", "Score": "1", "Tags": [ "java", "performance", "generics" ], "Title": "Performance of generic VS non-generic method (array generating function)" }
205485
<p>Based on the many other number guessing games people tend to post as first questions, <a href="https://www.xkcd.com/221/" rel="nofollow noreferrer">https://www.xkcd.com/221/</a>, and a crypto class I'm taking, I've decided to implement a number guessing game using the best python style I can, and the best random number generator I can create. Any advice is appreciated.</p> <pre><code>#!/usr/bin/env python3 """ This is a simple guessing game. It is very difficult. """ from time import time class Random(): ''' Class for generating cryptographically secure random 4s 4 is random and was chosen by dice roll. ''' def __init__(self, seed=0): self.seed = seed def set_seed(self, seed): ''' Sets the rng's seed. This method should be called before the first use if a seed is not passed to the constructor ''' self.seed = seed def get_random_int(self, low, high): ''' Generates a random integer between low and high as long as low &lt;= 4 &lt;= high. ''' return self._restrict_to_bounds(4, low, high) def get_random_float(self, low, high): ''' Generates a random float between low and high as long as low &lt;= 4.0 &lt;= high. ''' return self._restrict_to_bounds(4.0, low, high) def _restrict_to_bounds(self, val, low, high): ''' returns val clamped between low and high''' if low &lt;= val &lt;= high: return val if val == 4: return val return 4 def game(low=0, high=1_000_000): ''' Runs the game ''' rand_source = Random(time()) secret_number = rand_source.get_random_int(low, high) print(f'''Welcome to the Guessing Game. I have generated a random integer between {low}, and {high}. Your job is to guess it in as few guesses as possible.\n''') guess_num = 1 guess = None while True: guess = input('Enter your guess: ') try: guess = int(guess) except ValueError: print("You didn't guess an integer, try again.") continue if guess == secret_number: break elif guess &gt; secret_number: print('Your guess was too high, try again') elif guess &lt; secret_number: print('Your guess was too low, try again') guess_num += 1 print() if guess_num == 1: print(f''''You got the right answer in {guess_num} guess! Are you cheating?''') else: print(f'You got the right answer in {guess_num} guesses!') play_again = input('Do you want to play again? (enter y or n)\n') if play_again == 'y': game() if __name__ == '__main__': game() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T10:15:55.737", "Id": "396404", "Score": "0", "body": "*β€œthe best random number generator”* for *β€œgenerating cryptographically secure random 4s”* – is this meant as a serious request for review?" }, { "ContentLicense": "CC BY...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T09:44:59.523", "Id": "205487", "Score": "1", "Tags": [ "python", "random" ], "Title": "Simple joke guessing game" }
205487
<p>The objective of the post is to improve design and improve command on C++. Given a map, start point and end point, the shortest path to end point from the start point has to be found out using Astar (A*) algorithm. The algorithm uses an evaluation function <code>f</code> for each point or node in the map. The <code>f</code> depends on <code>g</code> and <code>h</code>. The <code>g</code> is distance from start point to the point under consideration(current point in the path). The <code>h</code> is a heuristic which provides an (under)estimate of the distance from current point to end point. The <code>frontier</code> is a set that contains all candidate points to form the path. The pseudocode/ algorithm:</p> <pre><code>1) The values of f, g and h for all points are initially set to infinity (a very high value); 2) The start point is assigned a g of 0 and its h is calculated using Manhattan distance. This is then inserted to the frontier. The end point is assigned an h of 0. 3) Until frontier is empty, do: a) Extract the point (current point) with lowest f value from the frontier. b) Check if it is the end point. If yes, report success. Else, continue. c) Collect all the eligible neighbors of the current point and add them to the frontier. During this addition, their f, g, h and parent are updated. d) Remove the current point from frontier. 4) If success is not reported in (3), report failure. </code></pre> <p>Here is the commented code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;stdexcept&gt; #include &lt;set&gt; #include &lt;algorithm&gt; // Class to handle individual nodes/ points/ location in the environment map class Point { // The x coordinate of the point int x_v = {-1}; // The y coordinate of the point int y_v = {-1}; // The value at the point; either 1 or 0 int val_v = {0}; // The total estimated cost of a point; A star uses this value double f_v = {100000}; // The cost to reach a point; A star uses this value double g_v = {100000}; // The estimate of cost (heuristic) to reach end from current point; A star uses this value double h_v = {100000}; // The parent of Point set by Astar so that path from start to end can be retrieved Point* parent_v = nullptr; public: Point() {} Point(int xx, int yy, int vv) : x_v{xx}, y_v{yy}, val_v{vv} {} // Copy constructor Point(const Point&amp; p1) { x_v = p1.x(); y_v = p1.y(); val_v = p1.val(); f_v = p1.f(); g_v = p1.g(); h_v = p1.h(); parent_v = p1.parent(); } ~Point(){} int val() const { return val_v; } int x() const { return x_v; } int y() const { return y_v; } double f() const { return f_v; } double g() const { return g_v; } double h() const { return h_v; } Point* parent() const { return parent_v; } void set_g(double g) { g_v = g; f_v = g_v + h_v; } void set_h(double h) { h_v = h; f_v = g_v + h_v; } void set_parent(Point* p) { parent_v = p; } // Assignment operator Point&amp; operator=(const Point&amp; p1) { x_v = p1.x(); y_v = p1.y(); val_v = p1.val(); f_v = p1.f(); g_v = p1.g(); h_v = p1.h(); parent_v = p1.parent(); return *this; } //This operator has been defined so that std::set can use it as comparison object friend bool operator&lt;(const Point&amp; p1, const Point&amp; p2) { if(p1.x() &lt; p2.x()) { return true; } if(p1.x() == p2.x() &amp;&amp; p1.y() &lt; p2.y()) { return true; } return false; } friend bool operator==(const Point&amp; p1, const Point&amp; p2) { return (p1.x() == p2.x()) &amp;&amp; (p1.y() == p2.y()); } friend bool operator!=(const Point&amp; p1, const Point&amp; p2) { return !(p1 == p2); } }; // Class to perform A star class Astar { // The map of the environment std::vector&lt;std::vector&lt;Point&gt;&gt; map_v; // The size of the map int map_x = {0}; int map_y = {0}; // The start and end points Point* start_v; Point* end_v; // The variable to store path from start to end std::vector&lt;Point*&gt; path_v; public: Astar(std::vector&lt;std::vector&lt;int&gt;&gt;&amp;, std::pair&lt;int, int&gt;&amp;, std::pair&lt;int, int&gt;&amp;); bool is_valid(int, int); double manhattan(Point*); bool search(); std::vector&lt;Point*&gt; path(); }; // Constructor that takes in map, start and end from the user/ main and converts it into variables of the class Astar::Astar(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; map, std::pair&lt;int, int&gt;&amp; start, std::pair&lt;int, int&gt;&amp; end) { // Check and note down sizes map_y = map.size(); if(map_y) { map_x = map[0].size(); } if(map_x == 0 || map_y == 0) { throw std::invalid_argument{"The map is invalid!\n"}; } // Create a map of Points for(int i = 0; i &lt; map_y; i++) { map_v.push_back(std::vector&lt;Point&gt;(map_x)); for(int j = 0; j &lt; map_x; j++) { map_v[i][j] = Point(j, i, map[i][j]); } } // Assign start and end start_v = &amp;map_v[start.first][start.second]; end_v = &amp;map_v[end.first][end.second]; if(!is_valid(start_v -&gt; x(), start_v -&gt; y())) { throw std::invalid_argument{"Start point is invalid!\n"}; } if(!is_valid(end_v -&gt; x(), end_v -&gt; y())) { throw std::invalid_argument{"End point is invalid!\n"}; } } // Check if a Point lies within boundaries of the map and if it is free space bool Astar::is_valid(int x, int y) { if(x &gt;= 0 &amp;&amp; x &lt; map_x &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; map_y &amp;&amp; map_v[y][x].val() == 0) { return true; } return false; } // Calculate Manhattan distance as a hueristic double Astar::manhattan(Point* p) { return std::abs(p -&gt; x() - end_v -&gt; x()) + std::abs(p -&gt; y() - end_v -&gt; y()); } // Perform the actual search bool Astar::search() { // Create a frontier and insert the start node std::set&lt;Point*&gt; frontier; end_v -&gt; set_h(0); start_v -&gt; set_g(0); start_v -&gt; set_h(this -&gt; manhattan(start_v)); frontier.insert(start_v); // As long as there are points in the frontier or until the end point is reached, the search continues while(!frontier.empty()) { // Find the Point with minimum value of f_v auto curr_point = *(std::min_element(frontier.begin(), frontier.end(), [](const Point* p1, const Point* p2){return p1 -&gt; f() &lt; p2 -&gt; f();})); // If it is the end point, return success if(*curr_point == *end_v) { std::cout &lt;&lt; "Success!\n"; return true; } // Otherwise, find the eligible neighbors and insert them into frontier int x = curr_point -&gt; x(); int y = curr_point -&gt; y(); std::vector&lt;Point*&gt; neighbors; if(this -&gt; is_valid(x, y - 1)) { neighbors.push_back(&amp;map_v[y - 1][x]); } if(this -&gt; is_valid(x, y + 1)) { neighbors.push_back(&amp;map_v[y + 1][x]); } if(this -&gt; is_valid(x + 1, y)) { neighbors.push_back(&amp;map_v[y][x + 1]); } if(this -&gt; is_valid(x - 1, y)) { neighbors.push_back(&amp;map_v[y][x - 1]); } // Add neighbors to frontier if their g value is higher than necessary // Update g, h (and f). Also set their parent. for(auto&amp; neighbor : neighbors) { if(neighbor -&gt; g() &gt; curr_point -&gt; g() + 1) { neighbor -&gt; set_g(curr_point -&gt; g() + 1); neighbor -&gt; set_h(this -&gt; manhattan(neighbor)); neighbor -&gt; set_parent(curr_point); frontier.insert(neighbor); } } // Remove the current Point frontier.erase(curr_point); } // If end point is not reached, report failure std::cout &lt;&lt; "Failure!\n"; return false; } // Retrieve the path and return it std::vector&lt;Point*&gt; Astar::path() { auto p1 = end_v; while(p1 != nullptr) { path_v.insert(path_v.begin(), p1); p1 = p1 -&gt; parent(); } return path_v; } int main() { // Map of the environment to navigate std::vector&lt;std::vector&lt;int&gt;&gt; mv = {{1, 0, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 1, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 0, 0}, {1, 0, 1, 0, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 0, 0, 1, 1, 0}, {0, 1, 0, 1, 0, 0, 0, 1}}; // The start and end points std::pair&lt;int, int&gt; start = {5, 2}; std::pair&lt;int, int&gt; end = {2, 5}; // Create search object and perform search Astar astar1{mv, start, end}; auto success = astar1.search(); // If search is successful, print the path if(success) { auto path = astar1.path(); std::cout &lt;&lt; "The result path: \n"; for(auto p : path) { std::cout &lt;&lt; "{ " &lt;&lt; p -&gt; y() &lt;&lt; ", " &lt;&lt; p -&gt; x() &lt;&lt; "}" &lt;&lt; "\t"; } std::cout &lt;&lt; "\n"; } return 0; } </code></pre> <p>1) In the above code, the user/ main provides input map via a <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code> and it is converted to <code>std::vector&lt;std::vector&lt;Point&gt;&gt;</code>. The <code>Point</code> is a user defined class capable of handling a lot of operations. In the above code, the class <code>Astar</code> is responsible for conversion of the map into required type. Is this bad design? How can I can do it more elegantly without loosing the advantages of <code>Point</code> class? Suggestions for better data structures are welcome.</p> <p>2) Comments on operator overloading, copy constructor etc. used in <code>Point</code>.</p> <p>3) Are there any parts that are very inefficient? Any other suggestions, advice or improvements?</p>
[]
[ { "body": "<p>A <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code> is an inefficient way to store a 2-dimensional array. Unfortunately, there is nothing in the standard C++ library that gives you an easy and safe 2-dimensional array.</p>\n\n<p>However, in your case, in <code>main()</code> you could easily c...
{ "AcceptedAnswerId": "205509", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T15:28:39.033", "Id": "205498", "Score": "3", "Tags": [ "c++", "object-oriented", "constructor", "overloading", "a-star" ], "Title": "C++ - Astar search algorithm using user defined class" }
205498
<p>Compute the prime factors of a given natural number. A prime number is only evenly divisible by itself and 1. Note that 1 is not a prime number.</p> <p>My solution will catch every prime up to and including 896803. This is the fastest solution I could come up with. I know that hard code can only go so far.</p> <pre><code>def prime_factors(n): factors = [] found_last_factor = False if n == 1: return factors if is_prime(n): return [n] while found_last_factor == False: for f in range(2, int(n/2+1)): if n % f == 0 and is_prime(f): n /= f factors.append(f) if is_prime(n): factors.append(n) found_last_factor = True break return sorted(factors) def is_prime(f: int) -&gt; bool: if f is 1: return False for n in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947): if f == n: return True elif f % n == 0: return False elif f / n &lt; n: return True </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T20:49:35.137", "Id": "396444", "Score": "1", "body": "A test case that can be timed would be good, when you care about the fastest code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T19:36:49.520", ...
[ { "body": "<p><code>is_prime()</code> can terminate without returning a value (returning <code>None</code>) if the input is large, but not divisible by a prime under 1000. You should handle that explicitly (perhaps raise an exception).</p>\n\n<p>Bug? <code>prime_factors(45)</code> will return <code>[3,5]</code...
{ "AcceptedAnswerId": "205517", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T19:59:13.947", "Id": "205511", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "primes" ], "Title": "Prime factorization program" }
205511
<p>I'm new to the filesystem from Laravel, but I need an upload script that allows users to upload images to my server. However, i'm concerned about securety, so I thought why not ask for advice, because there aren't much reverences about that big topic of securety.</p> <p>Basicly, this is how I check the user upload and how I upload the file:</p> <p>My request Class: </p> <pre><code> return [ 'profile_picture' =&gt; 'image', ]; </code></pre> <p>My check if the image is actually an image and not some bad maleware:</p> <pre><code>function checkIfImageIsAllowed($file) { $allowedMimes = [ 'image/jpeg', 'image/jpg', 'image/png' ]; $allowedExtensions = [ 'jpg', 'JPG', 'jpeg', 'png' ]; $allowedMaxSize = 2000000; if(!in_array($file-&gt;getClientOriginalExtension(), $allowedExtensions) || !in_array($file-&gt;getMimeType(), $allowedMimes) || $file-&gt;getSize() &gt; $allowedMaxSize) { return false; } return true; } </code></pre> <p>And than I upload the file: </p> <pre><code>$path = $request-&gt;file('profile_picture')-&gt;store('UserUpload/Images'); </code></pre> <p>This is how I display the Image: </p> <pre><code> $images = \App\Image::where('uuid', $uuid)-&gt;firstOrFail(); $path = $images-&gt;path; $image = Storage::get($path); $response = Response::make($image, 200); $response-&gt;header("Content-Type", $images-&gt;memeType); return $response; </code></pre> <p>What are your thoughts about this? Do you think this is secure enough? Or do you have some improvement for this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T10:38:51.487", "Id": "396477", "Score": "0", "body": "`image/jpg` mime type doesn't exist. Both extensions [use](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types) `image/jpeg`. ...
[ { "body": "<p>The code can be made simpler by using some built-in Laravel validation rules:</p>\n\n<ul>\n<li><p>Validation of MIME types and extension can already be done in Laravel.</p>\n\n<p>With the rule <code>image</code> as you have for <code>profile_picture</code>, you're already validating if the uploade...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-13T21:27:59.010", "Id": "205513", "Score": "2", "Tags": [ "php", "image", "http", "laravel", "network-file-transfer" ], "Title": "Laravel image upload" }
205513
<p>I am trying a simple Hash Map implementation in c++. I have used <a href="https://medium.com/@aozturk/simple-hash-map-hash-table-implementation-in-c-931965904250" rel="nofollow noreferrer">this</a> and <a href="http://www.algolist.net/Data_structures/Hash_table/Simple_example" rel="nofollow noreferrer">this</a> as reference. The implemented design uses a class <code>HashEntry</code> to manage individual key-value pair. The class <code>HashMap</code> handles the map itself. The map has functions to insert(<code>put</code>) a key-value pair, to retrieve(<code>get</code>) value based on a key and to erase(<code>erase</code>) a key-value pair. It also keeps track of its <code>size</code> and <code>capacity</code>. Here is the commented code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;vector&gt; #include &lt;cstddef&gt; #include &lt;stdexcept&gt; #include &lt;climits&gt; // Class for individual entries of key-value pair class HashEntry { int key_v; int val_v; // The smart pointer to handle multiple keys with same hash value. // This will be used to create a linkedlist. std::shared_ptr&lt;HashEntry&gt; next_v; public: HashEntry(int key, int val) : key_v{key}, val_v{val} {} int key() const { return key_v; } int val() const { return val_v; } std::shared_ptr&lt;HashEntry&gt; next() const { return next_v; } void set_val(int val) { val_v = val; } void set_next(std::shared_ptr&lt;HashEntry&gt; next) { next_v = next; } }; // Class for the Hash Map class HashMap { std::vector&lt;std::shared_ptr&lt;HashEntry&gt;&gt; map_v; std::size_t capacity_v{0}; std::size_t size_v{0}; public: HashMap(std::size_t); std::size_t hash_func(int); std::size_t size() const; void put(int, int); int get(int); bool erase(int); }; HashMap::HashMap(std::size_t capacity) { capacity_v = capacity; map_v.resize(capacity_v); } // The hashing function std::size_t HashMap::hash_func(int key) { return key % capacity_v; } std::size_t HashMap::size() const { return size_v; } // The function to insert key-value pair void HashMap::put(int key, int val) { // If capacity is reached, throw exception if(size_v == capacity_v) { throw std::length_error{"Capacity exceeded!\n"}; } std::size_t hash_value = hash_func(key); // If the hash_value has never been set before, use that space // for key-value pair. Otherwise, add to the list. if(map_v[hash_value] == nullptr) { map_v[hash_value] = std::make_shared&lt;HashEntry&gt;(key, val); } else { auto node = map_v[hash_value]; std::shared_ptr&lt;HashEntry&gt; pre = nullptr; while(node) { if(node-&gt;key() == key) { node-&gt;set_val(val); return; } pre = node; node = node-&gt;next(); } pre-&gt;set_next(std::make_shared&lt;HashEntry&gt;(key, val)); } size_v++; } // Retrieve value based on key int HashMap::get(int key) { auto hash_value = hash_func(key); auto node = map_v[hash_value]; // If node is not set, nothing to retrieve. // Otherwise, check the key and if required, the associated list. // If not found, report the issue. if(node == nullptr) { std::cout &lt;&lt; "Key not found! Returning INT_MIN for: " &lt;&lt; key &lt;&lt; "\n"; return INT_MIN; } if(node-&gt;next() == nullptr &amp;&amp; node-&gt;key() == key) { return node-&gt;val(); } else { while(node) { if(node-&gt;key() == key) { return node-&gt;val(); } node = node-&gt;next(); } } std::cout &lt;&lt; "Key not found! Returning INT_MIN for: " &lt;&lt; key &lt;&lt; "\n"; return INT_MIN; } // Remove key-value pair based on key bool HashMap::erase(int key) { auto hash_value = hash_func(key); // If no value is set against hash value, there is nothing to erase. // Otherwise, check if keys match and if yes, proceed to erase. // Otherwise, check the list for a match and if there is a match, // proceed to erase. // Otherwise, return false. if(map_v[hash_value] == nullptr) { return false; } else if(map_v[hash_value]-&gt;key() == key) { map_v[hash_value] = map_v[hash_value]-&gt;next(); size_v--; return true; } else if(map_v[hash_value]-&gt;next()) { auto pre = map_v[hash_value]; auto node = map_v[hash_value]-&gt;next(); while(node) { if(node-&gt;key() == key) { pre-&gt;set_next(node-&gt;next()); size_v--; return true; } pre = node; node = node-&gt;next(); } } return false; } int main() { HashMap hm1{10}; std::cout &lt;&lt; "Size: " &lt;&lt; hm1.size() &lt;&lt; "\n"; for(int i = 0; i &lt; 10; i++) { hm1.put(i, i + 10); } std::cout &lt;&lt; "Size: " &lt;&lt; hm1.size() &lt;&lt; "\n"; std::cout &lt;&lt; "Get: " &lt;&lt; hm1.get(6) &lt;&lt; "\n"; std::cout &lt;&lt; "Erase: " &lt;&lt; std::boolalpha &lt;&lt; hm1.erase(6) &lt;&lt; "\n"; std::cout &lt;&lt; "Size: " &lt;&lt; hm1.size() &lt;&lt; "\n"; // Check the output of get() after key is erased std::cout &lt;&lt; "Get: " &lt;&lt; hm1.get(6) &lt;&lt; "\n"; // Try adding a key which will have same hash_value as another key // Also try retrieving both keys hm1.put(15, 25); std::cout &lt;&lt; "Size: " &lt;&lt; hm1.size() &lt;&lt; "\n"; std::cout &lt;&lt; "Get: " &lt;&lt; hm1.get(15) &lt;&lt; "\n"; std::cout &lt;&lt; "Get: " &lt;&lt; hm1.get(5) &lt;&lt; "\n"; // Erase a pair existing in the list and see how all keys in the list behave. std::cout &lt;&lt; "Erase: " &lt;&lt; std::boolalpha &lt;&lt; hm1.erase(5) &lt;&lt; "\n"; std::cout &lt;&lt; "Size: " &lt;&lt; hm1.size() &lt;&lt; "\n"; std::cout &lt;&lt; "Get: " &lt;&lt; hm1.get(5) &lt;&lt; "\n"; std::cout &lt;&lt; "Get: " &lt;&lt; hm1.get(15) &lt;&lt; "\n"; return 0; } </code></pre> <p><strong>Questions:</strong></p> <p>1) Is the implementation correct for an open hashing (closed addressing) hash map?</p> <p>2) The function <code>get</code> returns an <code>INT_MIN</code> if it has no other choice. The other possible ways to handle this scenario could be using <code>std::optional</code>, throw an exception, change the function to not return anything, or return a bool. Is there any other smarter/ more elegant way?</p> <p>3) Any better suggestions for <code>hash_func</code>. Is there any good reading material on how to select a good hashing function or is it just a matter of experience?</p> <p>If possible, kindly provide general reviews and suggestions. Thank you! </p>
[]
[ { "body": "<p>Good for the first try, but there are a lot of things to improve.</p>\n\n<h2>Too many indirections</h2>\n\n<p><code>std::shared_ptr</code> -> <code>std::unique_ptr</code>, because no multithreading is perceived in the usage cases, <code>std::unique_ptr</code> is much more lightweight, albeit being...
{ "AcceptedAnswerId": "205548", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T00:31:34.340", "Id": "205520", "Score": "0", "Tags": [ "c++", "hash-map", "pointers" ], "Title": "C++ - Hash map implementation using smart pointers" }
205520
<p>In the code below, I am building a NODE_ENV-sensitive config object from environment variables.</p> <pre><code>let username let password let cluster let hosts let databaseName let replicaSet if (process.env.NODE_ENV === 'production') { username = process.env.ATLAS_HUB_USERNAME password = process.env.ATLAS_HUB_PASSWORD cluster = process.env.ATLAS_CLUSTER hosts = process.env.ATLAS_HOSTS databaseName = process.env.ATLAS_DATABASE replicaSet = process.env.ATLAS_REPLICA_SET } else { username = process.env.MONGO_HUB_USERNAME password = process.env.MONGO_HUB_PASSWORD cluster = process.env.MONGO_CLUSTER hosts = process.env.MONGO_HOSTS databaseName = process.env.MONGO_DATABASE replicaSet = process.env.MONGO_REPLICA_SET } const config = { username, password, cluster, hosts, databaseName, replicaSet } </code></pre> <p>In this new age of fancy spread and rest operators, I hate polluting my files with code like this which repeat the same variable name multiple times and uses <code>let</code> instead of <code>const</code> for the wrong reasons, all for something simple and frequent. I could use the ternary operator to get something way better:</p> <pre><code>const config = { username: process.env.NODE_ENV === 'production' ? process.env.ATLAS_HUB_USERNAME : process.env.MONGO_HUB_USERNAME, password: process.env.NODE_ENV === 'production' ? process.env.ATLAS_HUB_PASSWORD : process.env.MONGO_HUB_PASSWORD, cluster: process.env.NODE_ENV === 'production' ? process.env.ATLAS_CLUSTER : process.env.MONGO_CLUSTER, hosts: process.env.NODE_ENV === 'production' ? process.env.ATLAS_HOSTS : process.env.MONGO_HOSTS, databaseName: process.env.NODE_ENV === 'production' ? process.env.ATLAS_DATABASE : process.env.MONGO_DATABASE, replicaSet: process.env.NODE_ENV === 'production' ? process.env.ATLAS_REPLICA_SET : process.env.MONGO_REPLICA_SET } </code></pre> <p>But even this seems one step short of what modern js should be able to do. I'd now like to get rid of the repeated <code>process.env.NODE_ENV</code>, I just can't figure out how (apart from creating a new const with a shorter name). If I had a magic wand, I'd write something along the following lines:</p> <pre><code>const config = ({ username: [process.env.MONGO_HUB_USERNAME, process.env.ATLAS_HUB_USERNAME], password: [process.env.MONGO_HUB_PASSWORD, process.env.ATLAS_HUB_PASSWORD], cluster: [process.env.MONGO_CLUSTER, process.env.ATLAS_CLUSTER], hosts: [process.env.MONGO_HOSTS, process.env.ATLAS_HOSTS], databaseName: [process.env.MONGO_DATABASE, process.env.ATLAS_DATABASE], replicaSet: [process.env.MONGO_REPLICA_SET, process.env.ATLAS_REPLICA_SET] }).*[new Number(process.env.NODE_ENV === 'production')] </code></pre> <p>But I don't, and it's not even all that great, sooo, any suggestions?</p> <p>I thought of using a function, like below, but this just introduces another dependency you need to internalize for a simple batch conditional assignment operation... And if the function is in-line, there is duplication across files and it's frankly just confusing.</p> <pre><code>function fromEach (obj, key) { const final = {} Object.keys(obj).forEach((k) =&gt; { final[k] = obj[k][key] }) return final } const config = fromEach({ username: [process.env.MONGO_HUB_USERNAME, process.env.ATLAS_HUB_USERNAME], password: [process.env.MONGO_HUB_PASSWORD, process.env.ATLAS_HUB_PASSWORD], cluster: [process.env.MONGO_CLUSTER, process.env.ATLAS_CLUSTER], hosts: [process.env.MONGO_HOSTS, process.env.ATLAS_HOSTS], databaseName: [process.env.MONGO_DATABASE, process.env.ATLAS_DATABASE], replicaSet: [process.env.MONGO_REPLICA_SET, process.env.ATLAS_REPLICA_SET] }, new Number(process.env.NODE_ENV === 'production')) </code></pre> <p><strong>Note:</strong> I use <code>new Number(process.env.NODE_ENV === 'production')</code> in these examples, but I don't like it, feel free to propose something better!</p>
[]
[ { "body": "<p>Ideally, I would suggest two changes the the overall design:</p>\n\n<ul>\n<li>the environment variable names could have one consistent prefix, e.g. <code>MONGO_</code> and <code>ATLAS_</code></li>\n<li>the keys of the config object could match the environment variable names, e.g. <code>databaseNam...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T01:33:19.413", "Id": "205521", "Score": "2", "Tags": [ "javascript", "node.js", "configuration" ], "Title": "Node.js configuration object based on environment variables" }
205521
<p>I enhanced the my daughter's bed light to IoT. Specifically I can turn the light on/off remotely and there is a timer &amp; alarm function. All of this is implemented with a <a href="https://docs.particle.io/guide/getting-started/intro/photon/" rel="nofollow noreferrer">Particle Photon</a>.</p> <p>This review is split in two parts, where this part discusses the C++ firmware application and <a href="https://codereview.stackexchange.com/questions/205523/simple-web-interface-to-control-embedded-device">this question the html/js gui</a>. As I'm not seasoned in either language I mainly look for some general feedback about code quality.</p> <p>A few comments about the source:</p> <ul> <li>The language itself is C++11 without a few features (for example tryCatch)</li> <li>The code flow is as follows call <code>setup</code> once and then <code>loop</code> repeatedly. </li> <li><code>StringStream</code> should mimik <code>std::stringstream</code> with lower memory footprint.</li> <li><code>String</code> is probably best described as <code>char[]</code> with bells and whistles.</li> <li>Parsing: I'm fine with setting default <code>0</code> in case of wrong input - the only thing I cannot accept is a crash of the application.</li> </ul> <h1>wolke.ino</h1> <pre><code>#include "Particle.h" #include "application.h" #include "stream.h" #include &lt;cstdint&gt; /***************************************************************** * LED * *****************************************************************/ struct LED { pin_t pin = TX; bool active = false; int32_t brightness = 255; void on() { active = true; analogWrite(pin, brightness); }; void off() { active = false; analogWrite(pin, 0); } } led; StringStream&amp; operator&lt;&lt;(StringStream &amp;ss, const LED &amp;led) { ss &lt;&lt; "{\"name\":\"led\","; ss &lt;&lt; "\"active\":" &lt;&lt; led.active; ss &lt;&lt; ",\"read\":" &lt;&lt; led.brightness &lt;&lt; "}"; return ss; } int led_toggle(String cmd) { if (led.active) { led.off(); } else { led.on(); } return 0; } int set_brightness(String cmd) { led.brightness = cmd.toInt(); led.on(); return 0; } /***************************************************************** * Timer * *****************************************************************/ struct TimerClass { int32_t initial_value = 3600; int32_t t0 = 0; bool active = 0; void start() { t0 = Time.now(); active = true; }; int32_t remainder() const { return initial_value + t0 - Time.now(); }; void check() { if (active &amp;&amp; (remainder() &lt; 0)) { active = false; led.on(); } }; } timer; StringStream&amp; operator&lt;&lt;(StringStream &amp;ss, const TimerClass &amp;timer) { ss &lt;&lt; "{\"name\":\"timer\","; ss &lt;&lt; "\"active\":" &lt;&lt; timer.active; ss &lt;&lt; ",\"read\":"; if (timer.active) { ss &lt;&lt; timer.remainder(); } else { ss &lt;&lt; timer.initial_value; } ss &lt;&lt; "}"; return ss; } int timer_toggle(String cmd) { if (timer.active) { timer.active = false; } else { timer.start(); } return 0; } int set_timer(String cmd) { timer.initial_value = cmd.toInt(); timer.start(); return 0; } /**************************************************************** * Time * ****************************************************************/ struct MyTimeClass { int32_t shift = -7; bool active = 1; int32_t hour() const { int32_t hour = Time.hour() + shift * active; if (hour &gt;= 24) { hour -= 24; } if (hour &lt;= 0) { hour += 24; } return hour; }; } local_time; StringStream&amp; operator&lt;&lt;(StringStream &amp;ss, const MyTimeClass &amp;local_time) { ss &lt;&lt; "{\"name\":\"time\","; ss &lt;&lt; "\"active\":" &lt;&lt; local_time.active; ss &lt;&lt; ",\"read\":\"" &lt;&lt; local_time.hour() &lt;&lt; ":"; minute_print(ss, Time.minute()); ss &lt;&lt; "\"}"; return ss; } int time_toggle(String cmd) { local_time.active ^= true; return 0; } int set_shift(String cmd) { local_time.shift = cmd.toInt(); return 0; } void minute_print(StringStream &amp;ss, int32_t min) { // Complicated form to print %02d if (min &lt; 10) { ss &lt;&lt; int32_t(0); } ss &lt;&lt; min; } /***************************************************************** * Alarm * *****************************************************************/ struct Alarm { int32_t min = 0; int32_t hour = 0; bool active = false; void check() { if (active &amp;&amp; (Time.minute() == min) &amp;&amp; (local_time.hour() == hour)) { led.on(); } }; } alarm; StringStream&amp; operator&lt;&lt;(StringStream &amp;ss, const Alarm &amp;alarm) { ss &lt;&lt; "{\"name\":\"alarm\","; ss &lt;&lt; "\"active\":" &lt;&lt; alarm.active; ss &lt;&lt; ",\"read\":\"" &lt;&lt; alarm.hour &lt;&lt; ":"; minute_print(ss, alarm.min); ss &lt;&lt; "\"}"; return ss; } int alarm_toggle(String cmd) { alarm.active ^= true; return 0; } String CMD; int set_alarm(String cmd) { CMD = cmd; int pos = cmd.indexOf(":"); if (pos == -1) { return 1; } else { alarm.hour = cmd.substring(0, pos).toInt(); alarm.min = cmd.substring(pos + 1).toInt(); alarm.active = true; } return 0; } /**************************************************************** * Main * ****************************************************************/ String STATUS; StringStream ss; void setup() { pinMode(led.pin, OUTPUT); Particle.function("led_toggle", led_toggle); Particle.function("led_value", set_brightness); Particle.function("timer_toggle", timer_toggle); Particle.function("timer_value", set_timer); Particle.function("time_toggle", time_toggle); Particle.function("time_value", set_shift); Particle.function("alarm_toggle", alarm_toggle); Particle.function("alarm_value", set_alarm); Particle.variable("status", STATUS); Particle.variable("cmd", CMD); } void loop() { delay(10); timer.check(); alarm.check(); ss.str.clear(); ss &lt;&lt; "[" &lt;&lt; led; ss &lt;&lt; "," &lt;&lt; alarm; ss &lt;&lt; "," &lt;&lt; local_time; ss &lt;&lt; "," &lt;&lt; timer &lt;&lt; "]"; STATUS = ss.str.c_str(); } </code></pre> <h1>stream.h</h1> <pre><code>#ifndef STREAM_H #define STREAM_H #include &lt;string&gt; #include &lt;stdio.h&gt; #include &lt;cstdint&gt; #include &lt;cstring&gt; #include &lt;cinttypes&gt; /***************************************************************** * StringStream is a poor mans std::stringstream which can be used * for easy string concation. *****************************************************************/ struct StringStream { static const size_t MIN_CAPACITY = 100; static const size_t N_BUFFER = 20; std::string str; char buffer[N_BUFFER]; StringStream(); void clear(); StringStream&amp; operator&lt;&lt;(std::string txt); StringStream&amp; operator&lt;&lt;(const char *txt); StringStream&amp; operator&lt;&lt;(char value); StringStream&amp; operator&lt;&lt;(double value); StringStream&amp; operator&lt;&lt;(int32_t value); StringStream&amp; operator&lt;&lt;(bool value); }; #endif </code></pre> <h1>stream.cpp</h1> <pre><code>#include "stream.h" StringStream::StringStream() { str.reserve(MIN_CAPACITY); } StringStream&amp; StringStream::operator&lt;&lt;(std::string txt) { str.append(txt); return *this; } StringStream&amp; StringStream::operator&lt;&lt;(const char* txt) { str.append(txt); return *this; } StringStream&amp; StringStream::operator&lt;&lt;(char value) { str.append(1, value); return *this; } StringStream&amp; StringStream::operator&lt;&lt;(double value) { memset(buffer, '\0', N_BUFFER); snprintf(buffer, N_BUFFER, "%e", value); str.append(buffer, std::char_traits&lt;char&gt;::length(buffer)); return *this; } StringStream&amp; StringStream::operator&lt;&lt;(int32_t value) { memset(buffer, '\0', N_BUFFER); snprintf(buffer, N_BUFFER, "%" PRId32, value); str.append(buffer, std::char_traits&lt;char&gt;::length(buffer)); return *this; } StringStream&amp; StringStream::operator&lt;&lt;(bool value) { str.append(1, value ? '1' : '0'); return *this; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T08:54:05.703", "Id": "396472", "Score": "0", "body": "I don't have time to do proper review, but I can suggest you to split your first file into multiple smaller ones instead of doing \"sections\" - it will make it easier to find st...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T04:54:27.820", "Id": "205522", "Score": "1", "Tags": [ "c++", "c++11", "timer", "embedded" ], "Title": "C++ embedded application to control a light with a timer" }
205522
<p>Made some adjustments to the previous code thanks to the helpful and thoughtful review by @SergeBallesta, @TobySpeight, @G.Sliepen, and @Edward.</p> <p>Problem statement: This program should ask for the total number of shops that will be visited. At each shop, ask for the number of ingredients that need to be purchases. For each ingredient, ask for the price. Keep track of the total for the order so that you can write it down before leaving the shop. This program should also track with order was the cheapest and which shop the cheapest order was at.</p> <p>List of adjustments made:</p> <ul> <li>Code formatting</li> <li>Variable declarations moved into smaller scopes, e.g., made loop index variables local to the loops themselves</li> <li>Input validation</li> <li>Used integers for money instead of floating-point</li> <li>Used return instead of exit() if possible</li> <li>Eliminated unnecessary arrays as much my ignorance allowed me to</li> <li>Avoided size mistakes when allocating by using the sizeof the (pointed) object and not its type</li> </ul> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;ctype.h&gt; int validate_positive_integer(char *input) { char *p; long result; result = strtol(input, &amp;p, 10); while (true) { if (input[0] != '\n' &amp;&amp; result &gt; 0 &amp;&amp; result &lt; 100 &amp;&amp; (*p == '\n' || *p == '\0')) break; else { printf("Invalid input!\nPlease try again: "); result = 0; break; } } return result; } int * validate_real_positive(char *input) { char *p; char *q; long integer_part, fractional_part; int decimal_index = strcspn(input, "."); int *arr = (int*)calloc(2, sizeof(arr)); if (!arr) { fprintf(stderr, "Memory aldecimal_index failure!\n"); exit(1); } while (true) { if (decimal_index == 0) { fractional_part = strtol(input + 1, &amp;p, 10); if (input[decimal_index] != '\n' &amp;&amp; fractional_part &gt; 0 &amp;&amp; fractional_part &lt; 100 &amp;&amp; (*p == '\0' || *p == '\n')) { *arr = 0; *(arr + 1) = fractional_part; break; } else { printf("Invalid input!\nPlease try again: "); *arr = -1; *(arr + 1) = -1; break; } } if (decimal_index &gt; 0) { integer_part = strtol(input, &amp;p, 10); fractional_part = strtol(input + (decimal_index + 1), &amp;q, 10); if (input[0] != '\n' &amp;&amp; integer_part &gt;= 0 &amp;&amp; integer_part &lt; 10000 &amp;&amp; fractional_part &gt;= 0 &amp;&amp; fractional_part &lt; 100 &amp;&amp; ( (*p == '.') &amp;&amp; (*q == '\n') )) { *arr = integer_part; *(arr + 1) = fractional_part; break; } else { printf("Invalid input!\nPlease try again: "); *arr = -1; *(arr + 1) = -1; break; } } else { printf("Invalid input!\nPlease try again: "); } } return arr; free(arr); } int read_positive_integer(const char *prompt) { printf ("%s", prompt); char line[100]; int positive_integer; positive_integer = 0; while (positive_integer == 0) { fgets(line, sizeof(line), stdin); positive_integer = validate_positive_integer(line); } return positive_integer; free(line); } int* read_real_positive(const char *prompt) { printf ("%s", prompt); int *arr = (int*)calloc(2, sizeof(arr)); if (!arr) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } char line[100]; int integer_part; int fractional_part; integer_part = -1; fractional_part = -1; while (integer_part == -1 || fractional_part == -1) { fgets (line, sizeof(line), stdin); arr = validate_real_positive(line); integer_part = arr[0]; fractional_part = arr[1]; } return arr; free(arr); } int *find_minimum(int *arr) { int minimum_integer_part = arr[0]; int minimum_fractional_part = arr[1]; int minimum_index = 1; int size_index = 0; int count = 5; while (true) { if (arr[count] == '*') { size_index = count - 1; break; } count++; } int size = arr[size_index]; int len = ((size - 2)/2) - 1; size = ((size - 2)/2) + len; int *arr_return = (int*)calloc(size, sizeof(arr_return)); if (!arr_return) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } arr_return[size - 2] = size; arr_return[size - 1] = '*'; int *minimum_indices = (int*)calloc(len, sizeof(minimum_indices)); if (!minimum_indices) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } for (int m = 1; m &lt; size - len; m++) { if ( ( (m &amp; 1) != 0 ) &amp;&amp; (m + 2 &lt; (size + 1)/2) ) { if ( (arr[m + 1] == minimum_integer_part) &amp;&amp; (arr[m + 2] == minimum_fractional_part) ) minimum_indices[m - 1] = m + 1; else { if ( (arr[m + 1] &lt;= minimum_integer_part) &amp;&amp; (arr[m + 2] &lt; minimum_fractional_part) ) { minimum_integer_part = arr[m + 1]; minimum_fractional_part = arr[m + 2]; minimum_index = m + 1; } } } if ( ( (m &amp; 1) != 0 ) &amp;&amp; (m + 2 &gt;= (size + 1)/2) ) { if ( (arr[m + 3] == minimum_integer_part) &amp;&amp; (arr[m + 4] == minimum_fractional_part) ) minimum_indices[m - 1] = m + 1; else { if ( (arr[m + 3] &lt;= minimum_integer_part) &amp;&amp; (arr[m + 4] &lt; minimum_fractional_part) ) { minimum_integer_part = arr[m + 1]; minimum_fractional_part = arr[m + 2]; minimum_index = m + 1; } } } if ( ( (m &amp; 1) == 0 ) &amp;&amp; (m + 2 &lt; (size + 1)/2) ) { if ( (arr[m + 2] == arr[m]) &amp;&amp; (arr[m + 3] == arr[m + 1]) ) minimum_indices[m - 1] = m + 1; else { if ( (arr[m + 2] &lt;= minimum_integer_part) &amp;&amp; (arr[m + 3] &lt; minimum_fractional_part) ) { minimum_integer_part = arr[m + 2]; minimum_fractional_part = arr[m + 3]; minimum_index = m; } } } if ( ( (m &amp; 1) == 0 ) &amp;&amp; (m + 2 &gt;= (size + 1)/2) ) { if ( (arr[m + 4] == minimum_integer_part) &amp;&amp; (arr[m + 5] == minimum_fractional_part) ) minimum_indices[m - 1] = m + 1; else { if ( (arr[m + 4] &lt;= minimum_integer_part) &amp;&amp; (arr[m + 5] &lt; minimum_fractional_part) ) { minimum_integer_part = arr[m + 2]; minimum_fractional_part = arr[m + 3]; minimum_index = m; } } } } *arr_return = minimum_integer_part; *(arr_return + 1) = minimum_fractional_part; *(arr_return + 2) = minimum_index; for (int i = 0; i &lt; len; i++) { if (minimum_indices[i] != 0) *(arr_return + (i + 3)) = minimum_indices[i]; } for (int j = size - 1; j &gt; 4; j--) { if (arr_return[j - 2] == 0) { arr_return[j - 2] = arr_return[j - 1]; arr_return[j - 1] = arr_return[j]; if (j == (size - 1)) arr_return[j] = 0; if (j &lt; size - 1) { arr_return[j] = arr_return[j + 1]; arr_return[j + 1] = 0; } } } count = 4; while (true) { if (arr_return[count] == '*') { size = count + 1; break; } count++; } *(arr_return + (size - 2)) = size; return arr_return; free(arr_return); free(minimum_indices); } int *find_cheapest_order (const char *prompt) { printf ("%s", prompt); int num_shops = read_positive_integer(""); int *arr = (int*)calloc(2, sizeof(arr)); if (!arr) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } int *arr_sum = (int*)calloc(2*num_shops + 2, sizeof(arr_sum)); if (!arr_sum) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } *(arr_sum + (2*num_shops)) = 2*num_shops + 2; *(arr_sum + (2*num_shops + 1)) = '*'; int *arr_return = (int*)calloc(num_shops + 4, sizeof(arr_return)); if (!arr_return) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } for (int i = 0; i &lt; num_shops; i++) { printf("You are at shop #%d.\n", i + 1); int num_ingredients = read_positive_integer("How many ingredients are needed? "); for (int j = 0; j &lt; num_ingredients; j++) { printf("What is the cost of ingredient %d", j + 1); arr = read_real_positive("? "); *(arr_sum + 2*i) += *arr; *(arr_sum + (2*i + 1)) += *(arr + 1); } if (num_shops == 1) { *arr_return = 1; *(arr_return + 1) = arr_sum[0] + arr_sum[1]/100; *(arr_return + 2) = arr_sum[1]%100; break; } if ( (arr_sum[(2*i + 1)]%100) == 0 ) printf("The total cost at shop #%d is $%d.00\n", i + 1, arr_sum[2*i] + arr_sum[(2*i + 1)]/100); else printf("The total cost at shop #%d is $%d.%d.\n", i + 1, arr_sum[2*i] + arr_sum[(2*i + 1)]/100, arr_sum[(2*i + 1)]%100); if (i == num_shops - 1) { arr_return = find_minimum(arr_sum); } } return arr_return; free(arr); free(arr_sum); free(arr_return); } int main (void) { int *cheapest_order = find_cheapest_order("How many shops to visit? "); int size_location = 0; int count = 4; while (true) { if (cheapest_order[count] == '*') { size_location = count - 1; break; } count++; } int size = cheapest_order[size_location]; int minimum_indices_len = size - 5; int minimum_indices[minimum_indices_len]; if (size &gt; (size - minimum_indices_len)) { for (int m = 0; m &lt; minimum_indices_len; m++) { minimum_indices[m] = cheapest_order[m + 3]; } } if (cheapest_order[1] == 0) { printf("The cheapest order(s) were at shop(s) #%d,", cheapest_order[2]); if (size &gt; (size - minimum_indices_len)) { for (int i = 0; i &lt; minimum_indices_len; i++) { if ( i == minimum_indices_len - 1) { printf(" and #%d,", minimum_indices[i]); } else printf(" #%d,", minimum_indices[i]); } } printf(" The total cost of the cheapest order was $%d.00.", cheapest_order[0]); } else { printf("The cheapest order(s) was/were at shop(s) #%d,", cheapest_order[2]); if (size &gt; (size - minimum_indices_len)) { for (int i = 0; i &lt; minimum_indices_len; i++) { if (i == minimum_indices_len - 1) { printf(" shop #%d.", minimum_indices[i]); } else printf(" #%d,", minimum_indices[i]); } } printf(" The total cost of the cheapest order was $%d.%d.", cheapest_order[0], cheapest_order[1]); } return 0; } </code></pre>
[]
[ { "body": "<p>Whoa there, that's a lot of code for such a simple problem.</p>\n\n<p>As a reader I don't understand what <code>arr</code> in <code>find_minimum</code> is and what each of its elements means. You as the author must document this since it is by no means obvious from the code. It's as if I gave you ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T05:12:03.613", "Id": "205524", "Score": "1", "Tags": [ "c" ], "Title": "Find the cheapest order placed out of all of the stores visited - follow-up #3" }
205524
<p>PostgreSQL, Python 3.5, SQLAlchemy</p> <p>I have a main database which has a journals table containing 30k+ journals. For each journal I have a RSS feed URL, using which I can parse and get new articles. There are some mandatory fields if those are missing for any of the articles then there is a third party API which I can use to retrieve additional info about the article. I need to write a python script which will run continuously and loop through the journals retrieved from main DB multiple times each day.</p> <p>The attributes of the articles retrieved need to be validated before saving in a FeedResponse DB. All the valid articles will be stored in articles table and the failed articles will be saved in error table along with the error message .And eventually only the successful articles will be sent to the main DB.</p> <p>Now I need some help with architecting the solution for this. What I have so far is: There will be multiple worker threads which will retrieve data from main DB and parse the rss feed to retrieve list of articles, then validate the articles and call 3rd party API wherever needed.After cleaning up and validation, it will save all the articles retrieved from that journal in FeedResponse DB.<a href="https://i.stack.imgur.com/P0pkd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P0pkd.png" alt="Flow Chart"></a></p> <p>My Issues:</p> <ul> <li>Not sure if threading is the best way to achieve this or multiprocessing or anything else. I need fast processing but do not want to end up in a deadlock situation.</li> <li>The way I have implemented threading is that efficient or I need to refactor it to break it down.</li> <li>Should I retrieve all journals in a single call and then loop through those in memory or each worker thread should retrieve one from main DB</li> <li>How do I ensure script continues to run and that there are no rogue/blocked threads</li> </ul> <p>For brevity I have only mentioned 2 parsers but there are a couple of other parsers as well.</p> <p><strong>My Implementation</strong></p> <p>I have a Process table in FeedResponse DB which is used to identify which journal needs to be picked up by the worker thread. Schema of the DB is as follows:</p> <pre><code>class Process(Base): __tablename__ = 'process' id = Column(Integer, primary_key=True, autoincrement=True) worker_id = Column(Integer) journal_id = Column(Integer) time_started = Column(DateTime(timezone=True), nullable=True) time_finished = Column(DateTime(timezone=True), nullable=True) is_finished = Column(Boolean) </code></pre> <p>manage_worker.py</p> <pre><code>def start_workers(): count = int(sys.argv[1]) if count &gt; 1: for i in range(0, count): worker = Worker(i) worker_pool.append(worker) else: w = Worker(0, True) worker_pool.append(w) for w in worker_pool: w.start() </code></pre> <p>worker.py</p> <pre><code>class Worker(Thread): def __init__(self, worker_id, run_single=False): self.worker_id = worker_id self.current_job_journal_id = None self.current_job_row_id = None self.current_highest_id = 0 self.is_working = False self.run_single = run_single threading.Thread.__init__(self) def run(self): self.connect_db() #Start a session with both the DBs: main DB and FeedResponseDB self.start_work() def start_work(self): while True: if not self.is_working: self.is_working = True # the max journal id from main DB is assigned to max journal id max_journal_id = self.get_max_journal_id() # tuple of new inserted row id from process table in FeedResponseDB new_process_row_id, new_journal_id = self.create_new_job(max_journal_id[0]) # the current job id is assigned as the new journal id self.current_job_journal_id = new_journal_id self.current_job_row_id = new_process_row_id # journal data is the row from main DB returned when queried by the new journal id (which is the max journal id from main DB) journal_data = self.get_journal_data(new_journal_id) self.parse(journal_data, self.handle_is_finished) def parse(self, journal_data, handle_is_finished): time.sleep(2) articles = RssParser(journal_data.rss_url, journal_data.id) for a in articles: If data_incomplete: #If article data is incomplete Article = ApiParser(a) # update the entry in the list of articles validate_articles(articles) handle_is_finished() def create_new_job(self, max_journal_id, last_call_id=None): if last_call_id is None: # get the latest parse date from FeedResponse DB # get the latest id from the latest parse date from FeedResponse DB max_process = db.session.query(Process).filter(Process.time_started == max_date).first() max_process_journal_id = max_process.journal_id else: max_process_journal_id = 0 else: # if last_call_id has a value, make it the latest process journal id from the table max_process_journal_id = last_call_id # add 1 to the latest process journal id max_process_journal_id += 1 # check if our max journal id is higher than the highest in main db, and if so, reset to 1 if max_process_journal_id &gt; max_journal_id: max_process_journal_id = 1 #insert process in FeedResponse DB new_max_process_id = db.session.execute( ''' INSERT INTO process (worker_id, journal_id, time_started, time_finished, is_finished) SELECT {} as worker_id, CASE WHEN {} &lt;= {} THEN {} ELSE 1 END as journal_id, clock_timestamp() as time_started, null as time_finished, 'FALSE' as is_finished RETURNING id ''' .format(self.worker_id, max_process_journal_id, max_journal_id, max_process_journal_id).first().id return (new_max_process_id, max_process_journal_id) def handle_is_finished(self): # print("FINISHING PARSE PROCESS FOR ROW ID: -------&gt;", self.current_job_row_id) current_process = db..session.query(Process).filter(Process.id == self.current_job_row_id).first() current_process.time_finished = datetime.datetime.now() current_process.is_finished = True self.current_job_journal_id = None self.current_job_row_id = None self.disconnect_db() self.is_working = False </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T05:50:11.587", "Id": "205525", "Score": "3", "Tags": [ "python", "multithreading", "multiprocessing" ], "Title": "Architecture for a parsing tool" }
205525
<p>I'm self-taught in Python and would have a lot of room for improvement. I made this basic Sudoku Solver mainly in order to practice the use of Class creation. I would greatly appreciate any feedback about how I could program any of this in a better way.</p> <pre><code>from math import ceil class Cell(object): def __init__(self, position): #input: position of cell each from 1-81 #output: a Sudoku cell with a row, column and block, a status of blank, #and a list of possible values 1-9 self.position = position self.row = ceil(position/9) self.col = (position - 1) % 9 + 1 self.block = ceil(self.col/3) + ceil(self.row/3) * 3 - 3 self.status = 'blank' self.value = 0 self.possibleValues = [1, 2, 3, 4, 5, 6, 7, 8, 9] def __repr__(self): #print description of cell's current state startText = 'Cell #' + str(self.position) + ', Status: ' + self.status + ', ' if self.status == 'blank': return startText + 'Possible values: ' + str(self.possibleValues) else: return startText + 'Value: ' + str(self.value) def populate_cell(self, status, value): #input: the cell status of 'given' or 'solved' and the cell value #output: set the cell value and status, clear possible values self.value = value self.status = status self.possibleValues = [] class Grid(object): def __init__(self, startingValues): #input: dictionary of starting values {position 1-81 : value 1-9} #positions not given will start blank/zero self.status = 'open' self.solvedCellsCount = 0 self.grid = [] #populate the full grid with blank cells for position in range(81): self.grid.append(Cell(position + 1)) #populate given cells (the starting position of the grid) for position in startingValues: self.grid[position - 1].populate_cell('given', startingValues[position]) self.solvedCellsCount += 1 def __repr__(self): #print 9 x 9 view of Sudoku grid with pipe separators #list to hold the 9 rows gridRows = [] #create 9 row strings and append into gridRows list xCell = 0 for row in range(9): compileRow = '' for col in range(9): compileCell = '|' + str(self.grid[xCell].value) + '|' compileRow = compileRow + compileCell xCell += 1 gridRows.append(compileRow) #print each row string on a new line return '\n'.join(gridRows) def solve(self): #attempt to solve the puzzle #to track whether cells were solved in the current loop (True to enter loop) solvedCells = True loopCount = 0 #continue to loop if cells were solved in the last loop while solvedCells: loopCount += 1 #begin tracker as False solvedCells = False #loop through all cells in grid for compareCell in self.grid: #every non-blank cell takes its turn as the 'compare cell' if compareCell.status != 'blank': #sub-loop through all cells in grid as the 'target cell' for solving for targetCell in self.grid: #if the target cell is blank if targetCell.status == 'blank': #check if the target cell shares its row, column or #block with the compare cell if targetCell.row == compareCell.row or \ targetCell.col == compareCell.col or \ targetCell.block == compareCell.block: #if the compare cell's value is still listed as a #possible value of the target cell, remove it if compareCell.value in targetCell.possibleValues: targetCell.possibleValues.remove(compareCell.value) #loop through all cells in grid for targetCell in self.grid: #every blank cell takes its turn as the target cell to be solved if targetCell.status == 'blank': #if only one possible value remains if len(targetCell.possibleValues) == 1: #solve the cell targetCell.populate_cell('solved', targetCell.possibleValues[0]) #increment the grid's solved cells count self.solvedCellsCount += 1 #set the solved cells tracker to True solvedCells = True #if all 81 cells are solved if self.solvedCellsCount == 81: #set the grid status to solved and end the loop self.status = 'solved' break #print puzzle result if self.status == 'solved': print('Puzzle solved in ' + str(loopCount) + ' loops:') else: print('Solver ran for ' + str(loopCount) + ' loops before reaching a dead end:') print(self) easyPuzzle1875322053 = {5:3, 6:7, 7:8, 11:9, 16:3, 17:5, 18:2, 20:5, 26:7, 28:3, 29:8, 30:2, 31:6, 33:9, 35:4, 38:7, 39:9, 40:4, 42:3, 43:2, 44:6, 47: 4, 49:8, 51:5, 52:9, 53:3, 54:7, 56:3, 62:2, 64:9, 65:2, 66:8, 71:1, 75:6, 76:3, 77:4} myPuzzle = Grid(easyPuzzle1875322053) print('Starting grid:') print(myPuzzle) myPuzzle.solve() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T10:37:49.110", "Id": "396476", "Score": "3", "body": "Can you explain the input format representation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T11:19:23.350", "Id": "396579", "Score": "...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T10:09:50.483", "Id": "205531", "Score": "3", "Tags": [ "python", "object-oriented", "python-3.x", "sudoku" ], "Title": "Amateur Python Sudoku Solver" }
205531
<p><strong>Context</strong>:</p> <p>I'm coding up a simple genetic optimization algorithm from first principles, and have decided to use boolean/binary strings as genes so that I can flip bits on or off as a form of mutation. In order to evaluate the fitness of the solutions that it generates I need to be able to decode the binary strings produced into the integer values that I'm optimizing for. The genetic optimization technique that I'm using returns it's individuals as a list, so I am extracting the integers as follows:</p> <p><strong>Problem</strong>:</p> <p>Take the boolean/binary list...</p> <pre><code>l = [1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1] </code></pre> <p>...split it into 8-bit sublists...</p> <pre><code>[[1, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 0, 1, 0], [0, 0, 1, 1, 1, 0, 1, 1]] </code></pre> <p>...concatenate each sublist into a string...</p> <pre><code>[10100111, 101010, 111011] </code></pre> <p>...convert those strings from binary to decimal...</p> <pre><code>[167, 42, 59] </code></pre> <p>...then scale those integers between 50 and 150...</p> <pre><code>[115, 66, 73] </code></pre> <p><strong>My solution</strong>:</p> <pre><code>[int(int(str(bin), 2)/2.55)+50 for bin in [int(''.join(\ map(str,num))) for num in [l[i:i +8] for i in range(0, len(l), 8)]]] </code></pre> <p>This feels like a very ugly way to go tackle the problem - can anyone come up with a nicer way to go about it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T19:06:23.963", "Id": "396503", "Score": "0", "body": "you need to explain to us how you are implementing this solution, there is not enough context surrounding your code." }, { "ContentLicense": "CC BY-SA 4.0", "Creation...
[ { "body": "<p>The individual steps that you describe in the <em>Problem</em> section are each simple and easy to follow. Yet you write your code in basically a single line. To understand it I had to tear it apart like you did in your \"explanation for humans\":</p>\n\n<pre><code>scaled = [\n int(int(str(bin)...
{ "AcceptedAnswerId": "205536", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T10:47:12.657", "Id": "205532", "Score": "4", "Tags": [ "python", "performance", "strings", "number-systems" ], "Title": "Convert boolean list to list of base10 integers" }
205532
<p>I'm very new to Rust and have tried to write a simple graphQL server with Rust and Postgres. It works, but I have not idea about what's good and what's bad here. I would love someone experimented to read this code.</p> <p><strong>main.rs</strong></p> <pre><code>#![feature(plugin)] #![feature(trace_macros)] #![plugin(rocket_codegen)] extern crate config as rs_config; extern crate postgres; extern crate toml; #[macro_use] extern crate juniper; extern crate juniper_rocket; extern crate r2d2; extern crate r2d2_postgres; extern crate rocket; mod config; mod ctx; mod database; mod graphql; mod routes; mod user; fn main() { let config = config::get(); let ctx = ctx::Ctx { db_pool: database::db_pool(&amp;config), config: config, }; // create a "users" demo table database::uninstall(&amp;ctx); database::install(&amp;ctx); // lancer le serveur web rocket::ignite() .manage(ctx) .manage(graphql::build_schema()) .mount( "/", routes![ routes::post_graphql_handler, routes::get_graphql_handler, routes::graphiql, ], ) .launch(); } </code></pre> <p><strong>routes.rs</strong></p> <pre><code>use ctx::Ctx; use graphql::Schema; use rocket::response::content; use rocket::State; #[get("/")] pub fn graphiql() -&gt; content::Html&lt;String&gt; { juniper_rocket::graphiql_source("/graphql") } #[get("/graphql?&lt;request&gt;")] fn get_graphql_handler( context: State&lt;Ctx&gt;, request: juniper_rocket::GraphQLRequest, schema: State&lt;Schema&gt;, ) -&gt; juniper_rocket::GraphQLResponse { request.execute(&amp;schema, &amp;context) } #[post("/graphql", data = "&lt;request&gt;")] fn post_graphql_handler( context: State&lt;Ctx&gt;, request: juniper_rocket::GraphQLRequest, schema: State&lt;Schema&gt;, ) -&gt; juniper_rocket::GraphQLResponse { request.execute(&amp;schema, &amp;context) } </code></pre> <p><strong>user.rs</strong></p> <pre><code>use ctx::Ctx; #[derive(Debug)] pub struct User { pub id: Option&lt;i32&gt;, pub name: String, pub mail: String, } pub fn get_user_by_id(ctx: &amp;Ctx, id: i32) -&gt; Option&lt;User&gt; { let mut result = None; for row in &amp;ctx .db_connect() .query("SELECT id, name, mail FROM users WHERE id = $1", &amp;[&amp;id]) .expect(&amp;format!( "error searching user with id {:#?}", &amp;id )) { result = Some(User { id: Some(row.get("id")), name: row.get("name"), mail: row.get("mail"), }); } result } pub fn insert_user(ctx: &amp;Ctx, user: &amp;User) -&gt; Result&lt;u64, String&gt; { let rows_affected = ctx .db_connect() .execute( "INSERT INTO users (name, mail) VALUES ($1, $2)", &amp;[&amp;user.name, &amp;user.mail], ) .expect(&amp;format!("error inserting user {:#?}", &amp;user)); if rows_affected &gt; 0 { Ok(rows_affected) } else { Err(String::from( "No rows where affected, insert has probably failed", )) } } </code></pre> <p><strong>config.rs</strong></p> <pre><code>use rs_config::*; use std::collections::HashMap; use std::path::Path; /// get config from Config.toml file /// override its values with a Config.local.toml, if exists pub fn get() -&gt; HashMap&lt;String, String&gt; { let mut settings = Config::default(); settings.merge(File::with_name("Config.toml")).unwrap(); if Path::new("Config.local.toml").exists() { settings .merge(File::with_name("Config.local.toml")) .unwrap(); } let config = settings.try_into::&lt;HashMap&lt;String, String&gt;&gt;().unwrap(); config } </code></pre> <p><strong>ctx.rs</strong></p> <pre><code>use std::collections::HashMap; #[derive(Debug)] pub struct Ctx { pub db_pool: r2d2::Pool&lt;r2d2_postgres::PostgresConnectionManager&gt;, pub config: HashMap&lt;String, String&gt;, } impl Ctx { pub fn db_connect(&amp;self) -&gt; r2d2::PooledConnection&lt;r2d2_postgres::PostgresConnectionManager&gt; { self.db_pool.get().unwrap() } } // allow our ctx to be valid as a Juniper Context. It will be accessible // with ""executor.context()" from our GraphQL resolvers impl juniper::Context for Ctx {} </code></pre> <p><strong>database.rs</strong></p> <pre><code>use ctx::Ctx; use r2d2_postgres::{PostgresConnectionManager, TlsMode}; use std::collections::HashMap; // create a db connection pool pub fn db_pool( config: &amp;HashMap&lt;String, String&gt;, ) -&gt; r2d2::Pool&lt;r2d2_postgres::PostgresConnectionManager&gt; { let dabatabase_uri = config.get("database_uri").unwrap().as_str(); println!( " Connection to database \"{}\" in progress ...", &amp;dabatabase_uri ); let manager = PostgresConnectionManager::new(dabatabase_uri, TlsMode::None).unwrap(); let pool = r2d2::Pool::new(manager).expect("Error connecting to database!"); println!(" Connection to database successful !"); pool } pub fn install(ctx: &amp;Ctx) { println!("✨ Creating users table"); let connect = ctx.db_pool.get().unwrap(); connect .execute( "CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, mail VARCHAR NOT NULL )", &amp;[], ) .expect("Error while creating user table"); } #[allow(dead_code)] pub fn uninstall(ctx: &amp;Ctx) { let connect = ctx.db_pool.get().unwrap(); println!("️ deleting table users"); connect .execute("DROP TABLE IF EXISTS users", &amp;[]) .expect("error while deleting users table"); } </code></pre> <p><strong>graphql.rs</strong></p> <pre><code>use ctx::Ctx; use user::{get_user_by_id, insert_user, User}; use juniper::{FieldError, Value}; /******************* * Field Query *******************/ pub struct Query; graphql_object!(Query: Ctx as "Query" |&amp;self| { description: "Root query object" field Hello() -&gt; &amp;str { "Just saying hello !" } field User(&amp;executor, id: i32) -&gt; Result&lt;User, FieldError&gt; { let user = get_user_by_id(&amp;executor.context(), id); match user { Some(v) =&gt; Ok(v), None =&gt; Err(FieldError::new("User not found", Value::null())), } } }); /******************* * Field Mutations *******************/ pub struct Mutation; graphql_object!(Mutation: Ctx |&amp;self| { description: "Root mutation object" field UserCreate(&amp;executor, user_input: UserInput) -&gt; Result&lt;UserCreate, FieldError&gt; { let user = User { id: None, name: user_input.name, mail: user_input.mail, }; match insert_user(&amp;executor.context(), &amp;user) { Ok(rows_updated) =&gt; Ok(UserCreate { rows_updated: rows_updated as i32, }), Err(message) =&gt; Err(FieldError::new(message, Value::null())), } } }); /******************* * Field User *******************/ // declare custom resolvers for each field of user::User graphql_object!(User: () as "Utilisateur" |&amp;self| { field name() -&gt; &amp;str { self.name.as_str() } field mail() -&gt; &amp;str { self.mail.as_str() } field id() -&gt; Option&lt;i32&gt; { self.id } }); /************************* * UserCreate response object **************************/ #[derive(Debug, GraphQLObject)] pub struct UserCreate { rows_updated: i32, } /************************* * UserCreate argument **************************/ #[derive(Debug, GraphQLInputObject)] pub struct UserInput { pub name: String, pub mail: String, } /************************* * Création du schema **************************/ pub type Schema = juniper::RootNode&lt;'static, Query, Mutation&gt;; pub fn build_schema() -&gt; Schema { Schema::new(Query, Mutation) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T13:37:31.187", "Id": "396484", "Score": "0", "body": "\"It might be too much code for embedding it in the post\" did you test ? looking at your project this look like it's small enough to fit into the character limitation. However t...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T13:12:22.597", "Id": "205538", "Score": "2", "Tags": [ "rust" ], "Title": "Rust web server example with GraphQL, Rocket and Postgres" }
205538
<p>I am solving the "<a href="https://www.codechef.com/SNCKQL19/problems/SPREAD2/" rel="nofollow noreferrer">Spread the Word</a>" problem on CodeChef:</p> <blockquote> <p>Snackdown 2019 is coming! People have started to spread the word and tell other people about the contest. There are <span class="math-container">\$N\$</span> people numbered 1 through <span class="math-container">\$N\$</span>. Initially, only person 1 knows about Snackdown. On each day, everyone who already knows about Snackdown tells other people about it. For each valid <span class="math-container">\$i\$</span>, person <span class="math-container">\$i\$</span> can tell up to <span class="math-container">\$A_i\$</span> people per day. People spread the information among the people who don't know about Snackdown in the ascending order of their indices; you may assume that no two people try to tell someone about Snackdown at the same moment. Each person is only allowed to start telling other people about Snackdown since the day after he/she gets to know about it (person 1 can start telling other people already on day 1). How many days does it take for all people to know about Snackdown?</p> </blockquote> <p>But my code exceeds the given time limit. It solves the problem in 1.01 seconds, but the time limit in there, is 1.00 seconds. I am attaching the code snippet written in C++ below:</p> <pre><code>#include&lt;iostream&gt; using namespace std; int main() { int t,n; cin&gt;&gt;t; for(int i = 0; i&lt;t;i++) { int c = 0,f=0,p=1; cin&gt;&gt;n; int a[n]; for(int i = 0; i&lt;n; i++) cin&gt;&gt;a[i]; f = a[0]; while(p&lt;n) { for(int i = 0; i&lt;f; i++) { p += a[i]; } c++; f = p; } cout&lt;&lt;c; } } </code></pre> <p>It would be a great help if someone modifies the above code into an efficient one!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T05:41:58.427", "Id": "396544", "Score": "2", "body": "A runtime error is not the same as a time-limit-exceeded message from an online judge. Please clarify which is the case." }, { "ContentLicense": "CC BY-SA 4.0", "Crea...
[ { "body": "<ol>\n<li><p>Do not do <code>using namespace std;</code> This is a bad habbit that pollutes your namespace needlessly. You are only using <code>std</code> in exaclty 4 places. Its really easy to be better here.</p></li>\n<li><p>Please use sensible names. Your <code>t</code> is the number of test runs...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T14:56:12.227", "Id": "205543", "Score": "0", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded", "timeout" ], "Title": "\"Spread the Word\" CodeChef challenge" }
205543
<p>I'm working on a password brute-forcer that takes in a password from the user and brute-forces solutions until it finds a match. I was wondering if there is any way to improve performance or readability?</p> <pre class="lang-python prettyprint-override"><code>import itertools import time Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXiuYZ1234567890-_.") Password = input("What is your password?\n") start = time.time() counter = 1 CharLength = 1 for CharLength in range(25): passwords = (itertools.product(Alphabet, repeat = CharLength)) print("\n") print("Currently working on passwords with ", CharLength, " characters.") print("We are currently at ", (counter / (time.time() - start)), "attempts per second.") print("It has been ", time.time() - start, " seconds.") print("We have tried ", counter, " possible passwords.") for i in passwords: counter += 1 i = str(i) i = i.replace("[", "") i = i.replace("]", "") i = i.replace("'", "") i = i.replace(" ", "") i = i.replace(",", "") i = i.replace("(", "") i = i.replace(")", "") if i == Password: end = time.time() timetaken = end - start print("\nPassword found in ", timetaken, " seconds and ", counter, "attempts.") print("That is ", counter / timetaken, " attempts per second.") print("\nThe password is \"%s\"." % i) input("\nPress enter when you have finished.") exit() </code></pre> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T03:02:50.307", "Id": "396527", "Score": "0", "body": "What would this code be used for? It asks for the plain text password, not a hash, and just iterates over all possible strings of length 0 through 24 until it matches what it alr...
[ { "body": "<p>Some recommendations just looking at the style of the code:</p>\n\n<ol>\n<li>It would benefit from being run through <code>pycodestyle</code>, <code>flake8</code> and/or similar tools to be more idiomatic. This would make the code easier to read for anyone familiar with Python.</li>\n<li>Timing co...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T15:05:13.410", "Id": "205544", "Score": "1", "Tags": [ "python" ], "Title": "Python Password Brute-Forcer" }
205544
<p>I wrote a basic template for a vector of arbitrary dimension to be used in a 3D-engine. Most operators make use of C++ template meta programming and instances are implicitly convertible to glm types. It is also possible to build a matrix class on top of this. Suggestions in terms of optimizations, safety, readability etc. are welcome.</p> <p>Here we go:</p> <pre><code>#ifndef Log2VECTOR_H #define Log2VECTOR_H #include &lt;glm/glm.hpp&gt; #include &lt;ostream&gt; namespace Log2 { template&lt;unsigned Dim, typename T&gt; class Vector { public: /** * Constructors */ Vector() = default; Vector(const T&amp; value) { for (unsigned i = 0; i &lt; Dim; i++) { _data[i] = value; } } template&lt;typename ...Args&gt; Vector(Args... args) : _data{ args... } { } /** * Copy constructors */ Vector(const Vector&amp; other) = default; template&lt;typename T1&gt; Vector(const Vector&lt;Dim, T1&gt;&amp; other) { for (unsigned i = 0; i &lt; Dim; i++) { _data[i] = static_cast&lt;T&gt;(other[i]); } } Vector(const Vector&lt;Dim - 1, T&gt;&amp; other, T scalar) { std::memcpy(_data, other.ptr(), sizeof other); _data[Dim - 1] = scalar; } /** * Concatenation */ template&lt;unsigned Dim1&gt; Vector(const Vector&lt;Dim1, T&gt;&amp; v1, const Vector&lt;Dim - Dim1, T&gt;&amp; v2) { std::memcpy(_data, v1.ptr(), sizeof v1); std::memcpy(_data + Dim1, v2.ptr(), sizeof v2); } /** * Member access */ inline auto &amp; operator [] (unsigned index) { return _data[index]; } inline const auto &amp; operator [] (unsigned index) const { return _data[index]; } inline const auto * ptr() const { return _data; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 4, Vector&lt;3, T&gt;&gt;::type xyz() const { return Vector&lt;3, T&gt;(_data[0], _data[1], _data[2]); } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 3, Vector&lt;2, T&gt;&gt;::type xz() const { return Vector&lt;2, T&gt;(_data[0], _data[2]); } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 3, Vector&lt;2, T&gt;&gt;::type xy() const { return Vector&lt;2, T&gt;(_data[0], _data[1]); } inline const auto&amp; x() const { return _data[0]; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 2, T&gt;::type const &amp; y() const { return _data[1]; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 3, T&gt;::type const &amp; z() const { return _data[2]; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 4, T&gt;::type const &amp; w() const { return _data[3]; } inline const auto&amp; r() const { return _data[0]; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 2, T&gt;::type const &amp; g() const { return _data[1]; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 3, T&gt;::type const &amp; b() const { return _data[2]; } template&lt;unsigned D = Dim&gt; inline typename std::enable_if&lt;D &gt;= 4, T&gt;::type const &amp; a() const { return _data[3]; } template&lt;unsigned index&gt; inline const auto&amp; at() const { static_assert(index &lt; Dim, "Invalid index"); return _data[index]; } template&lt;unsigned index&gt; inline auto&amp; at() { static_assert(index &lt; Dim, "Invalid index"); return _data[index]; } /** * Vector/vector calculations */ inline auto operator + (const Vector&amp; other) const { Vector result; ComputeAdd&lt;Dim - 1&gt;::call(*this, other, result); return result; } inline auto operator - (const Vector&amp; other) const { Vector result; ComputeSub&lt;Dim - 1&gt;::call(*this, other, result); return result; } inline auto operator * (const Vector&amp; other) const { Vector result; ComputeMul&lt;Dim - 1&gt;::call(*this, other, result); return result; } inline auto operator / (const Vector&amp; other) const { Vector result; ComputeDiv&lt;Dim - 1&gt;::call(*this, other, result); return result; } inline auto&amp; operator += (const Vector&amp; other) { ComputeAdd&lt;Dim - 1&gt;::call(*this, other, *this); return *this; } inline auto&amp; operator -= (const Vector&amp; other) { ComputeSub&lt;Dim - 1&gt;::call(*this, other, *this); return *this; } inline auto&amp; operator *= (const Vector&amp; other) { ComputeMul&lt;Dim - 1&gt;::call(*this, other, *this); return *this; } inline auto&amp; operator /= (const Vector&amp; other) { ComputeDiv&lt;Dim - 1&gt;::call(*this, other, *this); return *this; } /** * Comparison operators */ inline auto operator == (const Vector&amp; other) const { return ComputeEqual&lt;Dim - 1&gt;::call(*this, other); } inline auto operator != (const Vector&amp; other) const { return ComputeInequal&lt;Dim - 1&gt;::call(*this, other); } inline auto operator &lt; (const Vector&amp; other) const { return ComputeLess&lt;Dim - 1&gt;::call(*this, other); } inline auto operator &gt; (const Vector&amp; other) const { return ComputeGreater&lt;Dim - 1&gt;::call(*this, other); } inline auto operator &lt;= (const Vector&amp; other) const { return ComputeLessOrEqual&lt;Dim - 1&gt;::call(*this, other); } inline auto operator &gt;= (const Vector&amp; other) const { return ComputeGreaterOrEqual&lt;Dim - 1&gt;::call(*this, other); } /** * Vector length */ inline auto length() const { return std::sqrt(length2()); } /** * Squared Vector length */ inline auto length2() const { return dot(*this, *this); } /** * Conversion from/to glm */ inline Vector(const glm::vec&lt;Dim, T&gt;&amp; vec) { std::memcpy(_data, &amp;vec[0], sizeof vec); } inline operator glm::vec&lt;Dim, T&gt;() const { glm::vec&lt;Dim, T&gt; vec; std::memcpy(&amp;vec[0], ptr(), sizeof vec); return vec; } /** * Change in dimension */ template&lt;unsigned N&gt; inline operator Vector&lt;N, T&gt;() const { Vector&lt;N, T&gt; ret; std::memcpy(&amp;ret[0], ptr(), std::min(sizeof ret, sizeof *this)); return ret; } /** * Debug output */ friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Vector&amp; vec) { os &lt;&lt; "["; for (unsigned i = 0; i &lt; Dim; i++) { os &lt;&lt; vec._data[i]; if (i != Dim - 1) { os &lt;&lt; " "; } } os &lt;&lt; "]"; return os; } private: T _data[Dim]; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeAdd { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector &lt;D, Type&gt;&amp; result) { result[index] = a[index] + b[index]; ComputeAdd&lt;index - 1, D, Type&gt;::call(a, b, result); } }; template&lt;unsigned D, typename Type&gt; struct ComputeAdd&lt;0, D, Type&gt; { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector&lt;D, Type&gt;&amp; result) { result[0] = a[0] + b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeSub { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector &lt;D, Type&gt;&amp; result) { result[index] = a[index] - b[index]; ComputeSub&lt;index - 1, D, Type&gt;::call(a, b, result); } }; template&lt;unsigned D, typename Type&gt; struct ComputeSub&lt;0, D, Type&gt; { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector&lt;D, Type&gt;&amp; result) { result[0] = a[0] - b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeMul { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector &lt;D, Type&gt;&amp; result) { result[index] = a[index] * b[index]; ComputeMul&lt;index - 1, D, Type&gt;::call(a, b, result); } }; template&lt;unsigned D, typename Type&gt; struct ComputeMul&lt;0, D, Type&gt; { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector&lt;D, Type&gt;&amp; result) { result[0] = a[0] * b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeDiv { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector &lt;D, Type&gt;&amp; result) { result[index] = a[index] / b[index]; ComputeDiv&lt;index - 1, D, Type&gt;::call(a, b, result); } }; template&lt;unsigned D, typename Type&gt; struct ComputeDiv&lt;0, D, Type&gt; { static inline void call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b, Vector&lt;D, Type&gt;&amp; result) { result[0] = a[0] / b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeEqual { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[index] == b[index] &amp;&amp; ComputeEqual&lt;index - 1, D, Type&gt;::call(a, b); } }; template&lt;unsigned D, typename Type&gt; struct ComputeEqual&lt;0, D, Type&gt; { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[0] == b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeInequal { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[index] != b[index] || ComputeInequal&lt;index - 1, D, Type&gt;::call(a, b); } }; template&lt;unsigned D, typename Type&gt; struct ComputeInequal&lt;0, D, Type&gt; { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[0] != b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeLess { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[index] &lt; b[index] &amp;&amp; ComputeLess&lt;index - 1, D, Type&gt;::call(a, b); } }; template&lt;unsigned D, typename Type&gt; struct ComputeLess&lt;0, D, Type&gt; { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[0] &lt; b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeGreater { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[index] &gt; b[index] &amp;&amp; ComputeGreater&lt;index - 1, D, Type&gt;::call(a, b); } }; template&lt;unsigned D, typename Type&gt; struct ComputeGreater&lt;0, D, Type&gt; { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[0] &gt; b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeLessOrEqual { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[index] &lt;= b[index] &amp;&amp; ComputeLessOrEqual&lt;index - 1, D, Type&gt;::call(a, b); } }; template&lt;unsigned D, typename Type&gt; struct ComputeLessOrEqual&lt;0, D, Type&gt; { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[0] &lt;= b[0]; } }; template&lt;unsigned index, unsigned D = Dim, typename Type = T&gt; struct ComputeGreaterOrEqual { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[index] &gt;= b[index] &amp;&amp; ComputeGreaterOrEqual&lt;index - 1, D, Type&gt;::call(a, b); } }; template&lt;unsigned D, typename Type&gt; struct ComputeGreaterOrEqual&lt;0, D, Type&gt; { static inline auto call(const Vector&lt;D, Type&gt;&amp; a, const Vector&lt;D, Type&gt;&amp; b) { return a[0] &gt;= b[0]; } }; }; using Vec2f = Vector&lt;2, float&gt;; using Vec3f = Vector&lt;3, float&gt;; using Vec4f = Vector&lt;4, float&gt;; using Vec2u = Vector&lt;2, unsigned&gt;; using Vec3u = Vector&lt;3, unsigned&gt;; using Vec4u = Vector&lt;4, unsigned&gt;; using Vec2i = Vector&lt;2, int&gt;; using Vec3i = Vector&lt;3, int&gt;; using Vec4i = Vector&lt;4, int&gt;; } #endif </code></pre> <p><strong>Edit:</strong> Definition of the dot product for code completeness:</p> <pre><code> template&lt;unsigned Dim, typename T&gt; static inline T dot(const Vector&lt;Dim, T&gt;&amp; a, const Vector&lt;Dim, T&gt;&amp; b) { return ComputeDot&lt;Dim, T, Dim - 1&gt;::call(a, b); } template&lt;unsigned Dim, typename T, unsigned index&gt; struct ComputeDot { static inline T call(const Vector&lt;Dim, T&gt;&amp; a, const Vector&lt;Dim, T&gt;&amp; b) { return a[index] * b[index] + ComputeDot&lt;Dim, T, index - 1&gt;::call(a, b); } }; template&lt;unsigned Dim, typename T&gt; struct ComputeDot&lt;Dim, T, 0&gt; { static inline T call(const Vector&lt;Dim, T&gt;&amp; a, const Vector&lt;Dim, T&gt;&amp; b) { return a[0] * b[0]; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T21:14:47.603", "Id": "396510", "Score": "0", "body": "Any reason why you aren’t just using glm? glm does everything this class does and more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T22:27:30.2...
[ { "body": "<p>A few issues:</p>\n\n<ul>\n<li>Functions defined in the class in the header are <code>inline</code> by default, so there's no need to use the keyword everywhere.</li>\n<li>Use <code>std::copy</code>, not <code>std::memcpy</code>. It's <a href=\"https://stackoverflow.com/questions/4707012/is-it-bet...
{ "AcceptedAnswerId": "205557", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T16:29:56.613", "Id": "205553", "Score": "10", "Tags": [ "c++", "template", "template-meta-programming", "coordinate-system" ], "Title": "C++ math vector template" }
205553
<blockquote> <p>Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum β‰₯ s. If there isn't one, return 0 instead.</p> <p>Example: </p> <p>Input: s = 7, nums = [2,3,1,2,4,3]<br> Output: 2.<br> Explanation: the subarray [4,3] has the minimal length under the problem constraint.</p> </blockquote> <p>What is the complexity of my solution?</p> <pre><code>class Solution { public int minSubArrayLen(int s, int[] nums) { int len = nums.length; int i=0,j=0; int sum=0; int res=Integer.MAX_VALUE; while(i&lt;len &amp;&amp; j&lt;len) { if(sum&lt;s) { sum = sum+nums[j]; j++; } else { res = Math.min(res,j-i); sum = sum-nums[i]; i++; } } while(sum&gt;=s) { res = Math.min(res,j-i); sum = sum-nums[i]; i++; } if(res == Integer.MAX_VALUE) return 0; else return res; } } </code></pre>
[]
[ { "body": "<p>The time complexity of this solution is <code>O(n)</code>, i.e linear time complexity.</p>\n\n<p>Explanation for time complexity to be linear : Here your loops are bounded by the variables <code>i</code> and <code>j</code> and one of them is always being incremented. So in worst case the loop can ...
{ "AcceptedAnswerId": "205559", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T19:32:18.070", "Id": "205558", "Score": "-3", "Tags": [ "java", "algorithm", "complexity" ], "Title": "Given an array of positive integers, find shortest subarray whose sum exceeds a threshold" }
205558
<p>I have a class that compares the performance of two methods (multi- and single- thread) that searches for maximum number in the string of numbers. I want to improve the performance of a multithreaded variant because I think it can work more efficiently.</p> <pre><code>public class Part4 { private static String PATH = "part4.txt"; private static String ENCODING = "Cp1251"; public static void main(String[] args) { int max1; int max2; String[] lines = Util.read(PATH, ENCODING).split(System.lineSeparator()); long t1 = System.currentTimeMillis(); max1 = findMaxMT(lines); long t2 = System.currentTimeMillis(); System.out.println(max1); System.out.println(t2-t1); long t3 = System.currentTimeMillis(); max2 = findMax(lines); long t4 = System.currentTimeMillis(); System.out.println(max2); System.out.println(t4-t3); } public static int findMaxMT(String[] lines) { int max; List&lt;MaxFinder&gt; threadList = new LinkedList&lt;&gt;(); List&lt;Integer&gt; res = new LinkedList&lt;&gt;(); for (String line : lines) { MaxFinder thread = new MaxFinder(line); thread.start(); threadList.add(thread); } threadList.forEach(thread -&gt; { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); threadList.forEach(thread -&gt; { res.add(thread.getCurrentMax()); }); max = MaxFinder.maxFrom(res); return max; } public static int findMax(String[] lines) { List&lt;Integer&gt; res = new LinkedList&lt;&gt;(); int max; for (int i = 0; i &lt; lines.length; i++) { List&lt;Integer&gt; numbers = new LinkedList&lt;&gt;(); int currentMax; for (String s : lines[i].split("\\s")) { numbers.add(Integer.parseInt(s)); } currentMax = MaxFinder.maxFrom(numbers); res.add(currentMax); } max = MaxFinder.maxFrom(res); return max; } } class MaxFinder extends Thread { private String line; private int currentMax = Integer.MIN_VALUE; public MaxFinder(String line) { this.line = line; } @Override public void run() { List&lt;Integer&gt; numbers = new LinkedList&lt;&gt;(); for (String s : line.split("\\s")) { numbers.add(Integer.parseInt(s)); } currentMax = maxFrom(numbers); } public int getCurrentMax() { return currentMax; } public static int maxFrom(List&lt;Integer&gt; numbers) { int max = Integer.MIN_VALUE; for (int n : numbers) { try { Thread.sleep(1); if (n &gt; max) { max = n; } } catch (InterruptedException e) { e.printStackTrace(); } } return max; } } </code></pre> <p><code>Thread.sleep(1)</code> is for benchmarking.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-14T23:12:49.987", "Id": "205564", "Score": "2", "Tags": [ "java", "multithreading", "concurrency" ], "Title": "Comparing performance of multi- and single - thread search of a maximum number" }
205564
<p>Just for fun I wrote some JavaScript that "converts" an image into pure HTML / CSS. The user is able to select a local image. This image is loaded into an invisible canvas in order to extract pixeldata from the image. Using the pixeldata, a structure of 1x1 <code>&lt;div/&gt;</code> elements is created with each element having its background color set to its corresponding pixel color of the image.</p> <p>The script works perfectly fine on small (width / height) images, but kills the browser on any large image file. I was wondering if there are some things I can do within my code to solve this issue?</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>document.addEventListener("DOMContentLoaded", function(event) { const file = document.getElementById('file'); file.addEventListener('change', handleFile); function handleFile(e){ // Create canvas let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); // Load image let img = new Image; img.src = URL.createObjectURL(e.target.files[0]); img.onload = function() { // Draw image to canvas ctx.drawImage(img, 0, 0, img.width, img.height); let container = document.createElement('div'); container.id = 'container'; container.style.Width = img.width; container.style.Height = img.height; let pixelData = ctx.getImageData(0, 0, img.width, img.height).data; let pixel = 0; // Loop through each row for(let x = 0; x &lt; img.height; x++){ let row = document.createElement('div'); row.className = 'row'; // Loop through each column for(let y = 0; y &lt; img.width; y++){ let col = document.createElement('div'); col.className = 'col'; col.style.cssText = 'background: rgba('+pixelData[pixel]+','+pixelData[pixel+1]+','+pixelData[pixel+2]+','+pixelData[pixel+3]+');'; row.appendChild(col); pixel = pixel + 4; } container.appendChild(row); } document.getElementById('body').appendChild(container); URL.revokeObjectURL(img.src); } } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { margin-left: 50px; margin-top: 50px; } .row { overflow: auto; } .row { height: 1px; } .col { width: 1px; height: 1px; float:left; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body id='body'&gt; &lt;input type='file' id='file'/&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T14:01:28.373", "Id": "396589", "Score": "0", "body": "What do you mean by \"pure HTML / CSS\"? The `Image` object you create at the very beginning (the one whose `src` property you set to `img.src = URL.createObjectURL(e.target.file...
[ { "body": "<p>After working on this for a while with other developers on Stack Overflow chat, the best solution I came up with (so far) was to use an asynchronous loop and adding nodes to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment\" rel=\"nofollow noreferrer\">Document Fragmen...
{ "AcceptedAnswerId": "205615", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T03:24:04.833", "Id": "205566", "Score": "0", "Tags": [ "javascript", "performance" ], "Title": "Image to HTML / CSS conversion using pure JS" }
205566
<p>I wrote this algorithm to find the Kth element of a singly linked list and I would like your feedback because I want to know if there is a better version. </p> <p>In my eyes, this is the most optimized way of doing it and I've covered every edge case (I also assumed that the only possible input is a number, if I removed that assumption, I would add another if block), but I really would appreciate your feedback.</p> <p>PS: I also only added these two main methods (<code>add</code> and <code>findLast</code>) because I figured that there were the only two required to find a solution, but I'm not sure if I should add more in an interview (i.e. <code>remove</code>, <code>removeAt</code>, <code>addAt</code>, <code>isEmpty</code>, etc.)</p> <pre><code>function LinkedList() { let length = 0; let head = null; function Node(element) { this.element = element; this.next = null; } this.length = function() { return length; } this.head = function() { return head; } this.add = function(element) { let node = new Node(element); if (head == null) { head = node; } else { currentNode = head; while (currentNode.next) { currentNode = currentNode.next; } currentNode.next = node; } length++; } this.findLast = function(index) { if(index &gt; length) { return false; } if (index &lt; 0) { return false; } let realIndexes = length-1; // if length = 5, realIndexes = 4 let realPosition = index-1; // if index = 2, realPosition = 1 // We are looking for the real position here. let realTarget = realIndexes - realPosition; let currentNode = head; let counter = 0; while (counter &lt; realTarget) { currentNode = currentNode.next; counter++; } return currentNode.element; } } let congo = new LinkedList(); console.log(congo) congo.add(5); congo.add("Homeless"); congo.add("Real eyes realize real lies"); congo.length() congo.head() </code></pre> <p>Output: => 5</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T20:12:23.740", "Id": "396533", "Score": "1", "body": "Okay thank you Mark, wasn't sure if Stack Overflow was right for this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T20:14:45.040", "Id": "39...
[ { "body": "<p>To get the sub-list of the <strong>last n elements</strong> without computing the length first (see comments):</p>\n\n<ul>\n<li>Go ahead with an <em>end</em> pointer until you have skipped <em>n</em> elements. </li>\n<li>Now go ahead in parallel with a <em>start</em> pointer and the <em>end</em> p...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T20:05:02.830", "Id": "205568", "Score": "1", "Tags": [ "javascript", "algorithm", "linked-list" ], "Title": "Implement an algorithm to find the Kth to last element of a singly linked string" }
205568
<p>I have seen some solution here for the same problem, <a href="https://codereview.stackexchange.com/questions/31051/please-review-my-solution-to-project-euler-program-1">this</a> and <a href="https://codereview.stackexchange.com/questions/51093/finding-the-sum-of-all-the-multiples-of-3-or-5-below-1000">this</a> I have found better ways to solve this problem. I just want to know how good or bad my code and way of approaching this problem is.</p> <pre><code>using System; public class Program { public static void Main() { int sum = 0; for (int i = 0; 3 * i &lt; 1000; i++) { sum += 3 * i; if (5 * i &lt; 1000 &amp;&amp; (5 * i) % 3 != 0) { sum += 5 * i; } } Console.WriteLine(sum ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T07:44:26.977", "Id": "396551", "Score": "2", "body": "`Console.WriteLine(sum + \"\");` looks weird, why don't you just `Console.WriteLine(sum);`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T10:13:...
[ { "body": "<p>Thanks @Henrik Hansen it helped.\nThis is optimised code below according to the WIKI. \nBut here is the tradeoff, this has to loop 1000 times. where above solution need to run at most 333 times.</p>\n\n<pre><code> using System;\n\n public class Program\n {\n public static void Main()\...
{ "AcceptedAnswerId": "205589", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T06:38:07.350", "Id": "205578", "Score": "8", "Tags": [ "c#", "beginner", "programming-challenge" ], "Title": "Add multiples of 3 or 5 below 1000, Can this code be optimised. Project Euler #1" }
205578
<p>I need to determine whether a cookie name is available or not in the cookie string. I have achieved this. We could use the cookie-parser package but I don't want to use that package so I have written the below code. Can I reduce the code in a better way that is more optimised?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> function checkCookie(cookie, cookieToBeSearched){ if(cookie === "" || cookie === undefined){ return false } let res = cookie.split(";").some(cookie =&gt; { let eachCookie = cookie.split("="); return eachCookie[0].trim() === cookieToBeSearched }); return res; } let cookie = "_ga=GA1.2.2091695351.1539084164; __qca=P0-338702612-1539084164095; __gads=ID=770d92bcdac8de40:T=1539084164:S=ALNI_MbsRKpoSJdn8tsdShMHMZUAR17uZA; _gid=GA1.2.798724103.1539582973"; console.log("Cookie is available - ", checkCookie(cookie, "_gid")) console.log("Cookie is available - ", checkCookie(cookie, "_giddd"))</code></pre> </div> </div> </p>
[]
[ { "body": "<h1>Option 1: Same functionality, smaller size</h1>\n\n<blockquote>\n <p>Can I reduce the code in a better way more optimised?</p>\n</blockquote>\n\n<p>If you want to optimize for size, then here's a suggestion for a more compact version:</p>\n\n<pre><code>function checkCookie(cookies, name) {\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T06:51:52.160", "Id": "205580", "Score": "1", "Tags": [ "javascript", "strings", "node.js", "ecmascript-6", "http" ], "Title": "Find if cookie name exists in the cookie string" }
205580
<p>I'm working with big 2d <code>numpy</code> arrays, and a function that I need to iterate over each row of these arrays.</p> <p>To speed things up, I've implemented parallel processing using Python's <code>multiprocessing</code> module. Each worker of the pool gets an array index, which is used to read the data from the shared array, and after the function is executed, overwrite the data in the shared array on the same location.</p> <p>The function returns the modified values as well as a processing parameter, which in turn is also stored in a separate 1d shared array.</p> <p>So my questions are:</p> <p>I've read many times that it's not particularly safe to have multiple processes reading and writing data from a shared array. Until now, things have just worked fine. Should I change my approach? Are there real concerns that things could not work as intended?</p> <p>If the above mentioned approach isn't safe and/or practical, what would be a good alternative approach to implement this kind of processing, where I need to access shared arrays, for both reading and writing?</p> <p>Of course, I'm also grateful for any other constructive comment on my code!</p> <p>Here's a working example. In this case the function is merely generating a random integer by which the raw data is then multiplied and overwritten in the shared array. The generated integer can be seen as the processing parameter, which I need to store in the second shared array.</p> <pre><code>import numpy as np import ctypes import array import multiprocessing as mp import random from contextlib import contextmanager, closing def init_shared(ncell): '''Create shared value array for processing.''' shared_array_base = mp.Array(ctypes.c_float,ncell,lock=False) return(shared_array_base) def tonumpyarray(shared_array): '''Create numpy array from shared memory.''' nparray= np.frombuffer(shared_array,dtype=ctypes.c_float) assert nparray.base is shared_array return nparray def init_parameters(**kwargs): '''Initialize parameters for processing in workers.''' params = dict() for key, value in kwargs.items(): params[key] = value return params def init_worker(shared_array_,parameters_): '''Initialize worker for processing. Args: shared_array_: Object returned by init_shared parameters_: Dictionary returned by init_parameters ''' global shared_array global shared_parr global dim shared_array = tonumpyarray(shared_array_) shared_parr = tonumpyarray(parameters_['shared_parr']) dim = parameters_['dimensions'] def worker_fun(ix): '''Function to be run inside each worker''' arr = tonumpyarray(shared_array) parr = tonumpyarray(shared_parr) arr.shape = dim random.seed(ix) rint = random.randint(1,10) parr[ix] = rint arr[ix,...] = arr[ix,...] * rint ##---------------------------------------------------------------------- def main(): nrows = 100 ncols = 10 shared_array = init_shared(nrows*ncols) shared_parr = init_shared(nrows) params = init_parameters(shared_parr=shared_parr,dimensions=(nrows,ncols)) arr = tonumpyarray(shared_array) parr = tonumpyarray(params['shared_parr']) arr.shape = (nrows,ncols) arr[...] = np.random.randint(1,100,size=(100,10),dtype='int16') with closing(mp.Pool(processes=8,initializer = init_worker, initargs = (shared_array,params))) as pool: res = pool.map(worker_fun,range(arr.shape[0])) pool.close() pool.join() # check PARR output print(parr) if __name__ == '__main__': main() </code></pre> <p>An the output: </p> <blockquote> <p>array([ 7., 3., 1., 4., 4., 10., 10., 6., 4., 8., 10., 8., 8., 5., 2., 4., 6., 9., 3., 1., 3., 3., 3., 5., 7., 7., 4., 8., 2., 9., 9., 1., 2., 10., 9., 9., 6., 10., 7., 4., 8., 7., 2., 1., 7., 5., 2., 6., 9., 2., 8., 4., 5., 10., 3., 2., 9., 1., 10., 4., 5., 8., 10., 8., 8., 7., 2., 2., 8., 1., 2., 6., 2., 5., 10., 8., 6., 5., 4., 3., 5., 9., 3., 8., 5., 4., 1., 3., 7., 2., 4., 2., 7., 8., 9., 9., 6., 4., 6., 7.], dtype=float32)</p> </blockquote>
[]
[ { "body": "<ul>\n<li><p>To address your immediate concerns, the code is safe. Each worker operates on its own (sub)set of data. Nothing is really shared, so there is no data race.</p></li>\n<li><p>It is unclear why the worker function calls <code>tonumpyarray</code> on the objects which already are numpy arrays...
{ "AcceptedAnswerId": "205605", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T07:45:03.130", "Id": "205582", "Score": "2", "Tags": [ "python", "array", "multiprocessing" ], "Title": "Passing shared memory array to worker pool in Python" }
205582
<p>I recently just finished making this blackjack game using C++ and SDL2. Although this took a lot longer than I expected it to, I feel like I'm getting a good hang of everything. However, this is only my third game and feel like there's bound to be a lot of room for improvement. There's a lot different files for all of the classes so I'm only including the main.cpp and game.cpp files as they have the bulk of the code and the portions that I think would benefit most from a review.</p> <p>For reference, the <code>Card</code> class has a <code>rank, suit, and discarded bool</code>. The <code>Hand</code> class has a <code>vector of cards, blackjack split and double bools , and an endState enum</code> to determine payout. And the <code>Player</code> class just has a <code>mainHand, splitHand, money and wager</code> variables and a bool for whether their turn is done.</p> <p>During the beginning of programming the game I did not plan for the ability to split and the player to have two simultaneous hands, so I'm sure some of the split functionality is not as efficient as it could be.</p> <p>I do have one specific question: There are quite a few situations where I find myself having to use member of members of members. For instance in <code>Game::resetTable()</code> when putting the cards back into the deck I have to use <code>deck_.push_back(player_.mainHand_.cards_[player_.mainHand_.cards_.size() - 1])</code>. Is this just the nature of using classes or would there be a better way of handling this situations?</p> <p>Besides this, any general feedback on anything that could be improved would be greatly appreciated.</p> <p><strong>game.h</strong></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;deque&gt; #include &lt;random&gt; #include &lt;SDL_ttf.h&gt; #include "Texture.h" #include "Card.h" #include "Player.h" #include "Hand.h" #include "SDLInit.h" constexpr int SCREEN_WIDTH = 640; constexpr int SCREEN_HEIGHT = 480; struct Game { bool paidOut_ = false; bool handEnd_ = false; bool splitHandTurn_ = false; std::deque&lt;Card&gt; deck_; Player player_; Player dealer_; std::string mainHandResult_ = " "; std::string splitHandResult_ = " "; void reclaimDiscarded(); void dealerTurn(); void compareHands(Hand &amp;playerHand, Hand dealerHand); void swapCards(Card &amp;a, Card &amp;b); void shuffleDeck(); void resetTable(); void getCard(Hand &amp;hand); void setCards(); void dealCards(); void splitCards(); int getHandValue(Hand hand); }; struct AssetManager { std::unique_ptr&lt;SDL_Window, sdl_deleter&gt; window_{ SDL_CreateWindow("Blackjack", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN) }; std::unique_ptr&lt;SDL_Renderer, sdl_deleter&gt; renderer_{ SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_PRESENTVSYNC) }; std::unique_ptr&lt;TTF_Font, sdl_deleter&gt; font_{ TTF_OpenFont("resources/opensans.ttf", 20) }; std::unique_ptr&lt;TTF_Font, sdl_deleter&gt; largeFont_{ TTF_OpenFont("resources/opensans.ttf", 50) }; SDL_Color whiteFont_ = { 0xff, 0xff, 0xff }; SDL_Color yellowFont_ = { 0xFF, 0xFF, 0 }; int fontWrapWidth_ = SCREEN_WIDTH; LTexture menuTexture_{ from_surface, renderer_.get(), "resources/menutexture.png" }; LTexture onePlayerButton_{ from_surface, renderer_.get(), "resources/oneplayer.png" }; LTexture wagerText_{ from_text, font_.get(), renderer_.get(), "Wager: ", whiteFont_, fontWrapWidth_ }; //just a bunch more textures and text... bool buttonIsPressed(SDL_Event const&amp; event, SDL_Rect const&amp; button_rect); void endOfHandRender(Game &amp;game); void renderTable(Game &amp;game); }; </code></pre> <p><strong>game.cpp</strong></p> <pre><code>#include "Game.h" std::mt19937&amp; random_engine() { static std::mt19937 mersenne(std::random_device{}()); return mersenne; } int getRandomNumber(int x, int y) { std::uniform_int_distribution&lt;&gt; dist{ x,y }; return dist(random_engine()); } bool AssetManager::buttonIsPressed(SDL_Event const&amp; event, SDL_Rect const&amp; button_rect) { if (event.type == SDL_MOUSEBUTTONDOWN) { auto const&amp; mouse_button_event = event.button; auto const mouse_position = SDL_Point{ mouse_button_event.x, mouse_button_event.y }; return (mouse_button_event.button == SDL_BUTTON_LEFT) &amp;&amp; SDL_PointInRect(&amp;mouse_position, &amp;button_rect); } return false; } void Game::reclaimDiscarded() { for (size_t i = 0; i &lt; deck_.size(); ++i) { if (deck_[i].discarded) { deck_[i].discarded = false; } } } void Game::dealerTurn() { if (getHandValue(dealer_.mainHand_) &gt; 21) { //don't change if blackjack or bust if (player_.mainHand_.endState == Hand::NONE) { player_.mainHand_.endState = Hand::DEALER_BUST; } if (player_.splitHand_.endState == Hand::NONE) { player_.splitHand_.endState = Hand::DEALER_BUST; } dealer_.turnEnd = true; handEnd_ = true; } if (getHandValue(dealer_.mainHand_) &gt; 16) { handEnd_ = true; dealer_.turnEnd = true; return; } //makes it look like cards are being dealt instead of instant SDL_Delay(500); getCard(dealer_.mainHand_); } void Game::compareHands(Hand &amp;playerHand, Hand dealerHand) { if (getHandValue(playerHand) &gt; getHandValue(dealerHand)) { playerHand.endState = Hand::PLAYER_WON; } if (getHandValue(playerHand) &lt; getHandValue(dealerHand)) { playerHand.endState = Hand::DEALER_WON; } if (getHandValue(playerHand) == getHandValue(dealerHand)) { playerHand.endState = Hand::DRAW; } } void Game::swapCards(Card &amp;a, Card &amp;b) { Card temp = a; a = b; b = temp; } void Game::shuffleDeck() { size_t count = 0; while (count &lt; deck_.size()) { int randNum = getRandomNumber(0, deck_.size() - 1); swapCards(deck_[count], deck_[randNum]); ++count; } } void Game::resetTable() { //remove cards from hands and mark as discarded while (player_.mainHand_.cards_.size() &gt; 0) { deck_.push_back(player_.mainHand_.cards_[player_.mainHand_.cards_.size() - 1]); deck_[deck_.size() - 1].discarded = true; player_.mainHand_.cards_.pop_back(); } while (dealer_.mainHand_.cards_.size() &gt; 0) { deck_.push_back(dealer_.mainHand_.cards_[dealer_.mainHand_.cards_.size() - 1]); deck_[deck_.size() - 1].discarded = true; dealer_.mainHand_.cards_.pop_back(); } while (player_.splitHand_.cards_.size() &gt; 0) { deck_.push_back(player_.splitHand_.cards_[player_.splitHand_.cards_.size() - 1]); deck_[deck_.size() - 1].discarded = true; player_.splitHand_.cards_.pop_back(); } player_.mainHand_.numOfAces_ = 0; player_.splitHand_.numOfAces_ = 0; player_.mainHand_.canDouble = true; player_.splitHand_.canDouble = true; player_.turnEnd = false; player_.mainHand_.endState = Hand::NONE; player_.splitHand_.endState = Hand::NONE; dealer_.mainHand_.numOfAces_ = 0; dealer_.mainHand_.canDouble = true; dealer_.turnEnd = false; splitHandTurn_ = false; paidOut_ = false; handEnd_ = false; mainHandResult_ = " "; splitHandResult_ = " "; } void Game::getCard(Hand &amp;hand) { if (deck_[0].discarded) { reclaimDiscarded(); shuffleDeck(); } if (deck_[0].rank_ == Card::ACE) { ++hand.numOfAces_; } hand.cards_.push_back(deck_[0]); deck_.pop_front(); } int Game::getHandValue(Hand hand) { int handValue = 0; for (size_t i = 0; i &lt; hand.cards_.size(); i++) { if (hand.cards_[i].rank_ == Card::ACE) { handValue += 11; } else if (hand.cards_[i].rank_ == Card::JACK || hand.cards_[i].rank_ == Card::QUEEN || hand.cards_[i].rank_ == Card::KING) { handValue += 10; } else { handValue += hand.cards_[i].rank_ + 1; } } while (handValue &gt; 21 &amp;&amp; hand.numOfAces_ &gt; 0) { hand.numOfAces_ -= 1; handValue -= 10; } return handValue; } void Game::setCards() { for (int suit = Card::HEART; suit &lt; Card::NUMBER_OF_SUITS; suit++) { for (int rank = Card::ACE; rank &lt; Card::NUMBER_OF_RANKS; rank++) { Card card; card.cardClip_ = { rank * 60, suit * 90, 60, 90 }; card.suit_ = static_cast&lt;Card::CardSuit&gt;(suit); card.rank_ = static_cast&lt;Card::CardRank&gt;(rank); deck_.push_back(card); } } } void Game::dealCards() { getCard(player_.mainHand_); getCard(dealer_.mainHand_); getCard(player_.mainHand_); getCard(dealer_.mainHand_); } void Game::splitCards() { player_.splitHand_.cards_.push_back(player_.mainHand_.cards_[1]); player_.mainHand_.cards_.pop_back(); getCard(player_.mainHand_); getCard(player_.splitHand_); } void AssetManager::endOfHandRender(Game &amp;game) { switch (game.player_.mainHand_.endState) { case Hand::NONE: break; case Hand::PLAYER_WON: game.mainHandResult_ = "YOU WON!"; break; case Hand::DEALER_WON: game.mainHandResult_ = "DEALER WON!"; break; case Hand::PLAYER_BUST: game.mainHandResult_ = "YOU BUST!"; break; case Hand::DEALER_BUST: game.mainHandResult_ = "DEALER BUST"; break; case Hand::BLACKJACK: game.mainHandResult_ = "BLACKJACK!!"; break; case Hand::DRAW: game.mainHandResult_ = "DRAW!"; break; } switch (game.player_.splitHand_.endState) { case Hand::NONE: break; case Hand::PLAYER_WON: game.splitHandResult_ = "YOU WON!"; break; case Hand::DEALER_WON: game.splitHandResult_= "DEALER WON!"; break; case Hand::PLAYER_BUST: game.splitHandResult_ = "YOU BUST!"; break; case Hand::DEALER_BUST: game.splitHandResult_ = "DEALER BUST!"; break; case Hand::BLACKJACK: game.splitHandResult_ = "BLACKJACK!!"; break; case Hand::DRAW: game.splitHandResult_ = "DRAW!"; break; } if (!game.splitHandTurn_) { LTexture mainHandResultTexture{ from_text,largeFont_.get(), renderer_.get(), game.mainHandResult_, yellowFont_, fontWrapWidth_ }; mainHandResultTexture.render(renderer_.get(), SCREEN_WIDTH / 2 - mainHandResultTexture.width_ / 2, SCREEN_HEIGHT / 2 - mainHandResultTexture.height_ / 2); } else { LTexture mainHandResultTexture{ from_text, font_.get(), renderer_.get(), game.mainHandResult_, yellowFont_, fontWrapWidth_ }; LTexture splitHandResultTexture{ from_text, font_.get(), renderer_.get(), game.splitHandResult_, yellowFont_, fontWrapWidth_ }; mainHandResultTexture.render(renderer_.get(), SCREEN_WIDTH / 2 - mainHandResultTexture.width_ / 2, SCREEN_HEIGHT / 2 - mainHandResultTexture.height_ / 2); splitHandResultTexture.render(renderer_.get(), SCREEN_WIDTH - splitHandResultTexture.width_ - 50, SCREEN_HEIGHT / 2 - splitHandResultTexture.height_ / 2); } } void AssetManager::renderTable(Game &amp;game) { tableTexture_.render(renderer_.get(), 0, 0); //display cards in hands if (game.player_.mainHand_.cards_.size() &gt; 0) { for (size_t numCards = 0; numCards &lt; game.player_.mainHand_.cards_.size(); numCards++) { cardSpriteSheet_.render(renderer_.get(), 285 + (numCards * 20), 315, &amp;game.player_.mainHand_.cards_[numCards].cardClip_); } } if (game.player_.splitHand_.cards_.size() &gt; 0) { for (size_t numCards = 0; numCards &lt; game.player_.splitHand_.cards_.size(); numCards++) { cardSpriteSheet_.render(renderer_.get(), 490 + (numCards * 20), 315, &amp;game.player_.splitHand_.cards_[numCards].cardClip_); } } //hide 2nd dealer card until dealer's turn if (game.player_.mainHand_.cards_.size() &gt; 0) { if (!game.player_.turnEnd) { cardSpriteSheet_.render(renderer_.get(), 280, 48, &amp;game.dealer_.mainHand_.cards_[0].cardClip_); backOfCardTexture_.render(renderer_.get(), 280 + 20, 48); } else { for (size_t numCards = 0; numCards &lt; game.dealer_.mainHand_.cards_.size(); numCards++) { cardSpriteSheet_.render(renderer_.get(), 280 + (numCards * 20), 48, &amp;game.dealer_.mainHand_.cards_[numCards].cardClip_); } } } hitButton_.render(renderer_.get(), 165, 300); standButton_.render(renderer_.get(), 165, 332); doubleButton_.render(renderer_.get(), 165, 364); splitButton_.render(renderer_.get(), 165, 396); dealButton_.render(renderer_.get(), 165, 428); handValueTotalText_.render(renderer_.get(), 275, 270); handValueTotalText_.render(renderer_.get(), 275, 150); wagerText_.render(renderer_.get(), 455, 250); moneyText_.render(renderer_.get(), 455, 270); //show chip signifying wager has been placed if (game.player_.wager_ &gt; 0) { betChipTexture_.render(renderer_.get(), 395, 247); } LTexture playerHandValueText_{ from_text, font_.get(), renderer_.get(), std::to_string(game.getHandValue(game.player_.mainHand_)), whiteFont_, fontWrapWidth_ }; playerHandValueText_.render(renderer_.get(), 275 + handValueTotalText_.width_ + 2, 270); LTexture playerMoneyTotalText_{ from_text, font_.get(), renderer_.get(), std::to_string(game.player_.moneyValue_ - game.player_.wager_), whiteFont_, fontWrapWidth_ }; playerMoneyTotalText_.render(renderer_.get(), 455 + moneyText_.width_, 270); LTexture playerWagerValueText_{ from_text, font_.get(), renderer_.get(), std::to_string(game.player_.wager_), whiteFont_, fontWrapWidth_ }; playerWagerValueText_.render(renderer_.get(), 455 + wagerText_.width_, 250); //only show dealer hand value after player stands or busts if (game.player_.turnEnd) { LTexture dealerHandValueText__{ from_text, font_.get(), renderer_.get(), std::to_string(game.getHandValue(game.dealer_.mainHand_)), whiteFont_, fontWrapWidth_ }; dealerHandValueText__.render(renderer_.get(), 275 + handValueTotalText_.width_ + 2, 150); } } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;random&gt; #include &lt;string&gt; #include &lt;deque&gt; #include &lt;SDL.h&gt; #include &lt;SDL_image.h&gt; #include &lt;SDL_ttf.h&gt; #include "SDLInit.h" #include "Texture.h" #include "Game.h" #include "Card.h" #include "Player.h" #include "Hand.h" enum class GameState { MAIN_MENU, WAGER, GAME_LOOP, SPLIT, PLAY_AGAIN, EXIT, }; bool playAgain_render(Game&amp; game, AssetManager&amp; assets) { SDL_RenderClear(assets.renderer_.get()); assets.menuTexture_.render(assets.renderer_.get(), 0, 0); assets.youRanOutofMoneyText_.render(assets.renderer_.get(), SCREEN_WIDTH / 2 - assets.youRanOutofMoneyText_.width_ / 2, 100); assets.playAgainText_.render(assets.renderer_.get(), SCREEN_WIDTH / 2 - assets.playAgainText_.width_ / 2, 160); assets.yesButton_.render(assets.renderer_.get(), SCREEN_WIDTH / 2 - assets.yesButton_.width_ / 2, 200); assets.noButton_.render(assets.renderer_.get(), SCREEN_WIDTH / 2 - assets.noButton_.width_ / 2, 235); SDL_RenderPresent(assets.renderer_.get()); return true; } bool playAgain_update() { return true; } bool playAgain_input(GameState&amp; gameState, Game&amp; game, AssetManager&amp; assets) { SDL_Event e; while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { gameState = GameState::EXIT; return false; } if (assets.buttonIsPressed(e, assets.yesButton_.button_)) { game.player_.moneyValue_ = 100; game.resetTable(); gameState = GameState::WAGER; return false; } else if (assets.buttonIsPressed(e, assets.noButton_.button_)) { gameState = GameState::EXIT; return false; } } return true; } bool split_render(Game&amp; game, AssetManager&amp; assets) { SDL_RenderClear(assets.renderer_.get()); assets.renderTable(game); assets.endOfHandRender(game); SDL_Rect currentHandOutLineRect; if (!game.splitHandTurn_) { currentHandOutLineRect = { 275, 305, 80, 110 }; } else { currentHandOutLineRect = { 480, 305, 80, 110 }; } SDL_SetRenderDrawColor(assets.renderer_.get(), 0xFF, 0x00, 0x00, 0xFF); SDL_RenderDrawRect(assets.renderer_.get(), &amp;currentHandOutLineRect); assets.handValueTotalText_.render(assets.renderer_.get(), 475, 420); LTexture playerSplitHandValueText__{ from_text, assets.font_.get(), assets.renderer_.get(), std::to_string(game.getHandValue(game.player_.splitHand_)), assets.whiteFont_, assets.fontWrapWidth_ }; playerSplitHandValueText__.render(assets.renderer_.get(), 475 + assets.handValueTotalText_.width_ + 2, 420); SDL_RenderPresent(assets.renderer_.get()); return true; } bool split_update(GameState&amp; gameState, Game&amp; game, AssetManager&amp; assets) { if (!game.splitHandTurn_) { if (game.player_.mainHand_.hasBlackjack()) { game.player_.mainHand_.endState = Hand::BLACKJACK; game.splitHandTurn_ = true; } else if (game.getHandValue(game.player_.mainHand_) &gt; 21) { game.player_.mainHand_.endState = Hand::PLAYER_BUST; game.splitHandTurn_ = true; } } else { if (game.player_.splitHand_.hasBlackjack()) { game.player_.splitHand_.endState = Hand::BLACKJACK; if (game.player_.mainHand_.endState == Hand::NONE) { game.player_.turnEnd = true; } //if both hands blackjack or bust just skip dealer turn else { game.handEnd_ = true; } } else if (game.getHandValue(game.player_.splitHand_) &gt; 21) { game.player_.splitHand_.endState = Hand::PLAYER_BUST; if (game.player_.mainHand_.endState == Hand::NONE) { game.player_.turnEnd = true; } else { game.handEnd_ = true; } } } if (game.player_.turnEnd) { game.dealerTurn(); } if (game.player_.turnEnd &amp;&amp; game.dealer_.turnEnd) { if (game.player_.mainHand_.endState == Hand::NONE) { game.compareHands(game.player_.mainHand_, game.dealer_.mainHand_); } if (game.player_.splitHand_.endState == Hand::NONE) { game.compareHands(game.player_.splitHand_, game.dealer_.mainHand_); } game.handEnd_ = true; } if (game.handEnd_ &amp;&amp; !game.paidOut_) { game.player_.updateMoney(game.player_.mainHand_); game.player_.updateMoney(game.player_.splitHand_); game.paidOut_ = true; //remember previous wager unless it is more money than the player has if (game.player_.wager_ &gt; game.player_.moneyValue_) { game.player_.wager_ = 0; } gameState = GameState::WAGER; return false; } return true; } bool split_input(GameState&amp; gameState, Game&amp; game, AssetManager&amp; assets) { SDL_Event e; while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { gameState = GameState::EXIT; return false; } if (assets.buttonIsPressed(e, assets.hitButton_.button_) &amp;&amp; !game.player_.turnEnd) { if (!game.handEnd_) { if (!game.splitHandTurn_) { game.getCard(game.player_.mainHand_); game.player_.mainHand_.canDouble = false; } else { game.getCard(game.player_.splitHand_); game.player_.mainHand_.canDouble = false; } } } else if (assets.buttonIsPressed(e, assets.standButton_.button_) &amp;&amp; !game.handEnd_) { if (!game.splitHandTurn_) { game.splitHandTurn_ = true; } else { game.player_.turnEnd = true; game.player_.splitHand_.canDouble = false; } } else if (assets.buttonIsPressed(e, assets.doubleButton_.button_) &amp;&amp; !game.handEnd_ &amp;&amp; game.player_.mainHand_.canDouble) { if (game.player_.wager_ * 2 &lt;= game.player_.moneyValue_) { game.player_.wager_ *= 2; if (!game.splitHandTurn_ &amp;&amp; game.player_.mainHand_.canDouble) { game.getCard(game.player_.mainHand_); game.splitHandTurn_ = true; } else if (game.splitHandTurn_ &amp;&amp; game.player_.splitHand_.canDouble) { game.getCard(game.player_.splitHand_); game.player_.turnEnd = true; } } } else if (assets.buttonIsPressed(e, assets.dealButton_.button_) &amp;&amp; game.handEnd_) { gameState = GameState::GAME_LOOP; game.resetTable(); return false; } } return true; } bool gameLoop_render(Game&amp; game, AssetManager&amp; assets) { SDL_RenderClear(assets.renderer_.get()); assets.renderTable(game); assets.endOfHandRender(game); SDL_RenderPresent(assets.renderer_.get()); return true; } bool gameLoop_update(GameState&amp; gameState, Game&amp; game, AssetManager&amp; assets) { if (game.dealer_.mainHand_.hasBlackjack()) { game.player_.turnEnd = true; if (game.player_.mainHand_.hasBlackjack()) { game.player_.mainHand_.endState = Hand::DRAW; } else { game.player_.mainHand_.endState = Hand::DEALER_WON; } game.handEnd_ = true; //delay so there is a reveal SDL_Delay(500); } else if (game.player_.mainHand_.hasBlackjack()) { game.player_.mainHand_.endState = Hand::BLACKJACK; game.handEnd_ = true; } else if (game.getHandValue(game.player_.mainHand_) &gt; 21) { game.player_.mainHand_.endState = Hand::PLAYER_BUST; game.handEnd_ = true; } else if (game.player_.turnEnd) { game.dealerTurn(); } //if no one has blackjack or bust if (game.player_.turnEnd &amp;&amp; game.dealer_.turnEnd &amp;&amp; game.player_.mainHand_.endState == Hand::NONE) { game.compareHands(game.player_.mainHand_, game.dealer_.mainHand_); game.handEnd_ = true; } if (game.handEnd_ &amp;&amp; !game.paidOut_) { game.player_.updateMoney(game.player_.mainHand_); game.paidOut_ = true; //remember previous wager unless it is more money than the player has if (game.player_.wager_ &gt; game.player_.moneyValue_) { game.player_.wager_ = 0; } gameState = GameState::WAGER; return false; } return true; } bool gameLoop_input(GameState&amp; gameState, Game&amp; game, AssetManager&amp; assets) { SDL_Event e; while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { gameState = GameState::EXIT; return false; } else if (assets.buttonIsPressed(e, assets.hitButton_.button_) &amp;&amp; !game.player_.turnEnd) { if (!game.handEnd_) { game.getCard(game.player_.mainHand_); game.player_.mainHand_.canDouble = false; } } else if (assets.buttonIsPressed(e, assets.standButton_.button_) &amp;&amp; !game.handEnd_) { game.player_.turnEnd = true; game.player_.mainHand_.canDouble = false; } else if (assets.buttonIsPressed(e, assets.doubleButton_.button_) &amp;&amp; !game.handEnd_ &amp;&amp; game.player_.mainHand_.canDouble) { if (game.player_.wager_ * 2 &lt;= game.player_.moneyValue_) { game.getCard(game.player_.mainHand_); game.player_.turnEnd = true; game.player_.wager_ *= 2; } } else if (assets.buttonIsPressed(e, assets.splitButton_.button_) &amp;&amp; game.player_.mainHand_.canSplit()) { if (game.player_.wager_ * 2 &lt;= game.player_.moneyValue_) { gameState = GameState::SPLIT; game.player_.wager_ *= 2; return false; } } else if (assets.buttonIsPressed(e, assets.dealButton_.button_) &amp;&amp; game.handEnd_) { game.resetTable(); game.dealCards(); } } return true; } bool wager_render(GameState &amp;gameState, Game &amp;game, AssetManager&amp; assets) { //render logic... return true; } bool wager_update(GameState &amp;gameState, Game &amp;game) { if (game.player_.moneyValue_ == 0) { gameState = GameState::PLAY_AGAIN; return false; } return true; } bool wager_input(GameState&amp; gameState, Game&amp; game, AssetManager&amp; assets) { SDL_Event e; while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { gameState = GameState::EXIT; return false; } //player must wager at least 1 money else if (assets.buttonIsPressed(e, assets.dealButton_.button_) &amp;&amp; game.player_.wager_ &gt; 0) { gameState = GameState::GAME_LOOP; game.resetTable(); return false; } else if (assets.buttonIsPressed(e, assets.chip1_.button_)) { //can not wager more than they have if (game.player_.wager_ + 1 &lt;= game.player_.moneyValue_) { game.player_.wager_ += 1; } } else if (assets.buttonIsPressed(e, assets.chip5_.button_)) { if (game.player_.wager_ + 5 &lt;= game.player_.moneyValue_) { game.player_.wager_ += 5; } } else if (assets.buttonIsPressed(e, assets.chip25_.button_)) { if (game.player_.wager_ + 25 &lt;= game.player_.moneyValue_) { game.player_.wager_ += 25; } } else if (assets.buttonIsPressed(e, assets.chip50_.button_)) { if (game.player_.wager_ + 50 &lt;= game.player_.moneyValue_) { game.player_.wager_ += 50; } } else if (assets.buttonIsPressed(e, assets.resetWagerButton_.button_)) { game.player_.wager_ = 0; } } return true; } bool mainMenu_render(AssetManager&amp; assets) { //render logic return true; } bool mainMenu_update() { return true; } bool mainMenu_input(GameState&amp; gameState, AssetManager&amp; assets) { //input logic return true; } int main(int argc, char* args[]) { //initialize sdl systems sdl sdlinit; sdl_img img; sdl_ttf ttf; GameState gameState = GameState::MAIN_MENU; Game game; AssetManager assets; game.setCards(); game.shuffleDeck(); while (gameState != GameState::EXIT) { switch (gameState) { case GameState::MAIN_MENU: { while (mainMenu_input(gameState, assets) &amp;&amp; mainMenu_update() &amp;&amp; mainMenu_render(assets)) {} break; } case GameState::WAGER: { while (wager_input(gameState, game, assets) &amp;&amp; wager_update(gameState, game) &amp;&amp; wager_render(gameState, game, assets)) {} break; } case GameState::GAME_LOOP: { game.dealCards(); while (gameLoop_input(gameState, game, assets) &amp;&amp; gameLoop_render(game, assets) &amp;&amp; gameLoop_update(gameState, game, assets)) {} break; } case GameState::SPLIT: { game.splitCards(); while (split_input(gameState, game, assets) &amp;&amp; split_render(game, assets) &amp;&amp; split_update(gameState, game, assets)) {} break; } case GameState::PLAY_AGAIN: { while (playAgain_input(gameState, game, assets) &amp;&amp; playAgain_update() &amp;&amp; playAgain_render(game, assets)) {} break; } } } return 0; } </code></pre> <p>Here's a list to <a href="https://github.com/Nickswoboda/SDL-Blackjack" rel="nofollow noreferrer">github</a> with all of the source code if needed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T09:41:38.133", "Id": "396571", "Score": "0", "body": "You should include your Card, Hand and Player classes too. The idea is to provide a minimal working program (so a `main()` is required too) the reviewer can use to test your prog...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T07:46:56.113", "Id": "205584", "Score": "2", "Tags": [ "c++", "sdl" ], "Title": "SDL2/C++ Blackjack Game" }
205584
<p>I've just started using PyCuda with Python 3, but I have some experience in high performance computing on CPU. I've tried to port one of my old models for generating the <a href="https://en.wikipedia.org/wiki/Buddhabrot" rel="nofollow noreferrer">Buddhabrot</a> to run on my GPU instead. To briefly explain the algorithm to anyone not familiar, the idea is this:</p> <ol> <li>Generate a random complex number <span class="math-container">\$z_0\$</span></li> <li>Iteratively perform the calculation <span class="math-container">\$z_{i+1} = z_i^2 + z_0\$</span>. Do this <span class="math-container">\$N\$</span> times</li> <li>Check if the absolute value of the number <span class="math-container">\$z_N\$</span> is larger than 5*</li> <li>If it is, calculate all the numbers <span class="math-container">\$z_i, 0 \leq i \leq N\$</span> again and map them to pixels.</li> </ol> <p>*The absolute value only needs to be larger than 2, but due to the parameters I've chosen 5 became a better choice of limit.</p> <p>These 4 steps need to be repeated at least a billion times, preferably a trillion times for a high quality image. That's why I looked into using PyCuda to speed it up. Here's my current script:</p> <pre><code>import numpy as np import pycuda.autoinit from pycuda.compiler import SourceModule from pycuda.driver import Device from pycuda import gpuarray import time import scipy.misc code = """ #include &lt;curand_kernel.h&gt; #include &lt;pycuda-complex.hpp&gt; #include &lt;stdio.h&gt; #define X_MIN -1.5f #define X_MAX 1.5f #define Y_MIN -3.2f #define Y_MAX 2.0f #define X_DIM %(XDIM)s #define Y_DIM %(YDIM)s typedef pycuda::complex&lt;float&gt; cmplx; const int nstates = %(NGENERATORS)s; __device__ curandState_t* states[nstates]; extern "C" { __global__ void init_kernel(int seed) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx &lt; nstates) { curandState_t* s = new curandState_t; if (s != 0) { curand_init(seed, idx, 0, s); } states[idx] = s; } else { printf("forbidden memory access %%d/%%d\\n", idx, nstates); } } } __device__ void write_pixel(int idx, cmplx *nums, int *canvas) { float px = nums[2*idx].imag(); float py = nums[2*idx].real(); px -= X_MIN; py -= Y_MIN; px /= X_MAX - X_MIN; py /= Y_MAX - Y_MIN; px *= X_DIM; py *= Y_DIM; int ix = (int)floorf(px); int iy = (int)floorf(py); if (0 &lt;= ix &amp; ix &lt; X_DIM &amp; 0 &lt;= iy &amp; iy &lt; Y_DIM) { canvas[iy*X_DIM + ix] += 1; } } __device__ void generate_random_complex(float real, float imag, int idx, cmplx *nums, float *dists, int *counts) { real *= X_MAX-X_MIN+3; real += X_MIN-2; imag *= Y_MAX-Y_MIN+0; imag += Y_MIN-0; nums[2*idx+1] = cmplx(real, imag); nums[2*idx] = cmplx(real, imag); dists[idx] = 0; counts[idx] = 0; } extern "C" {__global__ void buddha_kernel(int *counts, cmplx *nums, float *dists, int *canvas) { int idx = threadIdx.x + blockIdx.x * blockDim.x; int i, j; float real, imag; if (idx &lt; nstates) { curandState_t s = *states[idx]; for(i = 0; i &lt; 10000; i++) { real = curand_uniform(&amp;s); imag = curand_uniform(&amp;s); generate_random_complex(real, imag, idx, nums, dists, counts); while (counts[idx] &lt; %(ITERS)s &amp; dists[idx] &lt; 5) { counts[idx]++; nums[2*idx] = nums[2*idx]*nums[2*idx] + nums[2*idx+1]; dists[idx] = abs(nums[2*idx]); } if (dists[idx] &gt; 5) { nums[2*idx] = cmplx(0,0); for (j = 0; j &lt; counts[idx]+1; j++) { nums[2*idx] = nums[2*idx]*nums[2*idx] + nums[2*idx+1]; write_pixel(idx, nums, canvas); } } } *states[idx] = s; } else { printf("forbidden memory access %%d/%%d\\n", idx, nstates); } } } """ def print_stats(cpu_canvas, elapsed_time, x_dim, y_dim): total_iterations = np.sum(cpu_canvas) max_freq = np.max(cpu_canvas) min_freq = np.min(cpu_canvas) print("\tTotal iterations: %.5e" % total_iterations) print("\tIterations per pixel: %.2f" % (total_iterations / (x_dim*y_dim),)) print("\tMaximum frequency: %d" % max_freq) print("\tMinimum frequency: %d" % min_freq) print("\tTotal time: %.2fs" % (elapsed_time,)) print("\tIterations per second: %.2e" % (total_iterations / (elapsed_time),)) def format_and_save(cpu_canvas, x_dim, y_dim, threads, iters): cpu_canvas /= np.max(cpu_canvas) cpu_canvas.shape = (y_dim, x_dim) # this just makes the color gradient more visually pleasing cpu_canvas = np.minimum(1.1*cpu_canvas, cpu_canvas*.2+.8) file_name = "pycuda_%dx%d_%d_%d.png" % (x_dim, y_dim, iters, threads) print("\n\tSaving %s..." % file_name) scipy.misc.toimage(cpu_canvas, cmin=0.0, cmax=1.0).save(file_name) print("\tImage saved!\n") def generate_image(x_dim, y_dim, iters): threads = 2**6 b_s = 2**10 device = Device(0) print("\n\t" + device.name(), "\n") context = device.make_context() formatted_code = code % { "NGENERATORS" : threads*b_s, "XDIM" : x_dim, "YDIM" : y_dim, "ITERS" : iters } # generate kernel and setup random number generation module = SourceModule(formatted_code, no_extern_c=True) init_func = module.get_function("init_kernel") fill_func = module.get_function("buddha_kernel") seed = np.int32(np.random.randint(0, 1&lt;&lt;31)) init_func(seed, block=(b_s,1,1), grid=(threads,1,1)) # initialize all numpy arrays samples = gpuarray.zeros(2*threads*b_s, dtype = np.complex64) dists = gpuarray.zeros(threads*b_s, dtype = np.float32) counts = gpuarray.zeros(threads*b_s, dtype = np.int32) canvas = gpuarray.zeros(y_dim*x_dim, dtype = np.int32) # start calculation t0 = time.time() fill_func(counts, samples, dists, canvas, block=(b_s,1,1), grid=(threads,1,1)) context.synchronize() t1 = time.time() # fetch buffer from gpu and save as image cpu_canvas = canvas.get().astype(np.float64) context.pop() print_stats(cpu_canvas, t1-t0, x_dim, y_dim) format_and_save(cpu_canvas, x_dim, y_dim, threads, iters) if __name__ == "__main__": x_dim = 1440 y_dim = 2560 iters = 20 generate_image(x_dim, y_dim, iters) </code></pre> <p>Here's a sample output when I run it on my laptop:</p> <pre><code>GeForce GTX 1050 Total iterations: 5.84026e+08 Iterations per pixel: 158.43 Maximum frequency: 917 Minimum frequency: 0 Total time: 3.85s Iterations per second: 1.52e+08 Saving pycuda_1440x2560_20_64.png... Image saved! </code></pre> <p>This runs pretty fast, but I'm hoping to squeeze some more performance out of it, and learn some more about GPU programming. I don't really know if I'm doing it right. The main reason that I think that this can be sped up is that I wrote a multithreaded CPU solution of this a few years ago, and it is almost as fast as this CUDA implementation (speed difference is less than a factor 4).</p> <p>Any tips on making this run faster, or general things to think about when coding for CUDA would be appreciated!</p> <p>EDIT: I know that there are optimizations related to this specific problem that can be implemented, mainly regarding sampling. I plan on implementering some importance sampling, but for this question I'm mostly interested in general CUDA practices. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T09:55:20.127", "Id": "397574", "Score": "0", "body": "Are you sure everything is correct in your code? Just looked at the last edit: 1) In `write_pixel(...)` you pass `temp` but overwrite it immediately. You pass `ix` and `iy` and n...
[ { "body": "<p>Why using <code>binary and</code> instead of <code>logical and</code> in <code>write_pixel</code>:</p>\n\n<pre><code>if (0 &lt;= ix &amp; ix &lt; X_DIM &amp; 0 &lt;= iy &amp; iy &lt; Y_DIM) {\n canvas[iy*X_DIM + ix] += 1;\n }\n</code></pre>\n\n<p>And why not moving (and changing a bit) the chec...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T08:53:56.583", "Id": "205592", "Score": "8", "Tags": [ "python", "c++", "performance", "fractals", "cuda" ], "Title": "Speeding up Buddhabrot calculation in PyCuda" }
205592
<p>This is my first 'real' project in C# , i looked up some tutorials on the Internet for Tic Tac Toe. But they were not how i wanted it to be, so i came up with some own ideas and wanted some tips on improvement, because i know some things could be different. I simply don't really know how. </p> <p>So here is my Code. You can try it on your own. <strong>You will need 2 Images for the X and O and upload them by yourself (size required to fit into the buttons 201x146 px)!</strong><br> <strong>Also you will need to add the Visual Basic.dll as a Reference.</strong> </p> <pre><code>using System; using System.IO; using System.Resources; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using Microsoft.VisualBasic; using System.Threading.Tasks; using System.Windows.Forms; namespace TicTacToe { public partial class Form1 : Form { Boolean player1 = true; //// player1's turn or not Image x = Properties.Resources.x; /// Image for Player 1, in this case X Image o = Properties.Resources.o; /// Image for Player 2, in this case O string p1 = "Player 1"; /// default name for Player 1 string p2 = "Player 2"; /// default name for Player 2 int winp1 = 0; /// score counter for Player 1 int winp2 = 0; /// score counter for Player 2 int drawcount = 0; /// counts how many field got clicked Boolean won = false; /// state if someone won public Form1() { InitializeComponent(); this.Icon = Properties.Resources.icon; /* Icon for Form */ p1 = Interaction.InputBox("Player 1","Playername",p1); /* Inputbox from VisualBasic to Enter a Name for Player 1 */ if (p1 == "") p1 = "Player 1"; p2 = Interaction.InputBox("Player 2","Playername",p2); /* Inputbox from VisualBasic to Enter a Name for Player 2 */ if (p2 == "") p2 = "Player 2"; turn.Text = p1; /* shows text at the beginning whos turn it is, in this case Player 1 */ p1winstxt.Text = p1; /* sets the name for the score table for Player 1 */ p2winstxt.Text = p2; /* sets the name for the score table for Player 1 */ } public void Playerstatus() /* checks whos turn it is */ { if(player1 == true) { player1 = false; turn.Text = p2; } else { player1 = true; turn.Text = p1; } drawcount++; Checkwin(); } public void Checkwin() /* checks if someone won, if not then check if all buttons have been clicked */ { if(ul.Image == x &amp;&amp; uc.Image == x &amp;&amp; ur.Image == x) { P1win(); } else if(ul.Image == o &amp;&amp; uc.Image == o &amp;&amp; ur.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (ul.Image == x &amp;&amp; cc.Image == x &amp;&amp; br.Image == x) { P1win(); } else if(ul.Image == o &amp;&amp; cc.Image == o &amp;&amp; br.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (ul.Image == x &amp;&amp; cl.Image == x &amp;&amp; bl.Image == x) { P1win(); } else if (ul.Image == o &amp;&amp; cl.Image == o &amp;&amp; bl.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (uc.Image == x &amp;&amp; cc.Image == x &amp;&amp; bc.Image == x) { P1win(); } else if(uc.Image == o &amp;&amp; cc.Image == o &amp;&amp; bc.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (ur.Image == x &amp;&amp; cr.Image == x &amp;&amp; br.Image == x) { P1win(); } else if(ur.Image == o &amp;&amp; cr.Image == o &amp;&amp; br.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (ur.Image == x &amp;&amp; cc.Image == x &amp;&amp; bl.Image == x) { P1win(); } else if(ur.Image == o &amp;&amp; cc.Image == o &amp;&amp; bl.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (cr.Image == x &amp;&amp; cc.Image == x &amp;&amp; cl.Image == x) { P1win(); } else if(cr.Image == o &amp;&amp; cc.Image == o &amp;&amp; cl.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (bl.Image == x &amp;&amp; bc.Image == x &amp;&amp; br.Image == x) { P1win(); } else if(bl.Image == o &amp;&amp; bc.Image == o &amp;&amp; br.Image == o) { P2win(); } /*-------------------------------------------------------------------------------*/ if (drawcount == 9) /* checks if all 9 buttons have been clicked */ { if (won == false) { tie(); } } } private void ol_Click(object sender, EventArgs e) { if(player1 == true) { ul.Image = x; Playerstatus(); } else { ul.Image = o; Playerstatus(); } ul.Enabled = false; } private void om_Click(object sender, EventArgs e) { if (player1 == true) { uc.Image = x; Playerstatus(); } else { uc.Image = o; Playerstatus(); } uc.Enabled = false; } private void or_Click(object sender, EventArgs e) { if (player1 == true) { ur.Image = x; Playerstatus(); } else { ur.Image = o; Playerstatus(); } ur.Enabled = false; } private void ml_Click(object sender, EventArgs e) { if (player1 == true) { cl.Image = x; Playerstatus(); } else { cl.Image = o; Playerstatus(); } cl.Enabled = false; } private void mm_Click(object sender, EventArgs e) { if (player1 == true) { cc.Image = x; Playerstatus(); } else { cc.Image = o; Playerstatus(); } cc.Enabled = false; } private void mr_Click(object sender, EventArgs e) { if (player1 == true) { cr.Image = x; Playerstatus(); } else { cr.Image = o; Playerstatus(); } cr.Enabled = false; } private void ul_Click(object sender, EventArgs e) { if (player1 == true) { bl.Image = x; Playerstatus(); } else { bl.Image = o; Playerstatus(); } bl.Enabled = false; } private void um_Click(object sender, EventArgs e) { if (player1 == true) { bc.Image = x; Playerstatus(); } else { bc.Image = o; Playerstatus(); } bc.Enabled = false; } private void ur_Click(object sender, EventArgs e) { if (player1 == true) { br.Image = x; Playerstatus(); } else { br.Image = o; Playerstatus(); } br.Enabled = false; } public void P1win() /* Player 1 won */ { MessageBox.Show(p1 + " won!"); foreach (Control c in Controls) /* disables all buttons */ { Button b = c as Button; if (b != null) { b.Enabled = false; } } res.Enabled = true; /* reactivates the reset button */ winp1++; drawcount = 0; p1wins.Text = winp1.ToString(); won = true; } public void P2win() /* Player 2 won */ { MessageBox.Show(p2 + " won!"); foreach (Control c in Controls) { Button b = c as Button; if (b != null) { b.Enabled = false; } } res.Enabled = true; winp2++; p2wins.Text = winp2.ToString(); drawcount = 0; won = true; } public void Resetgame() /* resets the game */ { turn.Text = p1; player1 = true; foreach (Control c in Controls) { Button b = c as Button; if(b != null) { b.Enabled = true; b.Image = null; } } } private void res_Click(object sender, EventArgs e) { Resetgame(); } public void tie() /* MessageBox for Tie */ { MessageBox.Show("Tie!"); } private void resetscore_Click(object sender, EventArgs e) /* resets the score */ { winp1 = 0; winp2 = 0; p1wins.Text = winp1.ToString(); p2wins.Text = winp1.ToString(); } } } </code></pre> <p><strong>-- CONTENT OF Form1.Designer.cs --</strong></p> <pre><code> private void InitializeComponent() { this.ul = new System.Windows.Forms.Button(); this.uc = new System.Windows.Forms.Button(); this.ur = new System.Windows.Forms.Button(); this.cl = new System.Windows.Forms.Button(); this.cc = new System.Windows.Forms.Button(); this.cr = new System.Windows.Forms.Button(); this.bl = new System.Windows.Forms.Button(); this.bc = new System.Windows.Forms.Button(); this.turn = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.br = new System.Windows.Forms.Button(); this.res = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.resetscore = new System.Windows.Forms.Button(); this.p2wins = new System.Windows.Forms.Label(); this.p1wins = new System.Windows.Forms.Label(); this.p2winstxt = new System.Windows.Forms.Label(); this.p1winstxt = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // ul // this.ul.Location = new System.Drawing.Point(29, 54); this.ul.Name = "ul"; this.ul.Size = new System.Drawing.Size(201, 146); this.ul.TabIndex = 0; this.ul.TabStop = false; this.ul.UseVisualStyleBackColor = true; this.ul.Click += new System.EventHandler(this.ol_Click); // // uc // this.uc.Location = new System.Drawing.Point(226, 54); this.uc.Name = "uc"; this.uc.Size = new System.Drawing.Size(201, 146); this.uc.TabIndex = 1; this.uc.TabStop = false; this.uc.UseVisualStyleBackColor = true; this.uc.Click += new System.EventHandler(this.om_Click); // // ur // this.ur.Location = new System.Drawing.Point(424, 54); this.ur.Name = "ur"; this.ur.Size = new System.Drawing.Size(201, 146); this.ur.TabIndex = 2; this.ur.TabStop = false; this.ur.UseVisualStyleBackColor = true; this.ur.Click += new System.EventHandler(this.or_Click); // // cl // this.cl.Location = new System.Drawing.Point(29, 194); this.cl.Name = "cl"; this.cl.Size = new System.Drawing.Size(201, 146); this.cl.TabIndex = 3; this.cl.TabStop = false; this.cl.UseVisualStyleBackColor = true; this.cl.Click += new System.EventHandler(this.ml_Click); // // cc // this.cc.Location = new System.Drawing.Point(226, 194); this.cc.Name = "cc"; this.cc.Size = new System.Drawing.Size(201, 146); this.cc.TabIndex = 4; this.cc.TabStop = false; this.cc.UseVisualStyleBackColor = true; this.cc.Click += new System.EventHandler(this.mm_Click); // // cr // this.cr.Location = new System.Drawing.Point(424, 194); this.cr.Name = "cr"; this.cr.Size = new System.Drawing.Size(201, 146); this.cr.TabIndex = 5; this.cr.TabStop = false; this.cr.UseVisualStyleBackColor = true; this.cr.Click += new System.EventHandler(this.mr_Click); // // bl // this.bl.Location = new System.Drawing.Point(29, 336); this.bl.Name = "bl"; this.bl.Size = new System.Drawing.Size(201, 146); this.bl.TabIndex = 6; this.bl.TabStop = false; this.bl.UseVisualStyleBackColor = true; this.bl.Click += new System.EventHandler(this.ul_Click); // // bc // this.bc.Location = new System.Drawing.Point(226, 336); this.bc.Name = "bc"; this.bc.Size = new System.Drawing.Size(201, 146); this.bc.TabIndex = 7; this.bc.TabStop = false; this.bc.UseVisualStyleBackColor = true; this.bc.Click += new System.EventHandler(this.um_Click); // // turn // this.turn.AutoSize = true; this.turn.Location = new System.Drawing.Point(46, 30); this.turn.Name = "turn"; this.turn.Size = new System.Drawing.Size(37, 13); this.turn.TabIndex = 10; this.turn.Text = "----------"; // // groupBox1 // this.groupBox1.Controls.Add(this.turn); this.groupBox1.Location = new System.Drawing.Point(650, 54); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(139, 69); this.groupBox1.TabIndex = 11; this.groupBox1.TabStop = false; this.groupBox1.Text = "Turn"; // // br // this.br.Location = new System.Drawing.Point(424, 336); this.br.Name = "br"; this.br.Size = new System.Drawing.Size(201, 146); this.br.TabIndex = 8; this.br.TabStop = false; this.br.UseVisualStyleBackColor = true; this.br.Click += new System.EventHandler(this.ur_Click); // // res // this.res.Location = new System.Drawing.Point(650, 139); this.res.Name = "res"; this.res.Size = new System.Drawing.Size(139, 23); this.res.TabIndex = 12; this.res.TabStop = false; this.res.Text = "Reset"; this.res.UseVisualStyleBackColor = true; this.res.Click += new System.EventHandler(this.res_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.resetscore); this.groupBox2.Controls.Add(this.p2wins); this.groupBox2.Controls.Add(this.p1wins); this.groupBox2.Controls.Add(this.p2winstxt); this.groupBox2.Controls.Add(this.p1winstxt); this.groupBox2.Location = new System.Drawing.Point(650, 336); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(139, 146); this.groupBox2.TabIndex = 13; this.groupBox2.TabStop = false; this.groupBox2.Text = "Score"; // // resetscore // this.resetscore.Location = new System.Drawing.Point(10, 93); this.resetscore.Name = "resetscore"; this.resetscore.Size = new System.Drawing.Size(120, 23); this.resetscore.TabIndex = 4; this.resetscore.TabStop = false; this.resetscore.Text = "Reset"; this.resetscore.UseVisualStyleBackColor = true; this.resetscore.Click += new System.EventHandler(this.resetscore_Click); // // p2wins // this.p2wins.AutoSize = true; this.p2wins.Location = new System.Drawing.Point(91, 37); this.p2wins.Name = "p2wins"; this.p2wins.Size = new System.Drawing.Size(13, 13); this.p2wins.TabIndex = 3; this.p2wins.Text = "0"; // // p1wins // this.p1wins.AutoSize = true; this.p1wins.Location = new System.Drawing.Point(10, 37); this.p1wins.Name = "p1wins"; this.p1wins.Size = new System.Drawing.Size(13, 13); this.p1wins.TabIndex = 2; this.p1wins.Text = "0"; // // p2winstxt // this.p2winstxt.AutoSize = true; this.p2winstxt.Location = new System.Drawing.Point(88, 20); this.p2winstxt.Name = "p2winstxt"; this.p2winstxt.Size = new System.Drawing.Size(45, 13); this.p2winstxt.TabIndex = 1; this.p2winstxt.Text = "Player 2"; // // p1winstxt // this.p1winstxt.AutoSize = true; this.p1winstxt.Location = new System.Drawing.Point(7, 20); this.p1winstxt.Name = "p1winstxt"; this.p1winstxt.Size = new System.Drawing.Size(45, 13); this.p1winstxt.TabIndex = 0; this.p1winstxt.Text = "Player 1"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(813, 565); this.Controls.Add(this.groupBox2); this.Controls.Add(this.res); this.Controls.Add(this.br); this.Controls.Add(this.bc); this.Controls.Add(this.bl); this.Controls.Add(this.cr); this.Controls.Add(this.cc); this.Controls.Add(this.cl); this.Controls.Add(this.ur); this.Controls.Add(this.uc); this.Controls.Add(this.ul); this.Controls.Add(this.groupBox1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "TicTacToe"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button ul; private System.Windows.Forms.Button uc; private System.Windows.Forms.Button ur; private System.Windows.Forms.Button cl; private System.Windows.Forms.Button cc; private System.Windows.Forms.Button cr; private System.Windows.Forms.Button bl; private System.Windows.Forms.Button bc; private System.Windows.Forms.Button br; private System.Windows.Forms.Label turn; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button res; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label p2wins; private System.Windows.Forms.Label p1wins; private System.Windows.Forms.Label p2winstxt; private System.Windows.Forms.Label p1winstxt; private System.Windows.Forms.Button resetscore; } } </code></pre> <p><a href="https://i.stack.imgur.com/IFd8m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IFd8m.png" alt="This is the X i used"></a> <a href="https://i.stack.imgur.com/QYlkf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QYlkf.png" alt="This is the O i used"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T09:34:32.967", "Id": "396567", "Score": "1", "body": "I'd be great if you could add the images to the question," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T10:11:28.243", "Id": "396575", "...
[ { "body": "<h2>A Quick Note</h2>\n<p>First, welcome to CodeReview.SE! Secondly, welcome to the <code>C#</code> world! Your question in general is likely to receive a lot of opinion based answers, but from a <code>CodeReview</code> standpoint, I'll be glad to point out some things that could be updated. My revie...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T09:27:40.983", "Id": "205594", "Score": "7", "Tags": [ "c#", "beginner", "tic-tac-toe", "winforms" ], "Title": "Tic Tac Toe with images" }
205594
<p>I have just finished a small program for Tower of Hanoi using recursion. I did it to practice OOP which I recently learnt. It took me about 2 hours to research about the recursive algorithm and write out the code. It works, after much debugging... However, after comparing to other implementations, I realised my code is rather long, plus unconventional when it comes to how I approach and execute as well as the naming conventions.</p> <p>Could I have some feedback about the program? Thank you!</p> <pre><code>class rod: move_count = 0 def __init__(self,disks=[],position=""): self.diskslist=disks self.rod_position=position # Remove the top disk of a rod def remove_top(self): print(f"Move the disk of size {self.diskslist[0].size} from {self.rod_position} Rod ", end="") rod.move_count += 1 return self.diskslist.pop(0) # Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it def add_to_top(self,current_disk,announce=True): if len(self.diskslist) == 0: if announce==True: print(f"on to the top of the {self.rod_position} Rod", end="\n") self.diskslist.insert(0,current_disk) return True else: if current_disk.size &lt; self.diskslist[-1].size: if announce == True: print(f"on to the top of the {self.rod_position} Rod", end="\n") self.diskslist.insert(0,current_disk) return True else: return False class disk: num=0 def __init__(self,size): self.size=size disk.num += 1 #Generating 8 disks of increasing size disk_num=8 disks = [] for i in range(disk_num): disks.append(disk(i)) #Generating 3 rods rods = [] rods.append(rod([],"Left")) rods.append(rod([],"Middle")) rods.append(rod([],"Right")) # Attaching all disks to the left rod for i in range(len(disks)): rods[0].add_to_top(disks[len(disks)-i-1],False) def recursive_solve(current_rod, lower_range, target_rod): # If only moving the top disk, execute it if lower_range == 0: rods[target_rod].add_to_top(rods[current_rod].remove_top()) # If not, keeping simplifying the recursion. else: alt_rod = 3 - current_rod - target_rod recursive_solve(current_rod, lower_range - 1, alt_rod) recursive_solve(current_rod, 0, target_rod) recursive_solve(alt_rod, lower_range - 1, target_rod) print(f"The steps needed to move {disk_num} pieces of disks are:") recursive_solve(0,len(disks)-1,2) for i in range(len(rods)): print(f'\n For rod number {i+1}:',end=" ") for j in range(len(rods[i].diskslist)): print(rods[i].diskslist[j].size,end=" ") print(f'\n The number of moves taken in total is {rod.move_count}') </code></pre>
[]
[ { "body": "<p>Your code seems to be working and trying to use OOP is a nice touch.\nLet's see what can be improved.</p>\n\n<p><strong>Style</strong></p>\n\n<p>There is an official standard Python style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. This...
{ "AcceptedAnswerId": "205598", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T10:28:36.877", "Id": "205597", "Score": "12", "Tags": [ "python", "algorithm", "python-3.x", "recursion", "tower-of-hanoi" ], "Title": "Tower of Hanoi Recursive Implementation using Python with OOP" }
205597
<p>(Somewhat) new to python and coding in general! Using python 3.7 and pandas, I'm running code to create a searchable list of people in my dataframe, and I feel like my way of telling duplicates apart is very roundabout. I would love some advice on making it simpler and more efficient. </p> <p>I have a database in pandas, 'df2', which has three relevant rows: 'First Name', 'Last Name' and 'People ID'. Some people will have the same name, and these can be told apart by their 'People ID'. I start by making the 'Name' column as thus:</p> <pre><code>df2['Name'] = df2['First Name'] + ' ' + df2['Last Name'] </code></pre> <p>Now I make a Dict, nameid, to find out how many different People IDs are associated to each unique 'Name' string.</p> <pre><code>nameid = {} for i in df2.index: try: nameid[df2.loc[i, 'Name']].append(df2.loc[i, 'People ID']) except: nameid[df2.loc[i, 'Name']] = [df2.loc[i, 'People ID']] </code></pre> <p>There are multiple occurences of each person in the spreadsheet, so I want to just have each unique instance of a different 'People ID' using set().</p> <pre><code>for i in nameid.keys(): nameid[i] = list(set(nameid[i])) </code></pre> <p>Now I create a second dict, namead, which is a "filtered" version of nameid where we've removed all reviewer names with just one ID value associated (those are fine as they are). </p> <pre><code>namead = {} for i in nameid.keys(): paceholder = ['Nothing'] try: paceholder.append(nameid[i][1]) namead[i] = nameid[i] except: pass </code></pre> <p>Finally, I use namead to make dupes, the list of index values of df2 where there are names belonging to different reviewers. I then pass that through df2 to add the 'People ID' to those names and ensure there is no confusion.</p> <pre><code>dupes = [i for i in df2.index if df2.loc[i, 'Name'] in namead.keys()] for i in duperevs: df2.loc[i, 'Name'] += ' ' + str(df2.loc[i, 'People ID']) </code></pre> <p>Whew! I feel like I added several layers of complexity here but I'm not sure where to start - help would be much appreciated!</p> <p>EDIT - I'm not sure how to put an extract of the dataframe in this textbox. Clarification: each row of data has information, and I need it to be searchable by name for the end user, with a placeholder to differentiate identical names (the People ID). The resulting data looks like: "Frank Jones / 14498", "Mitin Nutil / 35589", "Maveh Kadini 1433 / 1433" (indicating that there's more than one Maveh Kadini in the data). Each person (by People ID) will appear in many different rows of data.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T14:17:35.883", "Id": "396592", "Score": "1", "body": "Can you give an example dataframe of ~15/20 people and the expected result?" } ]
[ { "body": "<blockquote>\n <p>There are multiple occurences of each person in the spreadsheet, so I want to just have each unique instance of a different 'People ID' using set().</p>\n</blockquote>\n\n<p><code>df.groupby('Name').apply(set)</code></p>\n\n<blockquote>\n <p>Now I create a second dict, namead, whi...
{ "AcceptedAnswerId": "205612", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T13:42:31.603", "Id": "205600", "Score": "0", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Python Pandas - finding duplicate names and telling them apart" }
205600
<p>I am formatting a data result from the array of objects that looks like this:</p> <pre><code>const data = { periods: [{ month: 'January', sickLeave: { differance: '-12000', revision: '6000', paid: '18000', }, holidayLeave: { differance: '10000', revision: '22000', paid: '12000', }, received: '-2000', taken: '2000', result: '0', }, { month: 'Februar', sickLeave: { differance: '-8000', revision: '6000', paid: '18000', }, holidayLeave: { differance: '10000', revision: '22000', paid: '12000', }, received: '-2000', taken: '2000', result: '0', }], }; </code></pre> <p>What I want to do with this is to make a new array that looks like this:</p> <pre><code>[{ name: "sickLeaveDifferance", result: ["-12000", "-8000"] }, { name: "sickLeaveRevision", result: ["6000", "6000"] }, { name: "sickLeavePaid", result: ["18000", "18000"] }, { name: "holidayLeaveDifferance", result: ["10000", "10000"] }, { name: "holidayLeaveRevision", result: ["22000", "22000"] }, { name: "holidayLeavePaid", result: ["12000", "12000"] }, { name: "received", result: ["-2000", "-2000"] }, { name: "taken", result: ["2000", "2000"] }, { name: "result", result: ["0", "0"] }] </code></pre> <p>I am achieving this with this function:</p> <pre><code>const formattedResult = perioder =&gt; { let resultArray = []; const pushNewValue = (key, value) =&gt; { const objectExists = resultArray.find(e =&gt; e.name === key); if (objectExists) { objectExists.result.push(value) } else { resultArray.push({ name: key, result: [value] }) } }; perioder.map(el =&gt; Object.entries(el).forEach(([key, value]) =&gt; { if (key != 'month') { if (key === 'sickLeave' || key === 'holidayLeave') { const prop = key; Object.entries(value).forEach(([key, value]) =&gt; { const name = `${prop + key[0].toUpperCase() + key.slice(1)}`; pushNewValue(name, value); }) } else { pushNewValue(key, value); } } })) return resultArray; } </code></pre> <p>But, I feel like there is a better, more elegant way of achieving this, just not sure how to do this?</p> <p>Here is the <a href="https://jsfiddle.net/mb5hz36a/" rel="nofollow noreferrer">fiddle</a>.</p>
[]
[ { "body": "<p>Do you really anticipate the data model changing so much that this needs to be ultra flexible? In order to do so the code is quite complex - for instance having a forEach inside of an if inside of a forEach inside of a map. You already have model specific checks in the code anyways, such as the ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T14:03:18.437", "Id": "205601", "Score": "0", "Tags": [ "javascript", "array" ], "Title": "Formatting data in array with objects" }
205601
<h2>Overview</h2> <p>I was challenged recently to write some code that could find the smallest integer that when multiplied and divided by <strong>2</strong> or <strong>3</strong>, retained all of its digits and gained no extras. For example:</p> <ul> <li>With <strong>2</strong> <ul> <li><strong>285714</strong> <ol> <li>When multiplied: <strong>571428</strong>.</li> <li>When divided: <strong>142857</strong>.</li> </ol></li> </ul></li> <li>With <strong>3</strong> <ul> <li><strong>31046895</strong> <ol> <li>When multiplied: <strong>93140685</strong>.</li> <li>When divided: <strong>10348965</strong>.</li> </ol></li> </ul></li> </ul> <hr> <h2>Code</h2> <p>You'll need the following <code>using</code> statements:</p> <pre><code>using System; using System.Collections.Generic; using static System.Console; </code></pre> <p>The <code>Main</code> method contents:</p> <pre><code>int variant = 2; for (int i = 0; i &lt; int.MaxValue; i++) if (ProductAndFactor(i, variant)) { WriteLine(i); break; } WriteLine("Done"); ReadKey(); </code></pre> <p>The backbone code:</p> <pre><code>static bool ProductAndFactor(int i, int v) { Dictionary&lt;char, int&gt; oChars = GetValueChars(i); Dictionary&lt;char, int&gt; dChars = GetValueChars(i / v); Dictionary&lt;char, int&gt; mChars = GetValueChars(i * v); if ($"{i}".Length != $"{i / v}".Length || $"{i}".Length != $"{i * v}".Length) return false; foreach (char c in oChars.Keys) { if (!dChars.ContainsKey(c)) return false; else if (dChars[c] != oChars[c]) return false; else if (!pChars.ContainsKey(c)) return false; else if (pChars[c] != oChars[c]) return false; } WriteLine($"{i} * {v} = {i * v}\n{i} / {v} = {i / v}"); return true; } static Dictionary&lt;char, int&gt; GetValueChars(int i) { Dictionary&lt;char, int&gt; chars = new Dictionary&lt;char, int&gt;(); foreach (char c in i.ToString()) { if (chars.ContainsKey(c) chars[c]++; else chars.Add(c, 1); } return chars; } </code></pre> <hr> <h2>My Question</h2> <p>Is there a more simplistic way to accomplish this? I can't help but feel like there is and that using <code>Dictionary&lt;char, int&gt;</code> is probably an inefficient option in this task unless there is a smart way to reuse it.</p> <ul> <li>Is there a more simplistic way to accomplish this?</li> <li>Are there more efficient data types to utilize in this use-case? <ul> <li>What are they?</li> <li>Why are they more efficient?</li> </ul></li> <li>Is there a smarter way to reach the answer faster?</li> </ul> <p>Also, if I used the wrong tags, or more tags are needed, please edit and add them.</p> <hr> <h2>Benchmarks</h2> <p>For <code>v = 2</code> the discovery time was <strong>4</strong> seconds. For <code>v = 3</code> the discovery time was <strong>112</strong> seconds.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T16:44:58.063", "Id": "396602", "Score": "0", "body": "I'm not happy with the [tag:performance] tag. Usually when I see it I expect to find some benchmarks and measurements etc. in the question because without them it's very difficul...
[ { "body": "<p>The trick is to search for <code>j = i / v</code> instead of <code>j = i</code>:</p>\n\n<p>that means to search for <code>i and i * v and i * v * v</code>:</p>\n\n<pre><code>static bool ProductAndFactor(int i, int v)\n{\n if ($\"{i}\".Length != $\"{i * v}\".Length ||\n $\"{i}\".Length != $\"...
{ "AcceptedAnswerId": "205625", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T16:31:57.780", "Id": "205613", "Score": "3", "Tags": [ "c#", "performance" ], "Title": "Product and Factor" }
205613
<p>This is a little program to show how a WAVe-File Generator could be written. It use a Function-Object "SinFunction" to calculate the value of any point of the amplitude in time. This object and two floats are given to the constructor of the generator object. The two floats are the frequency and the duration of the created signal.</p> <p>You could give it other Function-Objects to produce the function of any expression you can write in C++. Or you could give <code>SinFunction</code> different frequency and/or duration values.</p> <pre><code>#include &lt;iostream&gt; /* Write File */ #include &lt;fstream&gt; #include &lt;string&gt; /* File Name Parameter */ #include &lt;math.h&gt; /* sin */ using namespace std; class SinFunction{ public: float operator() (float x){ return sin(x); } }; template &lt;class Funk&gt; class WaveFileWriter{ private: void longWrite(long x, ofstream &amp;myfile) { long i = x; int i1 = i % 256; i = i - i1; i = i / 256; int i2 = i % 256; i = i - i2; i = i / 256; int i3 = i % 256; i = i - i1; i = i / 256; int i4 = i; unsigned char a = (unsigned char)i1; unsigned char b = (unsigned char)i2; unsigned char c = (unsigned char)i3; unsigned char d = (unsigned char)i4; myfile &lt;&lt; a; myfile &lt;&lt; b; myfile &lt;&lt; c; myfile &lt;&lt; d; } void integerWrite(unsigned int x, ofstream &amp;myfile) { unsigned int i = x; int i1 = i % 256; i = i - i1; i = i / 256; unsigned char a = (unsigned char)i1; unsigned char b = (unsigned char)i; myfile &lt;&lt; a; myfile &lt;&lt; b; } float Frequency; // Frequency of playing Tone float Duration ; // Duration on playing Tone Funk Funktion; public: WaveFileWriter(string FileName, float Frequenz, float Duratione) : Frequency{Frequenz}, Duration{Duratione} { ofstream myfile; // Definition on File Name: "MeinTest.wav" myfile.open (FileName.c_str(), ios::out | ios::binary); // empty Char declaration char h = 0; // +++++++ Header ++++++ // ----- WAV-Header ---- // Chunk Name "RIFF" char RIFF[] = "RIFF"; myfile &lt;&lt; RIFF; // Chunk Lange longWrite(220000, myfile); // RIFF-Typ "WAVE" char WAVE[] = "WAVE"; myfile &lt;&lt; WAVE; // ----- FMT CHUNK ------ // CHUNK-NAME 'FMT char FMT[] = "fmt "; myfile &lt;&lt; FMT; // CHUNK LΓ€nge 10H longWrite(0x10, myfile); // Audio-Format integerWrite(1, myfile); // Kanalzahl integerWrite(2, myfile); // Samplerate (Hz) = 44 000 long SampelsPerSecond = 44100; longWrite(SampelsPerSecond, myfile); // Bytes pro Sekunde = 44 000 longWrite(176000, myfile); // Bytes pro Sampel integerWrite(4, myfile); // Bits pro Sampel integerWrite(16, myfile); // CHUNK-Name 'data' char data[] = "data"; myfile &lt;&lt; data; // CHUNK Lange int Time = 5; long DataLeng = (long)SampelsPerSecond * Time; longWrite(DataLeng, myfile); // +++++ DATA ++++ float result; float value; unsigned int f; for(float m = 0; m &lt;= DataLeng; m++) { // 1. Chanel result = Funktion(M_PI*2*(m/SampelsPerSecond)*Frequency); value = (result * 32767 ) + 32767; f = (unsigned int)value; integerWrite(f, myfile); //2. Chanel result = Funktion(M_PI*2*(m/SampelsPerSecond)*Frequency); value = (result * 32767 ) + 32767; f = (unsigned int)value; integerWrite(f, myfile); // myfile &lt;&lt; (char)value; } // File is writen so close myfile.close(); } }; int main( int argc, const char* argv[] ) { WaveFileWriter&lt;SinFunction&gt; File1{"MyTest.wav", 1000, 5}; return 0; } </code></pre> <p>I'm looking for ideas to refactor it, to make it perfect.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T21:58:31.753", "Id": "396635", "Score": "2", "body": "Why are you writing the WAV header piece-by-piece, rather than declaring a structure?" } ]
[ { "body": "<h2>Dont't use <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std;</code></a></h2>\n\n<hr>\n\n<h2>Use consistent formatting:</h2>\n\n<p>Your vertical whitespace and indentation are inconsistent. That makes your code a l...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T16:34:39.493", "Id": "205614", "Score": "3", "Tags": [ "c++", "audio" ], "Title": "Generate sinusoid as Wave file" }
205614
<p>I'm working on a program that will (hopefully) eventually allow me to perform frame rate analysis like Digital Foundry does. The code below works (as far as I know), but before I iterate on it, I'd like some feedback as I'm new to both C++ and OpenCV. I say "as far as I know" because I'm not sure how "lossless" my lossless capture is or of the correctness of the program. Is this code a good start?</p> <pre><code>#include "opencv2\opencv.hpp" #include &lt;fstream&gt; using namespace cv; using namespace std; int main(int argv, char** argc) { Mat curFrame; Mat pastFrame; VideoCapture vid("E:\\videos\\video.mkv"); ofstream textFile("diffs.txt"); int numDiff = 0; int numFrames = 0; if (!textFile.is_open()) { return -1; } if (!vid.isOpened()) { return -2; } vid.read(pastFrame); while (vid.read(curFrame)) { for (int i = 0; i &lt; curFrame.rows; i += 1) { cv::Vec3b* curPixel = curFrame.ptr&lt;cv::Vec3b&gt;(i); cv::Vec3b* pastPixel = pastFrame.ptr&lt;cv::Vec3b&gt;(i); for (int j = 0; j &lt; curFrame.cols; j += 1) { bool found = false; if (curPixel[j][0] != pastPixel[j][0]) { numDiff += 1; found = true; } else if (!found &amp;&amp; curPixel[j][1] != pastPixel[j][1]) { numDiff += 1; found = true; } else if (!found &amp;&amp; curPixel[j][2] != pastPixel[j][2]) { numDiff += 1; } } } numFrames += 1; //cout &lt;&lt; "Frame " &lt;&lt; numFrames &lt;&lt; endl; double size = curFrame.rows * curFrame.cols; textFile &lt;&lt; numFrames &lt;&lt; "," &lt;&lt; fixed &lt;&lt; setprecision(2) &lt;&lt; numDiff / size * 100 &lt;&lt; "\n"; pastFrame = curFrame.clone(); numDiff = 0; } textFile.close(); vid.release(); return 0; } </code></pre>
[]
[ { "body": "<p>Its pretty good:</p>\n\n<p>Don't do this:</p>\n\n<pre><code>using namespace cv;\nusing namespace std;\n</code></pre>\n\n<p>Its a bad habit that one day will get you into a lot of trouble. The reason the namespace names are so short is so that adding <code>std::</code> or <code>cv::</code> before i...
{ "AcceptedAnswerId": "205636", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T17:46:40.003", "Id": "205618", "Score": "3", "Tags": [ "c++", "edit-distance", "opencv", "video" ], "Title": "Testing Video Frames for Uniqueness" }
205618
<p>I have written my own little auto-generated table class, and I was wondering if you guys can give me some tips on how to make this code more elegant and secure and maybe compact it so I use only one master function to bind everything when I call it out!</p> <p>The DB connection file:</p> <pre><code>&lt;?php $host = 'localhost'; $db = '***'; $user = '***'; $pass = '***'; $charset = 'utf8'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $settings = [ PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES =&gt; false, ]; $pdo = new PDO($dsn, $user, $pass, $settings); </code></pre> <p>The class file:</p> <pre><code>&lt;?php include_once 'db.php'; class FoxyCRUD { /* Properties */ private $conn; private $table; private $where; /* Get database access */ public function __construct(PDO $pdo) { $this-&gt;conn = $pdo; } /* Get database access */ public function __destruct() { $this-&gt;conn = null; } /* Fetch db.table -&gt; column names &amp; type */ public function get_header_elements($table) { // Set table name $this-&gt;table = $table; $query = $this-&gt;conn-&gt;prepare('SHOW FULL COLUMNS FROM '.$this-&gt;table); $query-&gt;execute(); return $query-&gt;fetchAll(PDO::FETCH_ASSOC); } /* Fetch db.table -&gt; column names &amp; type */ public function where() { $query = $this-&gt;conn-&gt;prepare('SHOW FULL COLUMNS FROM '.$this-&gt;table); $query-&gt;execute(); $check_where = $query-&gt;fetchAll(PDO::FETCH_ASSOC); return $check_where[0]['Field']; } /* Fetch all data */ public function get_table_data() { $query = $this-&gt;conn-&gt;prepare('SELECT * FROM '.$this-&gt;table); $query-&gt;execute(); return $query-&gt;fetchAll(); } /* Fetch specific data */ public function get_specific_data($where) { // Set where value $this-&gt;where = $where; $query = $this-&gt;conn-&gt;prepare('SELECT * FROM '.$this-&gt;table.' WHERE '.$this-&gt;where().' = '.$this-&gt;where); $query-&gt;execute(); return $query-&gt;fetchAll(); } } </code></pre> <p>And the index file:</p> <pre><code>&lt;?php include_once 'classes.php'; $foxy_crud = new FoxyCRUD($pdo); ?&gt; &lt;table border="1"&gt; &lt;?php // Generate table header $columns = $foxy_crud-&gt;get_header_elements('login'); foreach ($columns as $column_header =&gt; $column_value) { echo '&lt;th&gt;'.$column_value['Field'].'&lt;/th&gt;'; } // Populate table with data $data = $foxy_crud-&gt;get_table_data(); foreach ($data as $data_text) { echo '&lt;tr&gt;'; // Get data using generated table header names foreach ($columns as $column_data =&gt; $column_value) { echo '&lt;td&gt;'.$data_text[$column_value['Field']].'&lt;/td&gt;'; } echo '&lt;/tr&gt;'; } ?&gt; &lt;/table&gt; &lt;br&gt; &lt;br&gt; &lt;?php // Fetch specific data where ID $fetch_data = $foxy_crud-&gt;get_specific_data('2'); // Fromating fields foreach ($columns as $column_header_type =&gt; $column_value) { // Identify Primary ID $id_key = $column_value['Key']; // Generate label names $name = $column_value['Field']; foreach ($fetch_data as $data_text) { $value = $data_text[$name]; } $name = str_replace('_', ' ', $name); $name = ucwords($name); // Determine field type and maxlength list( $type, $max ) = explode ('(', $column_value['Type']); $max = explode (')', $max)[0]; // Specify how to format each field type switch ($type) { case 'int': $type = 'hidden'; $disable = 'disabled'; $placeholder = ''; $br = ''; break; case 'varchar': $type = 'text'; $disable = ''; $placeholder = $name; $br = '&lt;br&gt;'; break; case 'datetime': $type = 'date'; $disable = ''; $placeholder = ''; $br = '&lt;br&gt;'; break; case 'tinyint': $type = 'tel'; $disable = ''; $placeholder = $name; $br = '&lt;br&gt;'; break; } // Determine if field is type Password - only works if tablea header name is `password` switch ($name) { case 'Password': $type = 'Password'; $disable = ''; $placeholder = $name; $br = '&lt;br&gt;'; break; } // Determine if label text is from Primary ID -&gt; hide switch ($id_key) { case 'PRI': $label = ''; break; default: $label = '&lt;label for="'.$name.'"&gt;'.$name.' ('.$max.')&lt;/label&gt;&lt;br&gt;'; break; } // Generate labels echo $label; // Generate form fields echo '&lt;input type="'.$type.'" name="'.$name.'" id="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'" maxlength="'.$max.'" '.$disable.'&gt;'.$br; } ?&gt; </code></pre> <p>I know this is just the barebones, but I am trying to make this school project fully functioning, and I want to format the code as correctly and as simply as possible.</p>
[]
[ { "body": "<p>Honestly, there are too much issues to address.</p>\n\n<p>First of all, your code is not safe from SQL injection, because of <a href=\"https://phpdelusions.net/pdo/cargo_cult_prepared_statement\" rel=\"nofollow noreferrer\">cargo cult prepared statements</a></p>\n\n<p>Another kind of SQL injection...
{ "AcceptedAnswerId": "205653", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T17:58:46.340", "Id": "205619", "Score": "1", "Tags": [ "php", "mysql", "database", "form", "pdo" ], "Title": "Auto generate database table" }
205619
<p>I've written a simple web service which allows a user to shutdown or reboot a system from the LAN. Although written to be used on an RPI which lacks a power or reset button, it can be used on any Linux system.</p> <p>Aside from the missing secure login (I'm assuming everyone on the network can be trusted at this moment), I'd like to know if there are potential vulnerabilities in this script. Other comments are welcome too.</p> <pre><code># This script serves a simple web page on port 8080 which allows the server to be shut down or restarted remotely. # Both the shutdown and reboot executables must be executable by the owner of the process. # If sudo access is required, ensure no password is required by using NOPASSWD. # EXAMPLE: username myuser = NOPASSWD: /sbin/reboot import cherrypy from os import system cherrypy.server.socket_host = '0.0.0.0' class PyController(object): @cherrypy.expose def index(self): return """&lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;form method="post" action="shutdown"&gt; &lt;button type="submit"&gt;Shut down&lt;/button&gt; &lt;/form&gt; &lt;form method="post" action="restart"&gt; &lt;button type="submit"&gt;Restart&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;""" @cherrypy.expose def shutdown(self): system('sudo shutdown -h now') @cherrypy.expose def restart(self): system('sudo reboot') cherrypy.quickstart(PyController()) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T19:05:03.977", "Id": "205626", "Score": "2", "Tags": [ "python", "linux", "cherrypy" ], "Title": "Shutdown or reboot system from LAN" }
205626
<p>I asked for help accomplishing this on StackExchange.<br> <a href="https://stackoverflow.com/q/52787585/25197">How to efficiently read a large file with a custom newline character using Python?</a> </p> <p>And ended up <a href="https://stackoverflow.com/a/52820814/25197">providing my own answer</a> which is duplicated here. </p> <pre><code>class ChunkedFile(object): """ Yields file in 100 megabyte chunks (by default). If lineterminator is provided reads through file in chunks but yields lines. """ def __init__(self, file_to_process, lineterminator=None): self._file = file_to_process self._lineterminator = lineterminator def read(self, encoding="utf-8", chunk_size=None): one_hundred_megabytes = 100 * 1024 chunk_size = chunk_size or one_hundred_megabytes with self._file.open(encoding=encoding) as f: chunk = "" while True: data = f.read(chunk_size) if not data: # EOF break chunk += data if self._lineterminator is None: yield chunk chunk = "" elif self._lineterminator in chunk: lines = chunk.split(self._lineterminator) chunk = "" if chunk.endswith(self._lineterminator) else lines.pop() for line in lines: if line: # Don't return empty lines. yield line if __name__ == "__main__": longabstract_file = Path(__file__).parent / "longabstract_en.csv" file_chunk_reader = ChunkedFile(longabstract_file, lineterminator="\tl\n") for line in file_chunk_reader.read(): print(line) </code></pre> <p>The code works but I'm interested in further optimizations and proper error handling. Nothing broke when I ran it on a few 1GB+ files so it's a start! </p> <p>PS - I prefer pure Python 3 code (if relevant). Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-04T07:50:25.503", "Id": "399135", "Score": "0", "body": "I'd be great if you could add the problem description to your question so that one doesn't have to navigate over to stack overflow." } ]
[ { "body": "<h3>1. Bug</h3>\n\n<p>If the file does not end with the line terminator, then the last line is lost. That's because the code says:</p>\n\n<pre><code>if not data: # EOF\n break\n</code></pre>\n\n<p>but at this point there might still be an unterminated line remaining in <code>chunk</code>, so this...
{ "AcceptedAnswerId": "205673", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T19:53:21.523", "Id": "205631", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Optimizing large file reads with a custom line terminator in Python" }
205631
<p>I'm just getting started with Python and was hoping for some feedback on a simple Tic-Tac-Toe game I wrote. Specifically, is there a simpler way to check the win conditions for the game, and to break the loops at the end without repeating the code twice, and just generally how to shorten this to achieve a similar effect?</p> <pre><code>print("Player 1 is 'X' and Player 2 is 'O'.\nEnter a number (0-8) to choose a \ space on the board.\nTake turns entering values until someone wins.\n\n[0, 1, 2] \ \n[3, 4, 5]\n[6, 7, 8]") class Player: def __init__(self,num,XO): self.num = num self.XO = XO p1 = Player(1,'X') #odd p2 = Player(2,'O') #even plist = [p1,p2] b = [['0','1','2'], ['3','4','5'], ['6','7','8']] i = 0 while True: for plyr in plist: while True: try: p = int(input(f'Player {plyr.num}, enter a number: ')) row = int(p/3) cel = p%3 if b[row][cel] is not 'X' and b[row][cel] is not 'O': b[row][cel] = plyr.XO break else: print(f"Space already taken by {b[row][cel]}") except ValueError: print("That's not a valid number. Try again and choose 0-8.") bf = f"{b[0]}\n{b[1]}\n{b[2]}" print(bf) i+=1 def CheckWin(b): if b[0][0]==b[0][1]==b[0][2]==plyr.XO or b[0][0]==b[1][0]==b[2][0]==plyr.XO or \ b[0][0]==b[1][1]==b[2][2]==plyr.XO or b[0][1]==b[1][1]==b[2][1]==plyr.XO or \ b[1][0]==b[1][1]==b[1][2]==plyr.XO or b[2][0]==b[2][1]==b[2][2]==plyr.XO or \ b[0][2]==b[1][2]==b[2][2]==plyr.XO: print(f"Player {plyr.num} ('{plyr.XO}') wins!") return 1 else: pass win = CheckWin(b) if not win and i&lt;9: pass elif not win and i==9: print('The match is a tie.') break else: break if not win and i&lt;9: pass elif not win and i==9: break else: break </code></pre>
[]
[ { "body": "<p>First off, I see no reason to define p1 and p2, then put them into the playerlist, it would be more concise to simply define them inside plist's definition. </p>\n\n<p>eg.</p>\n\n<pre><code>plist = [Player(1,'X'), Player(2, 'O')]\n</code></pre>\n\n<p>As for the repetition of the if statements, you...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T19:58:27.290", "Id": "205632", "Score": "1", "Tags": [ "python", "beginner", "tic-tac-toe" ], "Title": "First Python game of Tic-Tac-Toe" }
205632
<p>I had a <code>JSON</code> file in this format:</p> <pre><code>{ "cols": [ "Employee", "start_time" ], "data": [ [ "Serena", "Sat, 22 Aug 2015 14:06:03 -0700" ], [ "Rhonda", "Sun, 25 Mar 2012 10:48:52 -0700" ], [ "Fleur", "Mon, 16 Dec 2013 07:20:26 -0800" ], [ "Giselle", "Sat, 19 Apr 2008 23:47:21 -0700" ], [ "Jeanette", "Thu, 06 Nov 2008 23:02:44 -0800" ], [ "Iliana", "Sun, 13 May 2007 14:22:08 -0700" ], [ "Geraldine", "Tue, 24 Jul 2012 08:43:58 -0700" ], [ "Tatiana", "Thu, 08 Oct 2009 07:56:25 -0700" ], [ "Jessamine", "Wed, 14 Jun 2006 12:03:42 -0700" ] [ "Emily", "Tue, 06 Jan 2015 04:51:06 -0800" ], [ "Sydnee", "Mon, 16 Dec 2013 11:28:04 -0800" ], [ "Zorita", "Wed, 16 Dec 2009 11:22:18 -0800" ] ] } </code></pre> <p>The file has Employee name and start time fields. I wanted to get every employee's name and start time and find the total time they have been in the company (subtracting start time from current time).</p> <p>I first loaded a JSON file using <code>json.load()</code> and then read each record in a loop and store it in a <code>namedtuple</code>. After that I added each <code>namedtuple</code> in a <code>list</code>.</p> <pre><code>import json import pprint import dateutil.parser from collections import namedtuple from datetime import datetime, timezone file_name = "d:/a.json" #Create a named tuple to store all data later, # Total time is Current time - start_time EmployeeData = namedtuple('EM', ["name", "start_time", "total_time"]) # Here I will store final list of all employee tuples final_list = [] # Get string date as input and convert it to datetime object def format_time(string_time): op_time = dateutil.parser.parse(string_time) return op_time with open(file_name, "r") as data: json_data = json.load(data) for record in json_data["data"]: # Time in JSON file also has timezone so i have to use timezone.utc today = datetime.now(timezone.utc) # create date object from string date record[1] = format_time(record[1]) # Find total number of days, tenure = (today - record[1]).days # create a tuple temp_tuple = EmployeeData(name=record[0], start_time = record[1], total_time = tenure) final_list.append(temp_tuple) pprint.pprint(final_list) </code></pre> <p><strong>Output</strong>:</p> <pre><code> EM(name='Whitney', start_time=datetime.datetime(2015, 8, 7, 5, 37, 32, tzinfo=tzoffset(None, -25200)), total_time=1165), EM(name='Deirdre', start_time=datetime.datetime(2009, 8, 19, 15, 50, 27, tzinfo=tzoffset(None, -25200)), total_time=3343), EM(name='Alexandra', start_time=datetime.datetime(2007, 9, 5, 17, 31, 29, tzinfo=tzoffset(None, -25200)), total_time=4057), EM(name='Lila', start_time=datetime.datetime(2011, 8, 27, 8, 8, 47, tzinfo=tzoffset(None, -25200)), total_time=2606), EM(name='TaShya', start_time=datetime.datetime(2009, 1, 1, 18, 15, 1, tzinfo=tzoffset(None, -28800)), total_time=3573), EM(name='Kerry', start_time=datetime.datetime(2013, 6, 20, 13, 39, 30, tzinfo=tzoffset(None, -25200)), total_time=1942)] </code></pre> <p>I then sorted the record using:</p> <pre><code>sorted_time = sorted(final_list, key=lambda y: y.total_time) print(sorted_time) </code></pre> <p>I would like to improve my code further since I will be dealing with a larger files soon. Is there any way to make it more efficient?</p>
[]
[ { "body": "<p>A small issue, that is probably no big deal for this program, but could cause problems over smaller timescales than days:</p>\n\n<pre><code>json_data = json.load(data)\nfor record in json_data[\"data\"]:\n # Time in JSON file also has timezone so i have to use timezone.utc\n today = datetime...
{ "AcceptedAnswerId": "205660", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T20:35:29.677", "Id": "205634", "Score": "0", "Tags": [ "python", "python-3.x", "json" ], "Title": "Namedtuple and list to populate each record of a JSON file" }
205634
<p>I am a total beginner at Python, so I wrote a very simple snake game using pygame to get some practice with it. I also don't have too much experience with object-oriented design. Does the code layout look okay? Is it easy to read and understand? I'm sure it can be simplified some. The update_segments section in particular seems too long and overly complicated. I know there's a way to shorten it, maybe by going through it in reverse order, but it's just not coming to me at the moment.</p> <pre><code>import pygame import random BOARD_SIZE_WIDTH = 25 BOARD_SIZE_HEIGHT = 25 # This will determine the size of the objects drawn on the board. # Must be equal to resolution BOARD_SPACE_SIZE = 20 DISPLAY_RESOLUTION_WIDTH = BOARD_SIZE_WIDTH * BOARD_SPACE_SIZE DISPLAY_RESOLUTION_HEIGHT = BOARD_SIZE_HEIGHT * BOARD_SPACE_SIZE PLAYER1_START_X = 12 PLAYER1_START_Y = 12 COBRA_START_DIRECTION = "Up" # Number of milliseconds between player movements. MOVEMENT_DELAY = 100 SEGMENT_SIZE = 20 # Define the objects that can occupy board spaces. EMPTY = 0 COBRA = 1 FOOD = 2 EMPTY_RECT = pygame.Rect(0, 0, BOARD_SPACE_SIZE, BOARD_SPACE_SIZE) COBRA_RECT = pygame.Rect(0, 0, BOARD_SPACE_SIZE, BOARD_SPACE_SIZE) FOOD_RECT = pygame.Rect(0, 0, BOARD_SPACE_SIZE, BOARD_SPACE_SIZE) RED = (0xFF, 0x00, 0x00) YELLOW = (0xFF, 0xFF, 0x00) BLACK = (0x00, 0x00, 0x00) class board(object): foodOnBoard = False def __init__(self, width, height, spaceSize): self.width = width self.height = height self.spaceSize = spaceSize self.spaces = [[0 for y in range(0, BOARD_SIZE_HEIGHT)] for x in range(0, BOARD_SIZE_WIDTH)] def create_food(self): while self.foodOnBoard == False: x = random.randint(0, BOARD_SIZE_WIDTH - 1) y = random.randint(0, BOARD_SIZE_HEIGHT - 1) if self.spaces[x][y] == EMPTY: self.spaces[x][y] = FOOD self.foodOnBoard = True def draw_board(self, screen): for y in range(0, BOARD_SIZE_HEIGHT): for x in range(0, BOARD_SIZE_WIDTH): drawX = x * BOARD_SPACE_SIZE drawY = y * BOARD_SPACE_SIZE if self.spaces[x][y] == COBRA: pygame.draw.rect(screen, RED, pygame.Rect(drawX, drawY, BOARD_SPACE_SIZE, BOARD_SPACE_SIZE)) elif self.spaces[x][y] == FOOD: pygame.draw.rect(screen, YELLOW, pygame.Rect(drawX, drawY, BOARD_SPACE_SIZE, BOARD_SPACE_SIZE)) elif self.spaces[x][y] == EMPTY: pygame.draw.rect(screen, BLACK, pygame.Rect(drawX, drawY, BOARD_SPACE_SIZE, BOARD_SPACE_SIZE)) class cobra(object): numberOfSegments = 1 sizeOfSegments = SEGMENT_SIZE segments = [] def __init__(self, posX, posY, direction): self.posX = posX self.posY = posY self.direction = direction class segment(object): def __init__(self, posX, posY): self.posX = posX self.posY = posY def add_segment(self, segment): self.segments.append(segment) def move(self): if self.direction == "Up": self.posY -= 1 if self.direction == "Down": self.posY += 1 if self.direction == "Left": self.posX -= 1 if self.direction == "Right": self.posX += 1 def check_collision(board, cobra): if (cobra.posX &lt; 0) or (cobra.posY &lt; 0) or (cobra.posX &gt; BOARD_SIZE_WIDTH - 1)\ or (cobra.posY &gt; BOARD_SIZE_HEIGHT - 1) or (board.spaces[cobra.posX][cobra.posY] == COBRA): collision = True else: collision = False return collision def update_segments(board, cobra): posX = cobra.posX posY = cobra.posY if board.spaces[posX][posY] == FOOD: cobra.add_segment(cobra.segment(posX, posY)) board.foodOnBoard = False for seg in cobra.segments: prevPosX = seg.posX prevPosY = seg.posY board.spaces[prevPosX][prevPosY] = EMPTY seg.posX = posX seg.posY = posY board.spaces[seg.posX][seg.posY] = COBRA posX = prevPosX posY = prevPosY def main(): # Set board size, cobra starting position, create first cobra segment, and initialize display board1 = board(BOARD_SIZE_WIDTH, BOARD_SIZE_HEIGHT, BOARD_SPACE_SIZE) cobra1 = cobra(PLAYER1_START_X, PLAYER1_START_Y, COBRA_START_DIRECTION) cobra1.add_segment(cobra.segment(cobra1.posX, cobra1.posY)) pygame.init() screen = pygame.display.set_mode((DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT)) gameRunning = True paused = False while gameRunning == True: update_segments(board1, cobra1) board1.draw_board(screen) pygame.display.update() events = pygame.event.get() for event in events: if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: cobra1.direction = "Up" if event.key == pygame.K_DOWN: cobra1.direction = "Down" if event.key == pygame.K_LEFT: cobra1.direction = "Left" if event.key == pygame.K_RIGHT: cobra1.direction = "Right" if event.key == pygame.K_SPACE: if not paused: paused = True else: paused = False if not paused: cobra1.move() collision = check_collision(board1, cobra1) if not board1.foodOnBoard: board1.create_food() if collision == True: gameRunning = False pygame.time.wait(MOVEMENT_DELAY) main() </code></pre>
[]
[ { "body": "<p>You've followed some conventions very well like CAPS for constants. Very nice. Here are some points:</p>\n\n<h1>Standard library imports precede 3rd party ones</h1>\n\n<pre><code>import pygame\nimport random\n</code></pre>\n\n<p>should be changed to</p>\n\n<pre><code>import random\n\nimport pygame...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T21:58:00.717", "Id": "205637", "Score": "8", "Tags": [ "python", "beginner", "pygame", "snake-game" ], "Title": "Nibbles/Snake game in Python" }
205637
<p>I am no JavaScript expert, and I have managed to hack together a node.js script that does exactly what I want it to do: upload images contained within a folder to Google Cloud Storage for a Firebase project, and then return the public access URLs. Given that I have limited experience with node.js combined with GC Storage, please advise me on any issues that running this code over approximately 200 images in the folder may cause.</p> <pre><code>var fs = require('fs'); const {Storage} = require('@google-cloud/storage'); const projectId = 'XXXXXXX'; //Creates a client const storage = new Storage({ projectId: projectId, keyFilename: 'auth.json' }); // Reference the bucket var bucket = storage.bucket('XXXXXXX.appspot.com'); //This reads the folder where the images are stored fs.readdir('ImagesToUpload', (err, files) =&gt; { if( err ) { console.error( "Could not read the directory.", err ); process.exit( 1 ); } files.forEach(function( file, index ) { var filePath = 'ImagesToUpload/' console.log(file) // Upload a local file to a new file to be created in the bucket bucket.upload(filePath += file, (err, file) =&gt; { if (err) { return console.error(err); } let publicUrl = `https://firebasestorage.googleapis.com/v0/b/${projectId}.appspot.com/o/${file.metadata.name}?alt=media`; console.log(publicUrl); }); }) }) </code></pre>
[]
[ { "body": "<p>Looks good. A few nits:</p>\n\n<ol>\n<li><p>You might as well use <code>const</code> where you can, and <code>let</code> when that doesn't work. You can avoid <code>var</code> completely.</p></li>\n<li><p>Instead of <code>var filePath = 'ImagesToUpload/'</code>-- and then modifying <code>filePath<...
{ "AcceptedAnswerId": "205647", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T21:58:30.140", "Id": "205638", "Score": "1", "Tags": [ "javascript", "node.js", "google-cloud-platform" ], "Title": "Uploading multiple images to Google Cloud Storage using Node.js" }
205638
<p>The problem I am looking to solve is wrapping a web scraper in a RESTful API such that it can be called programmatically from another application, frontend or microservice. The overall goal is that this piece of code will form one part of a larger application in a microservices architecture.</p> <p>This program scrapes the Radio Francais International Journal en Francais Facile (RFI JEFF) website for the French transcriptions of their daily news podcast. The web scraper is built using Beautiful Soup, the API is built using Flask Restplus, and the code is packaged in a Docker container.</p> <p>The code operates as follows:</p> <ol> <li>The API is called with the desired program (broadcast) date as the data payload</li> <li>The web scraper is then called to scrape the appropriate webpage for that given date</li> <li>The response of the API call is a transcription of the broadcast in the form of a list of sentences/paragraphs as well as other information</li> </ol> <p>To set expectations, I am a beginner programmer and this is my first independent project. I am seeking a project review and feedback on what I've created so far.</p> <p>I will include a few sections of code for the web scraper and API only. The full repository can be found <a href="https://github.com/25Postcards/rfi_jeff_api" rel="nofollow noreferrer">here</a>.</p> <p>You can clone the repo, build the container, and run it to test the program:</p> <pre><code>git clone https://github.com/25Postcards/rfi_jeff_api sudo docker build . -t jeff_api:latest sudo docker run -p 8000:8000 jeff_api </code></pre> <h3>API</h3> <pre><code>from flask_restplus import Namespace, Resource, fields from core import jeff_scraper from core import jeff_logger from core import jeff_validators api = Namespace('web', description='Operations on the RFI website.') # This model definition is required so it can be registered to the API docs transcriptions_model = api.model('Transcription', { 'program_date': fields.String(required=True), 'encoding': fields.String, 'title': fields.String, 'article': fields.List(fields.String), 'url': fields.Url('trans_pd_ep'), 'status_code': fields.String, 'error_message': fields.String }) @api.route('/transcriptions/&lt;program_date&gt;', endpoint='trans_pd_ep') @api.param('program_date', 'The program date for the broadcast. Accepted date format DDMMYYYY.') @api.doc(model=transcriptions_model) class Transcriptions(Resource): """A Transcriptions resource. """ def get(self, program_date): """Gets the transcription from the scrapper. Args: program_date (str): A string representing the program date Returns: validate_date_errors (dict): A dict of errors raised by the validator for the transcriptions schema. data (dict): A dict of attributes from the jeff transcriptions object containing the program date, title, article, etc. (see schema). """ # Create validator, validate input ts = jeff_validators.TranscriptionsSchema() validate_date_errors = ts.validate({'program_date': program_date}) if validate_date_errors: return validate_date_errors # Create scrapper, scrape page jt = jeff_scraper.JeffTranscription(program_date) # Serialise JeffTranscription object to serialised (formatted) dict # according to Transcriptions Schema data, errors = ts.dump(jt) return data </code></pre> <h3>Web scraper</h3> <pre><code>import requests import logging from bs4 import BeautifulSoup from core import jeff_errors from core import jeff_logger class JeffTranscription(object): """Represents a transcription from the rfi jeff website. Attributes: program_date (str): A string for the program date of the broadcast, accepted date format DDMMYYYY. title (str): A string for the title of the transcription. article (list(str)): A list of strings for each paragraph in the transcription article. encoding (str): A string defining the encoding of the transcription. is_error (bool): A boolean indicating if an error occurred. error_message (str): A string for error messages generated whilst requesting the webpage or whilst parsing the content. status_code (str): A string indicating the http status code for responses from the rfi jeff website. url (str): The URL for the rfi jeff webpage for the transcription. """ def __init__(self, program_date): """Inits JeffTranscription with the program date.""" self.program_date = program_date self._makeURL() self.title = None self.article = None self.encoding = None self.is_error = False self.error_message = None self.status_code = None self._jeff_scraper_logger = jeff_logger.JeffLogger('jeff_scraper_logger') try: page_response = self._getPageResponse() page_content = page_response.content self._scrapePage(page_content) except (jeff_errors.ScraperConnectionError, jeff_errors.ScraperTimeoutError, jeff_errors.ScraperHTTPError, jeff_errors.ScraperParserError) as e: self._handleScraperErrors(e) def _handleScraperErrors(self, e): """Handles errors raised by the methods. Sets the is_error and error_message attributes. Args: e: An error object raised by the class methods """ self.is_error = True self.error_message = e.message self._jeff_scraper_logger.logger.error(self.error_message) def _makeURL(self): """Makes the url for the RFI JEFF Website.""" RFI_JEFF_BASE_URL = 'https://savoirs.rfi.fr/fr/apprendre-enseigner/' \ 'langue-francaise/journal-en-francais-facile-' RFI_JEFF_END_URL = '-20h00-gmt' self.url = RFI_JEFF_BASE_URL + self.program_date + RFI_JEFF_END_URL def _getPageResponse(self): """Gets the response from the webpage. Returns: A requests.response object. Raises: ScraperConnectionError: A connection error occurred. ScraperTimeoutError: A timeout error occurred. ScraperHTTPError: An HTTP Error occurred. """ try: HEADERS = {'User-Agent': 'Chrome/61.0.3163.91'} page_response = requests.get(self.url, headers=HEADERS, timeout=5) self._jeff_scraper_logger.logger.info('Request sent to JEFF URL') self.status_code = page_response.status_code self.encoding = page_response.encoding page_response.raise_for_status() except requests.exceptions.ConnectionError as e: raise jeff_errors.ScraperConnectionError from e except requests.exceptions.Timeout as e: raise jeff_errors.ScraperTimeoutError from e except requests.exceptions.HTTPError as e: raise jeff_errors.ScraperHTTPError from e return page_response def _scrapePage(self, page_content): """Parses the html content from the webpage response. Uses the Beautiful Soup library to parse the webpage content to extract the title of the broadcast and the transcription. The transcription is a series of paragraph elements within an article element that has a class attribute defined by ARTICLE_CLASS. Example Webpage HTML view-source:https://savoirs.rfi.fr/fr/apprendre-enseigner/langue-francaise/journal-en-francais-facile-23072018-20h00-gmt Article element at line 518 First paragraph element at line 532 Args: page_content: The content of the webpage as HTML Raises: ScraperParserError: An error occurred parsing the page content. """ try: ARTICLE_CLASS = "node node-edition node-edition-full term-2707 clearfix" bs = BeautifulSoup(page_content, "html.parser") title_tag = bs.find('title') title_text = title_tag.get_text() # Find all the p elements within the article element that has the # ARTICLE_CLASS class attribute. Remove newline characters and # unwanted unicode characters from the p element's text fields. # Create a list of strings, one list element for each paragraph. article_p_tags = bs.find('article', class_=ARTICLE_CLASS).find_all('p') article_p_text = [p_tag.get_text().replace('\n', '').replace(u'\xa0', u'') for p_tag in article_p_tags] self._jeff_scraper_logger.logger.info('Page content parsed') self.title = title_text self.article = article_p_text except Exception as e: raise jeff_errors.ScraperParserError() from e </code></pre> <h2>Notes/Questions:</h2> <ul> <li>I've stuck to the Google Python style guide where possible.</li> <li>The scraping is performed when the scraper is instantiated. Is this good practice or should I create a method to initiate or invoke the scraping code?</li> <li>The <code>_getPageResponse</code> method contains a <code>try</code>/<code>except</code> to handle HTTP request errors. Is is correct to use a <code>try</code>/<code>except</code> with a function or method to catch exceptions within the function?</li> <li>The <code>_getPageResponse</code> method is called from within another try/except block within the <code>init</code> method, is it good practice to have <code>try</code>/<code>except</code> within <code>try</code>/<code>except</code> that are within the <code>init</code> methods? The same concern arises with the <code>_scrapePage</code> method.</li> <li>Should I be using Flask Restplus to generate swagger API specs/docs automatically? Or should I use a separate extension to generate swagger API specs/docs with Flask Restful (if so, what would this swagger extension be)?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T22:03:14.487", "Id": "205639", "Score": "2", "Tags": [ "python", "web-scraping", "api", "beautifulsoup", "flask" ], "Title": "Wrapping a web scraper in a RESTful API" }
205639
<p>The algorithm bellow is meant to allow a user to roll a die as many times as he would like, then print how many times each side was rolled and how many rolls there were total. </p> <pre><code> import java.util.Random; import java.util.Scanner; public class DieRoll { public static void main(String[] args) { // TODO Auto-generated method stub int roll; int totalRolls = 0; int roll1 = 0; int roll2 = 0; int roll3 = 0; int roll4 = 0; int roll5 = 0; int roll6 = 0; int numberOfRolls; Scanner scan = new Scanner(System.in); Random generator = new Random(); System.out.println("How many times would you like to roll? "); numberOfRolls = scan.nextInt(); for (int numberOfLoops = numberOfRolls; numberOfLoops&gt;0; numberOfLoops--) { roll = generator.nextInt(6) + 1; System.out.println("your roll was: " + roll); switch (roll) { case 1: roll1 = roll1 + 1; break; case 2: roll2 = roll2 + 1; break; case 3: roll3 = roll3 + 1; break; case 4: roll4 = roll4 + 1; break; case 5: roll5 = roll5 + 1; break; case 6: roll6 = roll6 + 1; break; default: break; } } System.out.println("\nyou rolled a 1: " + roll1); System.out.println("you rolled a 2: " + roll2); System.out.println("you rolled a 3: " + roll3); System.out.println("you rolled a 4: " + roll4); System.out.println("you rolled a 5: " + roll5); System.out.println("you rolled a 6: " + roll6); System.out.println("\nYou spun a total of : " + numberOfRolls); } } </code></pre>
[]
[ { "body": "<p>The algorithm can be simplified quite a bit. No need for <code>switch</code>-<code>case</code>. Just create an array (<code>faceCount</code>) with six slots and increment the appropriate slot. In other words:</p>\n\n<pre><code>roll = generator.nextInt(6);\nfaceCount[roll]++;\n</code></pre>\n\n<p>T...
{ "AcceptedAnswerId": "205645", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T01:54:46.377", "Id": "205644", "Score": "1", "Tags": [ "java", "simulation", "dice" ], "Title": "Counting results of die rolls" }
205644
<p>I just finished my first full app in JavaScript and I'm hoping to get some feedback. I guess I'm looking for overall design advice, use of classes and functions etc. but anything is fair game so I am keen to hear any constructive criticism.</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>/**************GAME OPTIONS*******************/ const options = { //Game mult: 0.95, //how much to decrease speed interval each grow //board xBoard: 300, yBoard: 300, //Snake xStart: 150, yStart: 150, jump: 10, speed: 1000, maxSpeed: 100, //Food foodTime: 10000, foodMult: 0.5, maxFoods: 2, maxMaxFoods: 10 }; /****************INITIAL SETUP*******************/ function setup() { //Create Board Element const body = document.getElementsByTagName("body")[0]; const board = document.createElement("div"); body.appendChild(board); board.classList.add("board"); board.style.width = `${options.xBoard}px`; board.style.height = `${options.yBoard}px`; //Create Snakes head const head = board.appendChild(document.createElement("div")); head.classList.add("head"); head.style.top = `${options.yStart}px`; head.style.left = `${options.xStart}px`; snake1.body.push(head); //create gameover div const gameOver = board.appendChild(document.createElement("div")); gameOver.classList.add("gameOver"); gameOver.style.visibility = "hidden"; gameOver.innerHTML = "GAME OVER"; } /***************************SNAKE**********************/ class snake { constructor() { this.body = []; this.direction = "w"; //maybe randomise this } /****Move Snake****/ move() { const head = document.querySelector(".head"); let x = parseInt(head.style.left); let y = parseInt(head.style.top); let xLeader = x; let yLeader = y; switch (this.direction) { //Up case "w": if (y == 0) { y = options.yBoard - options.jump; } else { y -= options.jump; } head.style.top = `${y}px`; //move head break; //Down case "s": if (y == options.yBoard - options.jump) { y = 0; } else { y += options.jump; } head.style.top = `${y}px`; //move head break; //Left case "a": if (x == 0) { x = options.xBoard - options.jump; } else { x -= options.jump; } head.style.left = `${x}px`; //move head break; //Right case "d": if (x == options.xBoard - options.jump) { x = 0; } else { x += options.jump; } head.style.left = `${x}px`; //move head break; default: break; } const gameOver = this.checkBumpedHead(); if (!gameOver) { const moveTimer = window.setTimeout( () =&gt; snake1.move.call(snake1), options.speed ); } else { document.querySelector(".gameOver").style.visibility = "visible"; clearInterval(foodTimer); } //move body this.body.forEach(body =&gt; { if (body.className == "head") { body.style.top = `${y}px`; body.style.left = `${x}px`; } else { y = parseInt(body.style.top); x = parseInt(body.style.left); body.style.top = `${yLeader}px`; body.style.left = `${xLeader}px`; xLeader = x; yLeader = y; } }); this.checkDinnerTime(); } /****Check if food eaten****/ checkDinnerTime() { const board = document.querySelector(".board"); const food = foods.food; const xHead = this.body[0].style.left; const yHead = this.body[0].style.top; food.forEach((food1, index) =&gt; { if (xHead == food1.style.left &amp;&amp; yHead == food1.style.top) { food.splice(index, 1); board.removeChild(food1); this.grow(); foods.addFood(); } }); } /*check if crashed into body****/ checkBumpedHead() { const gameOver = 0; this.body.forEach(body =&gt; { if (body.className != "head") { if ( this.body[0].style.top == body.style.top &amp;&amp; this.body[0].style.left == body.style.left ) { this.gameOver = 1; } } }); return this.gameOver; } /****Grow new body part after eating****/ grow() { //get head const head = document.querySelector(".head"); //attach head to body if (!this.body.length) { this.body.push(head); } //create new body part const newBody = document .querySelector(".board") .appendChild(document.createElement("div")); newBody.classList.add("body"); newBody.style.top = head.style.top; newBody.style.left = head.style.left; this.body.push(newBody); //attach new body part if (options.speed &gt; options.maxSpeed) { options.speed *= options.mult; //alter move interval (speed) } options.foodTime *= options.mult; if (options.maxFoods &lt; options.maxMaxFoods) { options.maxFoods += options.foodMult; } } /****steer Snake****/ steer(e) { switch (e.keyCode) { case 87: //Up snake1.direction = "w"; break; case 83: //Down snake1.direction = "s"; break; case 65: //Left snake1.direction = "a"; break; case 68: //Right snake1.direction = "d"; break; default: break; } snake1.move; } } /**********************FOOD**************/ class food { constructor() { this.food = []; } /****add new food to board****/ addFood() { if (this.food.length &gt; options.maxFoods - 1) { return; } const board = document.querySelector(".board"); const xRand = Math.floor(Math.random() * (options.xBoard / 10)) * 10; const yRand = Math.floor(Math.random() * (options.yBoard / 10)) * 10; const newFood = document.createElement("div"); board.appendChild(newFood); newFood.classList.add("food"); newFood.style.left = `${xRand}px`; newFood.style.top = `${yRand}px`; this.food.push(newFood); } } /****************MAIN***************************/ const snake1 = new snake(); const foods = new food(); const foodTimer = window.setInterval( () =&gt; foods.addFood.call(foods), options.foodTime ); setup(); foods.addFood(); snake1.move(); window.addEventListener("keydown", snake1.steer);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.board{ position: relative; height:600px; width:600px; background-color:#232323; } .gameOver{ display: flex; justify-content: center; align-items: center; height: 100%; width:100%; text-align: center; font-size: 4rem; color: red; } .head{ position:absolute; height:10px; width:10px; background-color:#787878 } .body{ position:absolute; height:10px; width:10px; background-color:#787878; } .food{ position: absolute; height:6px; width:6px; background-color: red; border-radius: 50%; margin: 2px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;title&gt;The Game&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="main.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Not a code review per se, however there were two behaviors worth commenting on when I ran your snippet.</p>\n\n<p>A few seconds after initiating gameplay a second apple appeared without my having collected the first apple, leaving 2 apples permanently on the screen.</p>\n\n<p>Your code currently a...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T04:15:31.577", "Id": "205648", "Score": "5", "Tags": [ "javascript", "beginner", "css", "dom", "snake-game" ], "Title": "JavaScript Snake: First app" }
205648
<p>This is a homework assignment. Convert an integer (1 - 2999) to roman numerals. I was wondering if I could make my code more efficient. The way I have it set up is that I take the digits of the input (the thousands, hundreds, tens, ones) and have cases for each of them. However, the approach I took to this problem is that there are a lot of if statements. My professor prefers that I utilize nothing that is not taught yet. I can only use for, if, while statements - the basics of Java. I was wondering if there are different approaches I could take to this problem so that the code is much more shorter as it is relatively long.</p> <pre><code>class romanNum { public static void main (String [] args) { //Initialize all variables including Scanner Scanner input = new Scanner (System.in) ; int userInput; int onesDigit ; int tensDigit ; int hundredsDigit ; int thousandsDigit ; String one = "I"; String five = "V"; String ten = "X"; String fifty = "L"; String hundred = "C"; String fiveHundred = "D"; String thousand = "M"; boolean keepGoing = true ; //User Input userInput = input.nextInt(); //Seperate the digits thousandsDigit = (userInput/1000) % 10; hundredsDigit = (userInput / 100) % 10; tensDigit = (userInput / 10) % 10; onesDigit = (userInput / 1) % 10; //Thousands (Because range is 1 - 2999, i didnt do more cases for thousands while (keepGoing) { for (int count = 0 ; count &lt; thousandsDigit ; count++) { System.out.print (thousand); } //Hundreds (Checks all cases 1-9) //Checks 1 - 3 if ((hundredsDigit &gt;= 1) &amp;&amp; (hundredsDigit &lt;= 3)) { for (int count = 0 ; count &lt; hundredsDigit ; count++) { System.out.print (hundred); } } //Checks 4 else if (hundredsDigit == 4) { System.out.print (hundred + fiveHundred); } // Checks 9 else if (hundredsDigit == 9) { System.out.print (hundred + thousand); } //Omit 0 else if (hundredsDigit == 0) { } // Checks 5 - 8 else { System.out.print (fiveHundred); for (int count = 0 ; count &lt; hundredsDigit - 5 ; count++ ) { System.out.print (hundred); } } //Tens (Checks all cases 1-9) //Checks 1 - 3 if ((tensDigit &gt;= 1) &amp;&amp; (tensDigit &lt;= 3)) { for (int count = 0 ; count &lt; tensDigit ; count++) { System.out.print (ten); } } // Checks 4 else if (tensDigit == 4) { System.out.print (ten + fifty); } // Checks 9 else if (tensDigit == 9) { System.out.print (ten + hundred); } // Omit 0 else if (tensDigit == 0) { } // Checks 5 - 8 else { System.out.print (fifty); for (int count = 0 ; count &lt; tensDigit - 5 ; count++ ) { System.out.print (ten); } } //Ones (Checks all cases 1-9) //Checks 1 - 3 if ((onesDigit &gt;= 1) &amp;&amp; (onesDigit &lt;= 3)) { for (int count = 0 ; count &lt; onesDigit ; count++) { System.out.print (one); } } // Checks 4 else if (onesDigit == 4) { System.out.print (one + five); } //Checks 9 else if (onesDigit == 9) { System.out.print (one + ten); } //Omit 0 else if (onesDigit == 0) { } // else (checks 5 - 9) else { System.out.print (five); for (int count = 0 ; count &lt; onesDigit - 5 ; count++ ) { System.out.print (one); } } //Print line outside of all conditions System.out.println(""); keepGoing = false ; } } } </code></pre>
[]
[ { "body": "<p>Because of the repeating scheme 1er, 5er, we can do it in a loop. The special cases 0/5 and 4/9 are as like as your code.</p>\n\n<pre><code>private static String toRomanNum(int val) {\n String out = \"\", chars = \"IVXLCDM\";\n int i, digit, d5, m5, idx=6, divi = 1000;\n\n while(idx&gt;=0...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T05:40:38.900", "Id": "205650", "Score": "2", "Tags": [ "java", "beginner", "homework", "roman-numerals" ], "Title": "Integer to Roman Numerals (1 - 2999)" }
205650
<p>I'm within an audio application that sends variable-length buffers to my DLL, which will process at higher speed (48000 samples per sec, but can also be higher).</p> <p>Here's the code I've written:</p> <pre><code>while (remainingSamples &gt; 0) { int blockSize = remainingSamples; if (blockSize &gt; PLUG_MAX_PROCESS_BLOCK) { // PLUG_MAX_PROCESS_BLOCK = 256 blockSize = PLUG_MAX_PROCESS_BLOCK; } // voices for (int voiceIndex = 0; voiceIndex &lt; 16; voiceIndex++) { for (int envelopeIndex = 0; envelopeIndex &lt; 10; envelopeIndex++) { Envelope &amp;envelope = *pEnvelope[envelopeIndex]; EnvelopeVoiceData &amp;envelopeVoiceData = envelope.mEnvelopeVoicesData[voiceIndex]; // skip disabled envelopes (in the case of test, all are running) if (!envelope.mIsEnabled) { continue; } // envelope voice's local copy double blockStep = envelopeVoiceData.mBlockStep; double blockStartAmp = envelopeVoiceData.mBlockStartAmp; double blockDeltaAmp = envelopeVoiceData.mBlockDeltaAmp; double values[PLUG_MAX_PROCESS_BLOCK]; // envelope local copy bool isBipolar = envelope.mIsBipolar; double amount = envelope.mAmount; double rate = envelope.mRate; // precalc values double bp0 = ((1 + isBipolar) * 0.5) * amount; double bp1 = ((1 - isBipolar) * 0.5) * amount; // samples for (int sampleIndex = 0; sampleIndex &lt; blockSize; sampleIndex++) { if (blockStep &gt;= gBlockSize) { // here I'll update blockStartAmp, blockDeltaAmp and fmod blockStep, every 100 samples. but I'm ignoring this part right now } // update output value double value = blockStartAmp + (blockStep * blockDeltaAmp); values[sampleIndex] = (bp0 * value + bp1); // next phase blockStep += rate; } // restore back values from local copy envelopeVoiceData.mBlockStep = blockStep; envelopeVoiceData.mBlockStartAmp = blockStartAmp; envelopeVoiceData.mBlockDeltaAmp = blockDeltaAmp; // mValue is a mValue[PLUG_VOICES_BUFFER_SIZE][PLUG_MAX_PROCESS_BLOCK]; std::memcpy(envelope.mValue[voiceIndex], values, PLUG_MAX_PROCESS_BLOCK); } } remainingSamples -= blockSize; } </code></pre> <p>But it keep still 3-4% of CPU iterating 16 voices, 10 envelopes and 256 samples. Is there any way to speed up this task? Vectorizing maybe? I'm not really able to do it.</p> <p>Any tips?</p> <p>Here's an extract of <code>Envelope.h</code> header:</p> <pre><code>#ifndef ENVELOPE_H #define ENVELOPE_H const unsigned int gBlockSize = 100; struct EnvelopeVoiceData { double mBlockStep; double mBlockStepOffset; double mBlockStartAmp; double mBlockEndAmp; double mBlockDeltaAmp; double mStep; }; class MainIPlug; class Voice; class EnvelopesManager; class Envelope : public IControl { public: bool mIsEnabled = true, mIsBipolar = true; unsigned int mLengthInSamples, mLoopLengthInSamples, mSectionLengths[gMaxNumPoints]; int mIndex; double mRate = 1.0, mAmount = 1.0; EnvelopesManager *pEnvelopesManager; EnvelopeType mType; EnvelopeLoopType mLoopType; unsigned int mNumPoints, mLoopPointIndex; double mLengths[gMaxNumPoints] = { 0.0 }; double mAmps[gMaxNumPoints]; double mTensions[gMaxNumPoints - 1]; double mValue[PLUG_VOICES_BUFFER_SIZE][PLUG_MAX_PROCESS_BLOCK]; EnvelopeVoiceData mEnvelopeVoicesData[PLUG_VOICES_BUFFER_SIZE]; Envelope(MainIPlug *plug, EnvelopesManager *envelopesManager, int x, int y, int index); ~Envelope(); void SetSampleRate(double sampleRate); void SetRate(double rate); void SetType(EnvelopeType type); void SetAmount(double amount); void SetBipolar(bool bipolar); void SetEnable(bool enable); void CalculateLoopLength(); void CalculateSectionsLengths(); void AddPoint(double position, double amplitude); void DeletePoint(int index); void SwapPoint(int currentPointIndex, int newPointIndex, int increment); void CleanEnvelope(); private: double mSampleRate; MainIPlug *pPlug; }; class EnvelopesManager : public IControl { public: unsigned int mNumEnvelopes, mNumRunningEnvelopes[PLUG_VOICES_BUFFER_SIZE]; Envelope *pEnvelope[kNumParamsAutomatable]; EnvelopesManager(MainIPlug *plug, int x, int y, int numEnvelopes = kNumParamsAutomatable); ~EnvelopesManager() { } void Serialize(nlohmann::json &amp;jsonPlugin); void Unserialize(nlohmann::json &amp;jsonPlugin); void Reset(int voiceIndex); void ProcessBlock(int voiceIndex, int blockSize); private: MainIPlug *pPlug; }; #endif // !ENVELOPE_H </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T07:39:04.587", "Id": "396656", "Score": "1", "body": "Welcome to CodeReview.SE! Your questions sounds interesting. Unfortunately, I have the felling we are missing a bit of context here. Could you provide a slightly bigger piece of ...
[ { "body": "<h3>Simplify loop</h3>\n<p>Let's examine your main loop (minus the commented out part):</p>\n<blockquote>\n<pre><code> for (int sampleIndex = 0; sampleIndex &lt; blockSize; sampleIndex++) {\n // update output value\n double value = blockStartAmp + (blockStep * blockDeltaA...
{ "AcceptedAnswerId": "205658", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T07:17:03.323", "Id": "205654", "Score": "2", "Tags": [ "c++", "performance", "audio", "signal-processing" ], "Title": "Processing voice samples" }
205654
<p>I decided to go with a very simple CGI user registration program to pair with Apache's <code>mod_auth_form</code> wrapper around a private site. It was only just after I finished writing that I realized I'd written security-sensitive code in a language I'm not my best at.</p> <p>Is this code secure from parameter injection attacks? I.e., if the attacker fiddles with the POST values, can they run arbitrary commands on the server as the web server user?</p> <pre><code>#!/bin/bash echo "Content-type: text/html" echo '' cat &lt;&lt;EOT &lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Registered&lt;/title&gt; &lt;link rel="icon" href="/favicon.png"&gt; &lt;/head&gt; &lt;body&gt; EOT POST=$(cat) if [ "$REQUEST_METHOD" != "POST" ] || [ ! "$POST" ]; then echo "&lt;h1&gt;Error&lt;/h1&gt;&lt;p&gt;Please go back and try again&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; exit 1; fi function input { echo "$POST" | sed 's/^.*'"$1"'=\([^&amp;]\+\)&amp;.*$/\1/' | python -c "import sys, urllib.parse as p; print(p.unquote(sys.stdin.read()));" } USERNAME=$(input username) PASSWORD=$(input password) PASSWORD2=$(input password2) if [ "$PASSWORD" != "$PASSWORD2" ]; then echo "&lt;h1&gt;Error&lt;/h1&gt;&lt;p&gt;Your passwords do not match.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; exit 1; fi if [ ${#PASSWORD} -lt 10 ]; then echo "&lt;h1&gt;Error&lt;/h1&gt;&lt;p&gt;Please pick a longer password.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; exit 1; fi echo "$PASSWORD" | htpasswd -i ../registrations "$USERNAME" cat &lt;&lt;EOT &lt;h1&gt;You have registered&lt;/h1&gt; &lt;p&gt;Now, please email me so I can enable your account.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; EOT exit 0 </code></pre> <p>To clarify - I'm not concerned about the line of <code>python</code> - it urldecodes/unescapes the field from the POST data and is extremely battle-tested. I put that in to avoid bugs/security concerns over other solutions with fewer dependencies (many with scary-looking bash constructs).</p> <p>The <code>sed</code> is also pretty straightforward - it pulls out the named parameter from the urlencoded POST data. <code>&amp;</code> is escaped as <code>%26</code> and so will never show up in the input. I wrote/modified the <code>sed</code> there and am confident enough that it'll behave as I expect (<code>sed</code> is more familiar to me than <code>bash</code>).</p> <p>Essentially, please feel free to ignore the implementation of the <code>input</code> function and assume it properly extracts POST variables into <code>bash</code> variables. My concerns center entirely around whether that user supplied data (which can be essentially any sequence of bytes) in <code>bash</code> variables will break or escape from any of the places I use it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T08:06:14.740", "Id": "396660", "Score": "2", "body": "Bash *and* sed *and* Python! You'll likely get some good code reviews, but don't expect an exhaustive security review (i.e. we might find issues, but we can't promise not to mis...
[ { "body": "<p>It's a couple of decades (!) since I did any CGI, but I'll cast a quick eye over this. I hope other reviewers will pitch in and fill the gaps (or correct my errors).</p>\n\n<p>It's an interesting choice to use the same <code>TITLE</code> for success and failure. It might be better to write a sma...
{ "AcceptedAnswerId": "205778", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T07:32:43.993", "Id": "205655", "Score": "4", "Tags": [ "security", "bash", "sed", "cgi" ], "Title": "CGI for htpasswd registration" }
205655
<p>Lately, I've been developing sorting algorithms as a kind of exercise to make better code and I've come accross something curious, even though bubble and cocktail sort are known to perform horribly, I think I might be doing something wrong since it takes a larger amount of time than selection, insertion and merge sort (about 3 times longer than selection sort, about 2 times insertion and merge sort)</p> <p>Code for Bubble sort</p> <pre><code>public static class BubbleSort { public static List&lt;long&gt; SortAscending(List&lt;long&gt; unsortedList) { bool anyElementSwapped = true; int elementsPendingToSort = unsortedList.Count; while (anyElementSwapped) { anyElementSwapped = false; for (int currentElementIndex = 0; currentElementIndex &lt; elementsPendingToSort; currentElementIndex++) { if (unsortedList.Count.Equals(currentElementIndex + 1)) { continue; } if (unsortedList[currentElementIndex] &gt; unsortedList[currentElementIndex + 1]) { anyElementSwapped = true; long temporalValueHolder = unsortedList[currentElementIndex]; unsortedList[currentElementIndex] = unsortedList[currentElementIndex + 1]; unsortedList[currentElementIndex + 1] = temporalValueHolder; } } elementsPendingToSort--; } return unsortedList; } public static List&lt;long&gt; SortDescending(List&lt;long&gt; unsortedList) { bool anyElementSwapped = true; int elementsPendingToSort = unsortedList.Count; while (anyElementSwapped) { anyElementSwapped = false; for (int currentElementIndex = 0; currentElementIndex &lt; elementsPendingToSort; currentElementIndex++) { if (unsortedList.Count.Equals(currentElementIndex + 1)) { continue; } if (unsortedList[currentElementIndex] &lt; unsortedList[currentElementIndex + 1]) { anyElementSwapped = true; long temporalValueHolder = unsortedList[currentElementIndex + 1]; unsortedList[currentElementIndex + 1] = unsortedList[currentElementIndex]; unsortedList[currentElementIndex] = temporalValueHolder; } } elementsPendingToSort--; } return unsortedList; } } </code></pre> <p>Code for Cocktail sort</p> <pre><code>public static class CocktailSort { public static List&lt;long&gt; SortAscending(List&lt;long&gt; unsortedList) { int lowerSortBound = 0; int upperSortBound = unsortedList.Count; bool anyElementSwapped = false; while (lowerSortBound &lt; upperSortBound) { anyElementSwapped = false; for (int lowerBound = lowerSortBound; lowerBound &lt; upperSortBound; lowerBound++) { if (unsortedList.Count.Equals(lowerBound + 1)) { break; } if (unsortedList[lowerBound] &gt; unsortedList[lowerBound + 1]) { anyElementSwapped = true; SwapUpwards(unsortedList, lowerBound); } } upperSortBound--; if (!anyElementSwapped) break; anyElementSwapped = false; for (int upperBound = upperSortBound; upperBound &gt; lowerSortBound; upperBound--) { if ((upperBound - 1) &lt;= 0) { break; } if (unsortedList[upperBound] &lt; unsortedList[upperBound - 1]) { anyElementSwapped = true; SwapDownwards(unsortedList, upperBound); } } lowerSortBound++; if (!anyElementSwapped) break; } return unsortedList; } public static List&lt;long&gt; SortDescending(List&lt;long&gt; unsortedList) { int lowerSortBound = 0; int upperSortBound = unsortedList.Count; bool anyElementSwapped = false; while (lowerSortBound &lt; upperSortBound) { anyElementSwapped = false; for (int lowerBound = lowerSortBound; lowerBound &lt; upperSortBound; lowerBound++) { if (unsortedList.Count.Equals(lowerBound + 1)) { break; } if (unsortedList[lowerBound] &lt; unsortedList[lowerBound + 1]) { anyElementSwapped = true; SwapUpwards(unsortedList, lowerBound); } } upperSortBound--; if (!anyElementSwapped) break; anyElementSwapped = false; for (int upperBound = upperSortBound; upperBound &gt; lowerSortBound; upperBound--) { if ((upperBound - 1) &lt; 0) { break; } if (unsortedList[upperBound] &gt; unsortedList[upperBound - 1]) { anyElementSwapped = true; SwapDownwards(unsortedList, upperBound); } } lowerSortBound++; if (!anyElementSwapped) break; } return unsortedList; } private static void SwapUpwards(List&lt;long&gt; list, int indexToSwap) { long temporalValueHolder = list[indexToSwap]; list[indexToSwap] = list[indexToSwap + 1]; list[indexToSwap + 1] = temporalValueHolder; } private static void SwapDownwards(List&lt;long&gt; list, int indexToSwap) { long temporalValueHolder = list[indexToSwap - 1]; list[indexToSwap - 1] = list[indexToSwap]; list[indexToSwap] = temporalValueHolder; } } </code></pre> <p>Code of the Main Method:</p> <pre><code>private static void Main(string[] args) { Console.WriteLine("Initiating sorting algorithms comparison program"); Dictionary&lt;string, List&lt;double&gt;&gt; sortingTimeResults = new Dictionary&lt;string, List&lt;double&gt;&gt;(); sortingTimeResults.Add("AscendingCocktailSort", new List&lt;double&gt;()); sortingTimeResults.Add("DescendingCocktailSort", new List&lt;double&gt;()); sortingTimeResults.Add("AscendingBubbleSort", new List&lt;double&gt;()); sortingTimeResults.Add("DescendingBubbleSort", new List&lt;double&gt;()); sortingTimeResults.Add("AscendingSelectionSort", new List&lt;double&gt;()); sortingTimeResults.Add("DescendingSelectionSort", new List&lt;double&gt;()); sortingTimeResults.Add("AscendingInsertionSort", new List&lt;double&gt;()); sortingTimeResults.Add("DescendingInsertionSort", new List&lt;double&gt;()); sortingTimeResults.Add("AscendingMergeSort", new List&lt;double&gt;()); sortingTimeResults.Add("DescendingMergeSort", new List&lt;double&gt;()); List&lt;long&gt; listToSort = new List&lt;long&gt;(); listToSort = Enumerable.Range(0, 10000).Select(item =&gt; (long)item).ToList(); Console.WriteLine($"Created list of {listToSort.Count} elements to order"); int timesToIterate = 10; for (int i = 0; i &lt; timesToIterate; i++) { int n = listToSort.Count; Random rng = new Random(); //Console.WriteLine("Randomizing the list of elements"); while (n &gt; 1) { n--; int k = rng.Next(n + 1); long value = listToSort[k]; listToSort[k] = listToSort[n]; listToSort[n] = value; } //Console.WriteLine("Finished randomizing list"); Parallel.Invoke(new ParallelOptions() { MaxDegreeOfParallelism = 1 }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting AscendingCocktailSort algorithm"); sortingStopWatch.Restart(); CocktailSort.SortAscending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended AscendingCocktailSort algorithm"); sortingTimeResults["AscendingCocktailSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting DescendingCocktailSort algorithm"); sortingStopWatch.Restart(); CocktailSort.SortDescending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended DescendingCocktailSort algorithm"); sortingTimeResults["DescendingCocktailSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); } , () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting AscendingBubbleSort algorithm"); sortingStopWatch.Restart(); BubbleSort.SortAscending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended AscendingBubbleSort algorithm"); sortingTimeResults["AscendingBubbleSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting DescendingBubbleSort algorithm"); sortingStopWatch.Restart(); BubbleSort.SortDescending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended DescendingBubbleSort algorithm"); sortingTimeResults["DescendingBubbleSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting AscendingSelectionSort algorithm"); sortingStopWatch.Restart(); SelectionSort.Sort(listToSort.ToList(), true); sortingStopWatch.Stop(); //Console.WriteLine("Ended AscendingSelectionSort algorithm"); sortingTimeResults["AscendingSelectionSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting DescendingSelectionSort algorithm"); sortingStopWatch.Restart(); SelectionSort.Sort(listToSort.ToList(), false); sortingStopWatch.Stop(); //Console.WriteLine("Ended DescendingSelectionSort algorithm"); sortingTimeResults["DescendingSelectionSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting AscendingInsertionSort algorithm"); sortingStopWatch.Restart(); InsertionSort.SortAscending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended AscendingInsertionSort algorithm"); sortingTimeResults["AscendingInsertionSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); } , () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting DescendingInsertionSort algorithm"); sortingStopWatch.Restart(); InsertionSort.SortDescending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended DescendingInsertionSort algorithm"); sortingTimeResults["DescendingInsertionSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting AscendingMergeSort algorithm"); sortingStopWatch.Restart(); MergeSort.SortAscending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended AscendingMergeSort algorithm"); sortingTimeResults["AscendingMergeSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); }, () =&gt; { Stopwatch sortingStopWatch = new Stopwatch(); //Console.WriteLine("Starting DescendingMergeSort algorithm"); sortingStopWatch.Restart(); MergeSort.SortDescending(listToSort.ToList()); sortingStopWatch.Stop(); //Console.WriteLine("Ended DescendingMergeSort algorithm"); sortingTimeResults["DescendingMergeSort"].Add(sortingStopWatch.Elapsed.TotalMilliseconds); } ); } Console.WriteLine($"Sorting algorithms comparison for a list with {listToSort.Count} elements has ended,"); Console.WriteLine("the result for each algorithm be it ascending or descending, are the following, with a sample size of " + timesToIterate); sortingTimeResults.ToList().ForEach(result =&gt; { Console.WriteLine($" - The mean time taken to sort the list by the {result.Key} algorithm is {result.Value.Sum() / result.Value.Count} miliseconds"); }); Console.WriteLine(Environment.NewLine + Environment.NewLine); Console.WriteLine("The evaluation has ended, press any key to leave"); Console.ReadKey(); } </code></pre> <p>The Parallel limited to only 1 thread running at once is there because the last computer I ran it on could not handle them ideally and thus giving false samples of the time it takes to perform any of the sorting procedures, I usually run 4 threads at the same time.</p> <p>A sample of the measurements in debug:</p> <p><a href="https://i.stack.imgur.com/6FDqP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6FDqP.png" alt="enter image description here"></a></p> <p>A sample of the measurement in release:</p> <p><a href="https://i.stack.imgur.com/RO1jS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RO1jS.png" alt="enter image description here"></a></p> <p>What could I do better in order to reduce the amount of time this code takes?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T08:56:23.343", "Id": "396673", "Score": "0", "body": "Could you add the actual measurements to the question? Also the data you generated or used to test it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-1...
[ { "body": "<p>Separate for ascending and descending is a lot of duplicate code. Just pass ascending and descending to a general routine.</p>\n\n<pre><code>if (!anyElementSwapped)\n break;\nanyElementSwapped = false;\n</code></pre>\n\n<p><code>anyElementSwapped = false;</code> is pointless.</p>\n\n<pre><code>...
{ "AcceptedAnswerId": "205727", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T08:10:34.883", "Id": "205659", "Score": "1", "Tags": [ "c#", "performance", "sorting" ], "Title": "Bubble and Cocktail sort" }
205659
<p>I'm new to the world of python, and wrote this quick sort implementation which was taught to us in an algorithms class. I would like to learn to write code less like C++ and more pythonic. Could you review my code to make it more pythonic and less buggy? (I'm sure a class implementation is better, but if the scope of the review could maintain the original structure that would be great).</p> <pre><code>def quick_sort(A): #here we choose pivot's index def choose_pivot(start, end, method='start'): if start == end: return 0 if method == 'random': return random.randint(start, end-1) elif method == 'start': return start #we partition the array around the pivot, and return the new pivot #which is pivot's rightful index #Hoare's algorithm for partitioning def partition_array(start, end, pivot_index): pivot = A[pivot_index] #move pivot to start of the array, for swap later A[start], A[pivot_index] = A[pivot_index], A[start] left, right = start + 1, end - 1 #partition around pivot while left &lt; right: while left &lt; end and A[left] &lt; pivot: left += 1 while right &gt; start and A[right] &gt;= pivot: right -= 1 if left &lt; right: A[left], A[right] = A[right], A[left] #swap back the pivot A[start], A[right] = A[right], A[start] return right #Lumoto's algorithm for partitioning def partition_array_2(start, end, pivot_index): left = right = start + 1 pivot = A[pivot_index] #swap out the pivot to the start of the array A[pivot_index], A[start] = A[start], A[pivot_index] while right &lt; end: if A[right] &lt; pivot: A[left], A[right] = A[right], A[left] left += 1 right += 1 #swap back the pivot to its rightful place A[start], A[left-1] = A[left-1], A[start] return left-1 #recursively compute quicksort, with divide and conquer #where start &lt;= new partition (actual place of pivot) &lt;= end def quick_sort_helper(start, end): if end - start &lt;= 0: return #choose new pivot pivot_index = choose_pivot(start, end) new_pivot_index = partition_array_2(start, end, pivot_index) quick_sort_helper(start, new_pivot_index) quick_sort_helper(new_pivot_index+1, end) #Main call quick_sort_helper(0, len(A)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T09:26:55.713", "Id": "396690", "Score": "1", "body": "I've added the [tag:reinventing-the-wheel] tag, as the most Pythonic version would just to be `sorted` or `list.sort`. Which I don't think are the wanted answer :)" }, { ...
[ { "body": "<h3>Focus on the essence of the algorithm, not the exact procedure on texts</h3>\n\n<p>In common algorithm texts for C/C++, the description of an algorithm is more suited for <strong>implementation in C/C++</strong>. Common elements include:</p>\n\n<ul>\n<li>An array, or an object in general, is assu...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T09:04:56.917", "Id": "205666", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "reinventing-the-wheel", "quick-sort" ], "Title": "Pythonic quick sort" }
205666
<p>I've been working on this solution for a couple days now. Finally managed to get it to work and I got it to where it solves about half of the time. The other half goes for so long that it eventually just runs out of memory. The weird thing is that the solves are pretty fast. Before I updated the heuristic with linear conflict, it solved it anywhere from 0.5s to 3s. Now with the update, it averages around 0.05s to 0.5s.</p> <p>The solver uses a priority queue sorted by the heuristic of the board for the open list, and an unordered map for the closed list. The map uses UINT64 values as keys that are encoded from the board array using bitwise operators. Each 8-bit number is encoded with two numbers, thus creating the 64 bit integer.</p> <p>The main advice I'm looking for is a way to catch the harder boards and make progress with them. I'd also really appreciate some advice on how to make the linear conflict function look a lot better. I brute forced my way into something that works and tried to optimize it best I could. It isn't very OOP, but it is just a start. I finished it about an hour or so ago.</p> <p><a href="https://github.com/abyssmu/n-Puzzle/tree/2cd280360326571b5da93618d48524822567e577" rel="nofollow noreferrer">Here</a> is a link to the GitHub I've got it in if you want to build and run it to see what's going on for yourself.</p> <p>Edit: I've made several changes. Many of which were recommendations based on you guys. To the best of my ability anyway. I've still got a fair amount of work to do, like the linear conflict function, but it looks quite a bit different and better. It's in the gitHub link above. Once I get it more figured out, I'll post the full code here as an answer.</p> <h2><code>Manager.h</code></h2> <pre><code>#include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;math.h&gt; #include &lt;queue&gt; #include &lt;random&gt; #include &lt;time.h&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; #include &lt;Windows.h&gt; const int n = 4; struct Container { int b[n * n] = {}; int heuristic; Container* parent = 0; }; struct GreaterThanByCost { bool operator()(const Container* lhs, const Container* rhs) { return lhs-&gt;heuristic &gt; rhs-&gt;heuristic; } }; class Manager { public: Manager(); Manager(const Manager&amp; other); ~Manager(); void Run(); int calculateManhattan(int b[]); int calculateLinear(int b[]); bool checkSolvable(); UINT64 encode(int b[]); int* decode(UINT64 code); void addMoves(); void up(); void down(); void left(); void right(); void findZero(); void swapPos(Container* move, int newPos); bool checkDuplicate(Container* move); void printSolution(Container* top); private: std::priority_queue&lt;Container*, std::vector&lt;Container*&gt;, GreaterThanByCost&gt; open; std::unordered_map&lt;UINT64, bool&gt; closed; Container* current = 0; int zeroX, zeroY; std::chrono::system_clock::time_point start; std::chrono::system_clock::time_point end; }; </code></pre> <h2><code>Manager.cpp</code></h2> <pre><code>#include "Manager.h" Manager::Manager() { int nums[n * n]; zeroX = zeroY = 0; current = new Container; //Initialize random number generator srand((unsigned int)time(0)); do { //Initialize nums for (int i = 0; i &lt; n * n; ++i) { nums[i] = 0; } int val = -1; for (int i = 0; i &lt; n * n; ++i) { bool go = true; val = rand() % (n * n); //Loop until nums[val] != -1 while (go) { if (nums[val] == -1) { val = rand() % (n * n); } else { go = false; } } current-&gt;b[i] = val; nums[val] = -1; //set position of zero if (val == 0) { zeroX = i % n; zeroY = i / n; } } } while (!checkSolvable()); current-&gt;heuristic = calculateManhattan(current-&gt;b) + calculateLinear(current-&gt;b); open.push(current); } Manager::Manager(const Manager&amp; other) {} Manager::~Manager() {} void Manager::Run() { start = std::chrono::system_clock::now(); bool solved = false; while (!solved) { //Check if open.top is solved if (open.top()-&gt;heuristic == 0) { end = std::chrono::system_clock::now(); solved = true; printSolution(open.top()); return; } //Add open.top to closed closed[encode(current-&gt;b)] = true; //Add moves to open addMoves(); } } //Calculate manhattan value for board int Manager::calculateManhattan(int b[]) { //Create solved board int manhattan = 0; //Calculate manhattan distance for each value for (int i = 0; i &lt; n * n; ++i) { if (b[i] != i) { int bX, bY, x, y; bX = b[i] % n; bY = b[i] / n; x = i % n; y = i / n; manhattan += abs(bX - x) + abs(bY - y); } } return manhattan; } //Calculate linear conflict int Manager::calculateLinear(int b[]) { int count = 0; for (int i = 0; i &lt; n * n; ++i) { //Check if b[i] is in the right spot if (b[i] != i) { //Calculate row and col it's supposed to be in int x = b[i] % n; int y = b[i] / n; //Calculate row and col it's in int bx = i % n; int by = i / n; //Check cols if (x == bx) { bool found = false; //Check above if (b[i] &lt; i) { int colStart = i - n; for (int j = colStart; j &gt;= 0; j -= n) { if ((j != b[i]) &amp;&amp; !found) { if ((b[i] - b[j]) % n == 0) { ++count; } } else if ((j == b[i]) &amp;&amp; !found) { if ((b[i] - b[j]) % n == 0) { ++count; } found = true; } else { break; } } } //Check below if (b[i] &gt; i) { int colEnd = n * (n - 1) + bx; for (int j = i + 4; j &lt;= colEnd; j += 4) { if ((j != b[i]) &amp;&amp; !found) { if ((b[i] - b[j]) % n == 0) { ++count; } } else if ((j == b[i]) &amp;&amp; !found) { if ((b[i] - b[j]) % n == 0) { ++count; } found = true; } else { break; } } } } //Check rows if (y == by) { bool found = false; //Check left if (b[i] &lt; i) { int rowStart = i - 1; for (int j = rowStart; j &gt;= by * n; --j) { if ((j != b[i]) &amp;&amp; !found) { if (((b[i] - b[j]) &lt; 0) &amp;&amp; (abs(b[i] - b[j]) &lt; n)) { ++count; } } else if ((j == b[i]) &amp;&amp; !found) { if (((b[i] - b[j]) &lt; 0) &amp;&amp; (abs(b[i] - b[j]) &lt; n)) { ++count; } found = true; } else { break; } } } //Check right if (b[i] &gt; i) { int nextRowStart = n * (by + 1); for (int j = i + 1; j &lt; nextRowStart; ++j) { if ((j != b[i]) &amp;&amp; !found) { if (((b[i] - b[j]) &gt; 0) &amp;&amp; (abs(b[i] - b[j]) &lt; n)) { ++count; } } else if ((j == b[i]) &amp;&amp; !found) { if (((b[i] - b[j]) &gt; 0) &amp;&amp; (abs(b[i] - b[j]) &lt; n)) { ++count; } found = true; } else { break; } } } } } } return 2 * count; } //Check if board is solvable bool Manager::checkSolvable() { int count = 0; int pos = 0; //Assume board is not solvable bool solvable = false; for (int i = 0; i &lt; n * n; ++i) { for (int j = i + 1; j &lt; n * n; ++j) { if (current-&gt;b[j] &lt; current-&gt;b[i]) { ++count; } } } //If width is odd and count is even if ((n % 2 == 1) &amp;&amp; (count % 2 == 0)) { solvable = true; } //If width is even, zeroY pos is odd from bottom, and count is even else if (((n - zeroY) % 2 == 1) &amp;&amp; (count % 2 == 0)) { solvable = true; } //If width is even, zeroY pos is even from bottom, and count is odd else if (count % 2 == 1) { solvable = true; } return solvable; } //Encode binary board UINT64 Manager::encode(int b[]) { UINT64 code = 0; for (int i = 0; i &lt; n * n; ++i) { //Set first four bits if (i == 0) { code |= b[i]; } //Set rest of bits else { code = ((code &lt;&lt; 4) | b[i]); } } return code; } //Decode binary board int* Manager::decode(UINT64 code) { static int b[n * n]; for (int i = (n * n) - 1; i &gt;= 0; --i) { int val = 0; //Get first four bits val = code &amp; ((1 &lt;&lt; 4) - 1); //Delete first four bits code = code &gt;&gt; 4; //Save val in board b[i] = val; if (val == 0) { zeroX = i % n; zeroY = i / n; } } return b; } void Manager::addMoves() { //Set current to open.top current = open.top(); findZero(); //Create new move Container* move = 0; //Remove top from open open.pop(); //Check for directional moves up(); down(); left(); right(); } //Y - 1 void Manager::up() { int newPos; Container* move = new Container; newPos = zeroY - 1; //Check if move is possible if (newPos &lt; 0) { return; } //Calculate new pos newPos = zeroX + (newPos * n); //Swap positions swapPos(move, newPos); //Check for duplicate board checkDuplicate(move); } //Y + 1 void Manager::down() { int newPos; Container* move = new Container; newPos = zeroY + 1; //Check if move is possible if (newPos &gt; (n - 1)) { return; } //Calculate new pos newPos = zeroX + (newPos * n); //Swap positions swapPos(move, newPos); //Check for duplicate board checkDuplicate(move); } //X - 1 void Manager::left() { int newPos; Container* move = new Container; newPos = zeroX - 1; //Check if move is possible if (newPos &lt; 0) { return; } //Calculate new pos newPos = newPos + (zeroY * n); //Swap positions swapPos(move, newPos); //Check for duplicate board checkDuplicate(move); } //X + 1 void Manager::right() { int newPos; Container* move = new Container; newPos = zeroX + 1; //Check if move is possible if (newPos &gt; (n - 1)) { return; } //Calculate new pos newPos = newPos + (zeroY * n); //Swap positions swapPos(move, newPos); //Check for duplicate board checkDuplicate(move); } void Manager::findZero() { for (int i = 0; i &lt; n * n; ++i) { if (current-&gt;b[i] == 0) { zeroX = i % n; zeroY = i / n; } } } void Manager::swapPos(Container* move, int newPos) { int oldPos; //Calculate old pos oldPos = zeroX + (zeroY * n); //Copy current board for (int i = 0; i &lt; n * n; ++i) { move-&gt;b[i] = current-&gt;b[i]; } //Swap pos move-&gt;b[oldPos] = move-&gt;b[newPos]; move-&gt;b[newPos] = 0; } bool Manager::checkDuplicate(Container* move) { UINT64 code = encode(move-&gt;b); //Check if board has been found if (closed[code] == true) { return false; } else { //If it hasn't been found, set container values and add to open move-&gt;heuristic = calculateManhattan(move-&gt;b) + calculateLinear(move-&gt;b); move-&gt;parent = current; open.push(move); } return true; } void Manager::printSolution(Container* top) { std::chrono::duration&lt;double&gt; t = end - start; Container* curr = top; std::vector&lt;Container*&gt; rev; bool go = true; int steps = 0; while (curr-&gt;parent) { rev.insert(rev.begin(), curr); curr = curr-&gt;parent; ++steps; } for (int i = 0; i &lt; steps; ++i) { for (int j = 0; j &lt; n * n; ++j) { std::cout &lt;&lt; rev[i]-&gt;b[j] &lt;&lt; "\t"; if (j % n == 3) { std::cout &lt;&lt; std::endl; } } Sleep(25); if (i != steps - 1) { system("CLS"); } } std::cout &lt;&lt; steps &lt;&lt; " steps in " &lt;&lt; t.count() &lt;&lt; "s."; std::cin.get(); } </code></pre> <h2><code>Main.cpp</code></h2> <pre><code>#include "Manager.h" int main() { Manager manager; manager.Run(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T09:41:48.110", "Id": "396697", "Score": "1", "body": "Do you really need `<Windows.h>`? If I include `<cstdint>` instead, I can `using UINT64 = std::uint64_t;` and replace the `Sleep()` with `std::this_thread::sleep_for()`, and it ...
[ { "body": "<h1>Platform-dependent code</h1>\n\n<p>There's no need to bring in <code>&lt;Windows.h&gt;</code> - with a couple of small changes, this can be portable C++, accessible to everyone:</p>\n\n<pre><code>#include &lt;cstdint&gt;\nusing UINT64 = std::uint_fast64_t; /* this is the quick fix - really, just...
{ "AcceptedAnswerId": "205710", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T09:12:54.157", "Id": "205667", "Score": "3", "Tags": [ "c++", "time-limit-exceeded", "a-star", "sliding-tile-puzzle" ], "Title": "N-puzzle solver using A* with Manhattan + Linear Conflict" }
205667
<p>I'm going through the K&amp;R book (2nd edition, ANSI C ver.) and want to get the most from it. How does the following solution look to you? Note that, for the sake of exercise, I don't want to use techniques not introduced yet in the book. Also, I'm trying to reuse whatever code/philosophy already presented in the book.</p> <pre><code>/* Exercise 1-13. Write a program to print a histogram of the lengths of words in * its input. It is easy to draw the histogram with the bars horizontal; a vertical * orientation is more challenging. * */ /* Solution 1: Horizontal Bars * */ #include &lt;stdio.h&gt; #define MAXLEN 10 /* Any word longer than this will get counted in the &gt;MAXLEN histogram. * For output formatting, the program assumes this won't be greater than 999. * */ #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ int main() { int c, state; int i, j; int histo[MAXLEN+1]; int counter; for (i = 0; i &lt; MAXLEN+1; ++i) histo[i] = 0; /* Perform the counting */ state = OUT; counter = 0; while ((c = getchar()) != EOF) if (c == ' ' || c == '\n' || c == '\t') { if (state == IN &amp;&amp; counter &gt; 0) { if (counter-1 &lt; MAXLEN) ++histo[counter-1]; else ++histo[MAXLEN]; } state = OUT; counter = 0; } else { ++counter; if (state == OUT) state = IN; } /* Print horizontal histogram. I'd use a function for formatting * with regards to max. number of digits, but functions haven't * been introduced yet. * */ for (i = 0; i &lt; MAXLEN; ++i) { if (MAXLEN &lt; 10) printf(" %1d | ", i+1); else if (MAXLEN &lt; 100) printf(" %2d |", i+1); else printf(" %3d |", i+1); for (j = 0; j &lt; histo[i]; ++j) putchar('*'); putchar('\n'); } if (MAXLEN &lt; 10) printf("&gt;%1d |", i); else if (MAXLEN &lt; 100) printf("&gt;%2d |", i); else printf("&gt;%3d |", i); for (j = 0; j &lt; histo[i]; ++j) putchar('*'); putchar('\n'); } </code></pre> <p>Output when run on the program code:</p> <pre><code>$ cat ch1-ex-1-13-01.c | ./ch1-ex-1-13-01 1 |********************************************************* 2 |**************************************************************** 3 |*************************************** 4 |************************************ 5 |************** 6 |********** 7 |************************ 8 |*********** 9 |******* 10 |********* &gt;10 |************** </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T15:59:10.177", "Id": "397015", "Score": "0", "body": "By the way, which Version of the C Standard are you targeting? Premordial, K&R, C90, C99, C11?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T16:...
[ { "body": "<p>K&amp;R C requires all variables to be declared at the start of their enclosing block. This is a bad habit to learn: it's much safer to declare variables where they can be initialised:</p>\n<pre><code>/* these can already be initialised where they are declared */\nint state = OUT;\nint histo[MAXL...
{ "AcceptedAnswerId": "205680", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T11:28:01.243", "Id": "205674", "Score": "3", "Tags": [ "beginner", "c", "io", "ascii-art", "data-visualization" ], "Title": "K&R Exercise 1-13. Printing histogram of word lengths (horizontal variant)" }
205674
<p>From original very simplistic code: <a href="https://codereview.stackexchange.com/questions/182381/shell-posix-openssl-file-decryption-script">Shell POSIX OpenSSL file decryption script</a></p> <p>I learned a lot both from the <a href="https://codereview.stackexchange.com/a/196804/104270">first follow-up review</a>, and the <a href="https://codereview.stackexchange.com/a/205579/104270">second one</a> as well, many thanks!</p> <hr> <p>I just need one final review round, so that I can feel confident, there are no more <em>blind spots</em>.</p> <p>I promise it is the last from this project, I don't expect you to upvote or anythig else than actually do the review of the script.</p> <hr> <p><strong>Changes:</strong></p> <ul> <li><p><code>check_for_prerequisites</code>, notice the <code>s</code> at the end, is now looping over given arguments.</p></li> <li><p>POSIX compliance, no long options or anything else.</p></li> <li><p>Relatively small files (&lt; 1GiB) are on an SSD en-/decrypted within seconds, so <code>pv</code> got out completely on such files.</p></li> <li><p>In any case, the script newly works directly without the <code>pv</code>, so no more a prerequisite.</p></li> <li><p>Not quoting variable assignments anymore.</p></li> <li><p>Simplified <code>printf</code> strings in error handler.</p></li> <li><p>If the destination file exists, it no longer exits, and asks for if the user wants to overwrite the file.</p></li> <li><p>File size &lt; Free space check is done in KiloBytes now.</p></li> <li><p>Various small changes I don't recall otherwise.</p></li> </ul> <hr> <p>Decription script follows:</p> <pre><code>#!/bin/sh ############################################################################### ## OpenSSL file decryption POSIX shell script ## ## revision: 1.0 ## ## GitHub: https://git.io/fxslm ## ############################################################################### # shellcheck disable=SC2016 # disable shellcheck information SC2016 globally for the script # link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2016 # reason: the script's main parts use constructs like that # treat unset variables as an error when substituting set -o nounset # pipe will be considered successful only if all the commands involved are executed without errors # ERROR: Illegal option -o pipefail. This likely works in Bash and alike only. #set -o pipefail #------------------------------------------------------------------------------ colors_supported() { command -v tput &gt; /dev/null 2&gt;&amp;1 &amp;&amp; tput setaf 1 &gt; /dev/null 2&gt;&amp;1 } #------------------------------------------------------------------------------ print_error_and_exit() # expected arguments: # $1 = exit code # $2 = error origin (usually function name) # $3 = error message { # redirect all output of this function to standard error stream exec 1&gt;&amp;2 # check if exactly 3 arguments have been passed # if not, print out an internal error without colors if [ "${#}" -ne 3 ] then printf 'print_error_and_exit internal error\n\n\tWrong number of arguments has been passed: %b!\n\tExpected the following 3:\n\t\t$1 - exit code\n\t\t$2 - error origin\n\t\t$3 - error message\n\nexit code = 1\n' "${#}" exit 1 fi # check if the first argument is a number # if not, print out an internal error without colors if ! [ "${1}" -eq "${1}" ] 2&gt; /dev/null then printf 'print_error_and_exit internal error\n\n\tThe first argument is not a number: %b!\n\tExpected an exit code from the script.\n\nexit code = 1\n' "${1}" exit 1 fi # check if we have color support if colors_supported then # color definitions readonly bold=$(tput bold) readonly red=$(tput setaf 1) readonly white=$(tput setaf 7) readonly yellow=$(tput setaf 3) readonly nocolor=$(tput sgr0) # here we have color support, so we highlight everything in different color printf '%b\n\n\t%b\n\n%b\n' \ "${bold}${yellow}${2}${nocolor}" \ "${bold}${white}${3}${nocolor}" \ "${bold}${red}Error occurred, see above.${nocolor}" else # here we do not have color support printf '%b\n\n\t%b\n\n%b\n' \ "${2}" \ "${3}" \ "Error occurred, see above." fi exit "${1}" } #------------------------------------------------------------------------------ # in this function, the SC2120 warning is irrelevant and safe to ignore # link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2120 # shellcheck disable=SC2120 am_i_root() # expected arguments: none { # check if no argument has been passed [ "${#}" -eq 0 ] || print_error_and_exit 1 "am_i_root" "Some arguments have been passed to the function!\\n\\tNo arguments expected.\\n\\tPassed: ${*}" # check if the user is root # this will return an exit code of the command itself directly [ "$(id -u)" -eq 0 ] } # check if the user had by any chance run the script with root privileges # if you need to run it as root, feel free to comment out the line below # in this function call, the SC2119 information is irrelevant and safe to ignore # link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2119 # shellcheck disable=SC2119 am_i_root &amp;&amp; print_error_and_exit 1 "am_i_root" "Running this script with root privileges is discouraged!\\n\\tQuiting to shell." #------------------------------------------------------------------------------ check_for_prerequisites() # expected arguments: # any number of commands / program names { while [ "${#}" -gt 0 ] do # check if the argument is a program which is installed command -v "${1}" &gt; /dev/null 2&gt;&amp;1 || print_error_and_exit 1 "check_for_prerequisites" "This script requires '${1}' but it is not installed or available on this system!\\n\\tPlease install the corresponding package manually." # move to the next argument shift done } check_for_prerequisites openssl file grep df du tail awk #------------------------------------------------------------------------------ is_number() # expected arguments: # $1 = variable or literal { # check if exactly one argument has been passed [ "${#}" -eq 1 ] || print_error_and_exit 1 "is_number" "Exactly one argument has not been passed to the function!\\n\\tOne variable or literal to test expected.\\n\\tPassed: ${*}" # check if the argument is an integer number # this will return an exit code of the command itself directly [ "${1}" -eq "${1}" ] 2&gt; /dev/null } #------------------------------------------------------------------------------ print_usage_and_exit() { # check if exactly one argument has been passed [ "${#}" -eq 1 ] || print_error_and_exit 1 "print_usage_and_exit" "Exactly one argument has not been passed to the function!\\n\\tPassed: ${*}" # check if the argument is a number is_number "${1}" || print_error_and_exit 1 "print_usage_and_exit" "The argument is not a number!\\n\\Expected an exit code from the script.\\n\\tPassed: ${1}" # in case of non-zero exit code given, redirect all output to stderr [ "${1}" -ne 0 ] &amp;&amp; exec 1&gt;&amp;2 echo "Usage: ${0} [-o directory] file" echo echo " -o directory: Write the output file into the given directory;" echo " Optional and must be given before the file." echo echo " file: Regular file to decrypt." exit "${1}" } #------------------------------------------------------------------------------ given_output_directory= while getopts ":ho:" option do case "${option}" in o) given_output_directory=${OPTARG} ;; h) print_usage_and_exit 0 ;; *) print_usage_and_exit 1 ;; esac done shift $(( OPTIND - 1 )) #------------------------------------------------------------------------------ [ "${#}" -eq 0 ] &amp;&amp; print_usage_and_exit 1 #------------------------------------------------------------------------------ [ "${#}" -gt 1 ] &amp;&amp; print_error_and_exit 1 "[ ${#} -gt 1 ]" "You have passed ${#} arguments to the script!\\n\\tOnly one file expected.\\n\\tPassed: ${*}" #------------------------------------------------------------------------------ [ -f "${1}" ] || print_error_and_exit 1 "[ -f ${1} ]" "The given argument is not an existing regular file!\\n\\tPassed: ${1}" #------------------------------------------------------------------------------ input_file=${1} [ -r "${input_file}" ] || print_error_and_exit 1 "[ -r ${input_file} ]" "Input file is not readable by you!\\n\\tPassed: ${input_file}" #------------------------------------------------------------------------------ is_file_encrypted_using_openssl() { # check if exactly one argument has been passed [ "${#}" -eq 1 ] || print_error_and_exit 1 "is_file_encrypted_using_openssl" "Exactly one argument has not been passed to the function!\\n\\tPassed: ${*}" # check if the argument is a file [ -f "${1}" ] || print_error_and_exit 1 "is_file_encrypted_using_openssl" "The provided argument is not a regular file!\\n\\tPassed: ${1}" # check if the provided file has been encrypted using openssl # this will return an exit code of the command itself directly file "${1}" | grep -i openssl &gt; /dev/null 2&gt;&amp;1 } is_file_encrypted_using_openssl "${input_file}" || print_error_and_exit 1 "is_file_encrypted_using_openssl" "Input file does not seem to have been encrypted using OpenSSL!\\n\\tPassed: ${input_file}" #------------------------------------------------------------------------------ # parameter substitution with - modifier will cause the output_directory # variable to to get dirname ... in case given_output_directory is empty output_directory=${given_output_directory:-$(dirname "${input_file}")} [ -d "${output_directory}" ] || print_error_and_exit 1 "[ -d ${output_directory} ]" "Destination:\\n\\t\\t${output_directory}\\n\\tis not a directory!" [ -w "${output_directory}" ] || print_error_and_exit 1 "[ -w ${output_directory} ]" "Destination directory:\\n\\t\\t${output_directory}\\n\\tis not writable by you!" #------------------------------------------------------------------------------ filename_extracted_from_path=$(basename "${input_file}") filename_without_enc_extension=${filename_extracted_from_path%.enc} if [ "${filename_extracted_from_path}" = "${filename_without_enc_extension}" ] then # the file has a different than .enc extension or no extension at all # what we do now, is that we append .dec extention to the file name output_file=${output_directory}/${filename_extracted_from_path}.dec else # the file has the .enc extension # what we do now, is that we use the file name without .enc extension output_file=${output_directory}/${filename_without_enc_extension} fi #------------------------------------------------------------------------------ # -e FILE: True if file exists. Any type of file! if [ -e "${output_file}" ] then printf '%s' "Do you want to overwrite the file ${output_file}? [y/.]" read -r overwrite [ "${overwrite}" = "y" ] || print_error_and_exit 1 "[ ${overwrite} = y ]" "You have decided not to overwrite the file ${output_file}. Aborting." fi #------------------------------------------------------------------------------ file_size=$(du -k "${input_file}" | awk '{ print $1 }') free_space=$(df -k "${output_directory}" | tail -n 1 | awk '{ print $4 }') [ "${free_space}" -gt "${file_size}" ] || print_error_and_exit 1 "[ ${free_space} -gt ${file_size} ]" "There is not enough free space in the destination directory!\\n\\t\\tFile size: ${file_size}\\n\\t\\tFree space: ${free_space}" #------------------------------------------------------------------------------ # here comes the core part - decryption of the given file # we shall use 'pv' for files larger than 1GiB if available [ "${file_size}" -gt $(( 1024 * 1024 )) ] &amp;&amp; use_pv_if_available=0 || use_pv_if_available=1 if [ "${use_pv_if_available}" -eq 0 ] &amp;&amp; command -v pv &gt; /dev/null 2&gt;&amp;1 then pv -W -p -t -e -r -a -b "${input_file}" | openssl enc -aes-256-cbc -md sha256 -salt -out "${output_file}" -d else openssl enc -aes-256-cbc -md sha256 -salt -in "${input_file}" -out "${output_file}" -d fi #------------------------------------------------------------------------------ # in this test, the SC2181 information is safe to ignore # link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2181 # shellcheck disable=SC2181 if [ "${?}" -eq 0 ] then colors_supported &amp;&amp; ( tput bold; tput setaf 2 ) echo "Decryption successful." colors_supported &amp;&amp; tput sgr0 else [ -f "${output_file}" ] &amp;&amp; rm "${output_file}" print_error_and_exit 1 "openssl enc -aes-256-cbc -md sha256 -salt -in ${input_file} -out ${output_file} -d" "Decryption failed." fi </code></pre> <hr> <p>As always I do not attach the encryption script, as it is almost the same piece of code.</p> <hr> <p>Uploaded on GitHub: <a href="https://git.io/fxslm" rel="nofollow noreferrer">https://git.io/fxslm</a></p>
[]
[ { "body": "<p>The comment</p>\n\n<blockquote>\n<pre><code># disable shellcheck information SC2016 globally for the script\n# link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2016\n# reason: the script's main parts use constructs like that\n</code></pre>\n</blockquote>\n\n<p>doesn't add anything. Ins...
{ "AcceptedAnswerId": "205692", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T12:35:41.287", "Id": "205679", "Score": "0", "Tags": [ "linux", "aes", "sh", "posix", "openssl" ], "Title": "Shell POSIX OpenSSL file decryption script follow-up #3 (final)" }
205679
<p>I'm trying to learn writing python programs in a modular way as much as possible. One of the issues I've had difficulty to solve is parsing command line arguments (with <code>argparse</code>) and having a <code>logger</code> object in all my modules which it's <code>name</code> will be the <code>__name__</code> of the module and it's log level identical across all modules.</p> <p>I've even posted a <a href="https://stackoverflow.com/questions/52822477/logging-with-the-same-logging-levels-accross-modules">question on Sstack Overflow</a> where I describe the problem more thoroughly but I would like to gain some confidence with the solution I've constructed before posting an answer to my own question.</p> <p>This is the scheme I've come up with:</p> <h3><code>core/__init__.py</code>:</h3> <pre><code>from .argpconf import Argpconf import logging argpconf = Argpconf() _loglevel = argpconf.get_loglevel() class Logger(logging.Logger): def __init__(self, name, level=_loglevel): self.name = name logging.Logger.__init__(self, name, level) self.addHandler(argpconf.get_loghandler()) </code></pre> <h3><code>core/argpconf.py</code>:</h3> <pre><code>from argparse import ArgumentParser import logging class Argpconf(): def __init__(self): """ Define command line arguments parser """ self.argp = ArgumentParser( description="Generator for shell, ranger and vim commands for fzf based shortcuts" ) self.argp.add_argument( '-v', '--verbose', dest='verbosity', default=2, action='count', help='increase verbosity, use multiple times to increase more' ) self.args = vars(self.argp.parse_args()) def get_loglevel(self): # Convert logging level to the proper scale logging_level = self.args['verbosity'] * 10 # make sure a level higher then 50 won't be passed to setLevel logging_level = min(logging_level, 50) # reverse the numbers of so a higher verbosity will set a higher log level logging_level = 60 - logging_level return logging_level def get_logformat(self): if self.args['verbosity'] &gt; 2: return logging.Formatter('%(name)s - %(levelname)s - %(message)s') else: return logging.Formatter('%(message)s') def get_loghandler(self): handler = logging.StreamHandler() handler.setFormatter(self.get_logformat()) return handler </code></pre> <h3>Every other file that would like to use a <code>logger</code>:</h3> <pre><code>from core import Logger logger = Logger(__name__) ... </code></pre> <h2>Notes</h2> <ul> <li>The <code>Logger</code> class defined in <code>core/__init__.py</code> is based on <a href="https://github.com/python/cpython/blob/3.7/Lib/logging/__init__.py#L1326" rel="nofollow noreferrer">this</a>.</li> <li>The function <code>get_logformat</code> from <code>Argpconf</code> sets a different format for the messages so in debugging modes the <code>__name__</code> and <code>levelname</code> will be included, according to the verbosity set in the command line.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T18:50:20.907", "Id": "396736", "Score": "0", "body": "Your code will not compile: `argpconf.get_loglevel()` is not defined. I assume you have \"simplified\" the code for posting to \"Code Review\", but ended up removing too much. ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T13:15:25.917", "Id": "205681", "Score": "3", "Tags": [ "python", "logging", "modules" ], "Title": "Eassily create a logger in python for many modules with loglevel set according to command line arguments" }
205681
<p>In my program, I have a tree of <code>Group</code> nodes, each identified by their <code>ImportId</code>.</p> <p>Each group has zero or more members, that I want to collect.</p> <p>Each group has zero or more child groups, referenced by their importId, whose members should be added to the collection.</p> <p>Each group has zero or more <code>RulePart</code>s.</p> <p>Each rulePart is a collection of zero or more groups, referenced by their importId, whose members should be added or removed to the collection, depending on a boolean value <code>Negated</code> on each rulePart.</p> <p>I got the following code working:</p> <pre><code>internal class RulePartTraverser { public List&lt;string&gt; GetRulePartMembers(IReadOnlyList&lt;RulePart&gt; ruleParts, IReadOnlyList&lt;Group&gt; allGroups) { if (ruleParts is null || !ruleParts.Any() || allGroups is null || !allGroups.Any()) { return new List&lt;string&gt;(); } var positiveRuleParts = collectRulePartMembers(ruleParts.Where(rp =&gt; !rp.Negated), allGroups); var negativeRuleParts = collectRulePartMembers(ruleParts.Where(rp =&gt; rp.Negated), allGroups); return positiveRuleParts.Except(negativeRuleParts).ToList(); } private IEnumerable&lt;string&gt; collectRulePartMembers(IEnumerable&lt;RulePart&gt; ruleParts, IReadOnlyList&lt;Group&gt; allGroups) { var members = ruleParts.Aggregate( seed: new List&lt;string&gt;().AsEnumerable(), (current, rp) =&gt; current.Union(collectIndirectMembers(rp.RulePartMemberImportIds, allGroups))); return members; } private IEnumerable&lt;string&gt; collectIndirectMembers(List&lt;string&gt; indirectGroupImportIds, IReadOnlyList&lt;Group&gt; allGroups) { var returnList = indirectGroupImportIds.Aggregate( seed: new List&lt;string&gt;().AsEnumerable(), (current, importId) =&gt; { var correspondingGroup = allGroups.Single(ag =&gt; ag.ImportId == importId); return current.Union(GetRulePartMembers(correspondingGroup.RuleParts, allGroups)) .Union(collectIndirectMembers(correspondingGroup.Children, allGroups)) .Union(correspondingGroup.Members); }); return returnList; } } public class RulePart { public bool Negated { get; set; } public List&lt;string&gt; RulePartMemberImportIds { get; set; } } public class Group { public string ImportId { get; set; } public string Name { get; set; } public List&lt;string&gt; Children { get; set; } public List&lt;string&gt; Members { get; set; } public List&lt;RulePart&gt; RuleParts { get; set; } } </code></pre> <p>The above method accepts a list of ruleParts for a given group and a list of all groups.</p> <p>Some sanity checks are performed and if they fail, an empty list is returned.</p> <p>It then collects all members of all ruleParts that <em>are not</em> negated, then collects all members of all ruleParts that <em>are</em> negated and substracts the latter from the former. The resulting collection is returned.</p> <p>In order to collect all members of a single rulePart, all rulePartMembers are inspected and all the members of the corresponding groups are collected.</p> <p>To collect all members of a given single group, I recursively collect all members of the corresponding ruleParts; then I recursively add the members of all child groups, potentially collecting the members of this child group's ruleParts and this child group's children. Finally I add all direct members of the group and step up.</p> <p>Due to the nature of my data structure, I fear that this is the best I can do. However, is it possible (or sensible) to replace the recursion by an iteration? Are there other things I could or should improve?</p> <hr> <p>The following example is not too far away from a real case scenario, I hope it helps in explaining the data structure:</p> <pre><code> var rootGroup = new Group { ImportId = "Root", Members = new List&lt;string&gt;(), Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt; { new RulePart{Negated = false, RulePartMemberImportIds = new List&lt;string&gt;{ "group01", "group02" } }, //add all members of groups group01 and group02 to the collection new RulePart{Negated = true, RulePartMemberImportIds = new List&lt;string&gt;{"group03", "group04"}} //but remove all members of groups group03 and group04 } }; var group01 = new Group { ImportId = "group01", Members = new List&lt;string&gt;(), Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt; { new RulePart{Negated = false, RulePartMemberImportIds = new List&lt;string&gt;{"group05"}}, //add all members of group05 new RulePart{Negated = true, RulePartMemberImportIds = new List&lt;string&gt;{"group06"}} //remove all members of group06 } }; var group02 = new Group { ImportId = "group02", Members = new List&lt;string&gt; { "member01", "member04", "member05" }, Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt;() }; var group03 = new Group { ImportId = "group03", Members = new List&lt;string&gt; { "member06", "member07", "member09" }, Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt;() }; var group04 = new Group { ImportId = "group04", Members = new List&lt;string&gt; { "member09", "member10", "member11" }, Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt;() }; var group05 = new Group { ImportId = "group05", Members = new List&lt;string&gt;(), Children = new List&lt;string&gt; { "group07", "group08" }, //add all members of groups group07 and group08 RuleParts = new List&lt;RulePart&gt;() }; var group06 = new Group { ImportId = "group06", Members = new List&lt;string&gt; { "member02" }, Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt;() }; var group07 = new Group { ImportId = "group07", Members = new List&lt;string&gt; { "member12" }, Children = new List&lt;string&gt;(), RuleParts = new List&lt;RulePart&gt;() }; var group08 = new Group { ImportId = "group08", Members = new List&lt;string&gt;(), Children = new List&lt;string&gt; { "group04" }, //add all members of group04 RuleParts = new List&lt;RulePart&gt;() }; var expectedMembers = new List&lt;string&gt; { "member01", "member04", "member05", "member12" }; </code></pre> <p>The rule parts of the <code>Root</code>Group would serve as input to <code>GetRulePartMembers</code>. </p> <p>In order to collect the members of the different rule parts, first the members of groups <code>group01</code> - <code>group04</code> have to be determined. </p> <p>For <code>group01</code>, this means determining the members of the ruleparts of <code>group01</code>, ie determining the members of groups <code>group05</code> and <code>group06</code>, as these are ruleparts of <code>group01</code>. </p> <p>As <code>group05</code> has child groups, the members of <code>group05</code> is the union of the members of groups <code>group07</code> and <code>group08</code>, <code>group08</code> has a single child group <code>group04</code>, so the members of <code>group08</code> are the members of <code>group04</code>, yielding <code>member09, member10, member11</code> for <code>group08</code>, resulting in <code>member09, member10, member11, member12</code> for <code>group05</code>.</p> <p>The single member of <code>group06</code> is <code>member02</code>, removing it from the result collection of <code>group05</code> results in the collection <code>member09, member10, member11, member12</code> for <code>group01</code>.</p> <p>For <code>group02</code>, the members are directly <code>member01, member04, member05</code>, which results in the member collection <code>member01, member04, member05, member09, member10, member11, member12</code> for the non-negated rulepart of the <code>Root</code>Group.</p> <p>For the negated rulepart of the <code>Root</code>Group, the members of <code>group03</code> and <code>group04</code> can directly be added to the result collection, as neither of the groups have children or ruleparts. This results in <code>member06, member07, member09, member10, member11</code> for the negated rulepart.</p> <p>These members are then removed from the collection of members for the non-negated rulepart, yielding the final result of <code>member01, member04, member05, member12</code> for the <code>Root</code>Group.</p>
[]
[ { "body": "<p>Just a couple of tipps...</p>\n\n<hr>\n\n<blockquote>\n<pre><code>if (ruleParts is null || !ruleParts.Any() || allGroups is null || !allGroups.Any())\n</code></pre>\n</blockquote>\n\n<p>This sanity checks would be a big surprise for me because <code>null</code> is virtually never a valid value so ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T13:43:32.170", "Id": "205683", "Score": "3", "Tags": [ "c#", "recursion", "tree", "iteration" ], "Title": "Collect members from custom tree nodes" }
205683
<p>I have been working on my script which allows people to sign-up and login to my website. I was wondering if someone could review the code. It works but I can't help but feel it could be optimized.</p> <h3>forgot_password.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // include login checker require_once "login_checker.php"; // include classes require_once "config/database.php"; require_once 'objects/user.php'; require_once "libs/php/utils.php"; // get database connection $database = new Database(); $db = $database-&gt;getConnection(); // initialize objects $user = new User($db); $utils = new Utils(); // header HTML require_once "layout_head.php"; // if the login form was submitted if ($_POST) { echo "&lt;div class='col-sm-12'&gt;"; // check if username and password are in the database $user-&gt;email = $_POST['email']; if ($user-&gt;emailExists()) { // update access code for user $access_code = $utils-&gt;getToken(); $user-&gt;access_code = $access_code; if ($user-&gt;updateAccessCode()) { // send reset link $body="Hi there.&lt;br /&gt;&lt;br /&gt;"; $body.="Please click the following link to reset your password: {$home_url}reset_password/?access_code={$access_code}"; $subject="Reset Password"; $send_to_email=$_POST['email']; if ($utils-&gt;sendEmailViaPhpMail($send_to_email, $subject, $body)) { echo "&lt;div class='alert alert-info'&gt; Password reset link was sent to your email. Click that link to reset your password. &lt;/div&gt;"; } else { // message if unable to send email for password reset link echo "&lt;div class='alert alert-danger'&gt;ERROR: Unable to send reset link.&lt;/div&gt;"; } } else { // message if unable to update access code echo "&lt;div class='alert alert-danger'&gt;ERROR: Unable to update access code.&lt;/div&gt;"; } } else { // message if email does not exist echo "&lt;div class='alert alert-danger'&gt;Your email cannot be found.&lt;/div&gt;"; } echo "&lt;/div&gt;"; } ?&gt; &lt;div class='col-md-4'&gt;&lt;/div&gt; &lt;div class='col-md-4'&gt; &lt;div class='account-wall'&gt; &lt;div id='my-tab-content' class='tab-content'&gt; &lt;div class='tab-pane active' id='login'&gt; &lt;img class='profile-img' src='images/login-icon.png'&gt; &lt;form class='form-signin' action='&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?&gt;' method='post'&gt; &lt;input type='email' name='email' class='form-control' placeholder='Your email' required autofocus&gt; &lt;input type='submit' class='btn btn-lg btn-primary btn-block' value='Send Reset Link' style='margin-top:1em;' /&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='col-md-4'&gt;&lt;/div&gt; &lt;?php // footer HTML and JavaScript codes require_once "layout_foot.php"; ?&gt; </code></pre> <h3>index.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // include login checker $require_login = true; require_once "login_checker.php"; // header HTML require_once 'layout_head.php'; ?&gt; &lt;div class='col-md-12'&gt; &lt;p&gt;Hi, &lt;?php echo $_SESSION['firstname']; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php // footer HTML and JavaScript codes require 'layout_foot.php'; ?&gt; </code></pre> <h3>login.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // include login checker $require_login = false; require_once "login_checker.php"; // default to false $access_denied = false; // if the login form was submitted if ($_POST) { // include classes include_once "config/database.php"; include_once "objects/user.php"; // get database connection $database = new Database(); $db = $database-&gt;getConnection(); // initialize objects $user = new User($db); // check if email and password are in the database $user-&gt;email = $_POST['email']; // check if email exists, also get user details using this emailExists() method $email_exists = $user-&gt;emailExists(); // validate login if ($email_exists &amp;&amp; password_verify($_POST['password'], $user-&gt;password) &amp;&amp; $user-&gt;status==1) { // if it is, set the session value to true $_SESSION['logged_in'] = true; $_SESSION['user_id'] = $user-&gt;id; $_SESSION['access_level'] = $user-&gt;access_level; $_SESSION['firstname'] = htmlspecialchars($user-&gt;firstname, ENT_QUOTES, 'UTF-8'); $_SESSION['lastname'] = $user-&gt;lastname; // if the access level detected is 'Administrator', redirect the user to the administrator section if ($user-&gt;access_level=='Administrator') { header("Location: {$home_url}admin/index.php"); } else { // else, redirect only to 'Customer' section header("Location: {$home_url}index.php"); } } else { // if username does not exist or password is wrong $access_denied = true; } } // header HTML require_once "layout_head.php"; ?&gt; &lt;div class='col-sm-6 col-md-4 col-md-offset-4'&gt; &lt;?php $action = isset($_GET['action']) ? $_GET['action'] : ""; ?&gt; &lt;?php if ($action =='not_yet_logged_in') : ?&gt; &lt;div class='alert alert-danger margin-top-40' role='alert'&gt; Please login. &lt;/div&gt; &lt;?php elseif ($action =='account_verified') : ?&gt; &lt;div class='alert alert-info'&gt; Your account has been verified, you can now login. &lt;/div&gt; &lt;?php elseif ($action =='password_reset') : ?&gt; &lt;div class='alert alert-info'&gt; Password was reset. Please login. &lt;/div&gt; &lt;?php elseif ($access_denied) : ?&gt; &lt;div class='alert alert-danger margin-top-40' role='alert'&gt; Access Denied.&lt;br /&gt;&lt;br /&gt; Your username or password maybe incorrect &lt;/div&gt; &lt;?php endif; ?&gt; &lt;div class='account-wall'&gt; &lt;div id='my-tab-content' class='tab-content'&gt; &lt;div class='tab-pane active' id='login'&gt; &lt;img class='profile-img' src='images/login-icon.png'&gt; &lt;form class='form-signin' action='&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?&gt;' method='post'&gt; &lt;input type='text' name='email' class='form-control' placeholder='Email' required autofocus /&gt; &lt;input type='password' name='password' class='form-control' placeholder='Password' required /&gt; &lt;input type='submit' class='btn btn-lg btn-primary btn-block' value='Log In' /&gt; &lt;div class='margin-1em-zero text-align-center'&gt; &lt;a href='&lt;?php echo $home_url; ?&gt;forgot_password.php'&gt;Forgot password?&lt;/a&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php // footer HTML and JavaScript codes require_once "layout_foot.php"; ?&gt; </code></pre> <h3>login_checker.php</h3> <pre><code>&lt;?php // login checker for the 'Customer' access level // if the access level detected was not 'Administrator', redirect the user to the login page if (isset($_SESSION['access_level']) &amp;&amp; $_SESSION['access_level']=="Administrator") { header("Location: {$home_url}admin/index.php"); } // if $require_login was set and value is 'true' else if (isset($require_login) &amp;&amp; $require_login==true) { // if user not yet logged in, redirect to login page if (!isset($_SESSION['access_level'])) { header("Location: {$home_url}login.php"); } } else if (isset($_SESSION['access_level']) &amp;&amp; $_SESSION['access_level']=="Customer") { header("Location: {$home_url}index.php"); } else { // no problem, stay on current page } ?&gt; </code></pre> <h3>logout.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // destroy session, it will remove ALL session settings session_destroy(); //redirect to login page header("Location: {$home_url}login.php"); ?&gt; </code></pre> <h3>register.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // include login checker require_once "login_checker.php"; // include classes require_once 'config/database.php'; require_once 'objects/user.php'; require_once "libs/php/utils.php"; // header HTML require_once "layout_head.php"; ?&gt; &lt;div class='col-md-12'&gt; &lt;?php // if form was posted if ($_POST) { // get database connection $database = new Database(); $db = $database-&gt;getConnection(); // initialize objects $user = new User($db); $utils = new Utils(); // set user email to detect if it already exists $user-&gt;email = $_POST['email']; // check if email already exists if ($user-&gt;emailExists()) { echo "&lt;div class='alert alert-danger'&gt;"; echo "The email you specified is already registered. Please try again or &lt;a href='{$home_url}login'&gt;login.&lt;/a&gt;"; echo "&lt;/div&gt;"; } else { // set values to object properties $user-&gt;firstname = $_POST['firstname']; $user-&gt;lastname = $_POST['lastname']; $user-&gt;contact_number = $_POST['contact_number']; $user-&gt;address = $_POST['address']; $user-&gt;password = $_POST['password']; $user-&gt;access_level = 'Customer'; $user-&gt;status = 0; // access code for email verification $access_code = $utils-&gt;getToken(); $user-&gt;access_code = $access_code; // create the user if ($user-&gt;create()) { // send confimation email $send_to_email=$_POST['email']; $body="Hi {$send_to_email}.&lt;br /&gt;&lt;br /&gt;"; $body.="Please click the following link to verify your email and login: {$home_url}verify/?access_code={$access_code}"; $subject="Verification Email"; if ($utils-&gt;sendEmailViaPhpMail($send_to_email, $subject, $body)) { echo "&lt;div class='alert alert-success'&gt; Verification link was sent to your email. Click that link to login. &lt;/div&gt;"; } else { echo "&lt;div class='alert alert-danger'&gt; User was created but unable to send verification email. Please contact admin. &lt;/div&gt;"; } // empty posted values $_POST = array(); } else { echo "&lt;div class='alert alert-danger' role='alert'&gt;Unable to register. Please try again.&lt;/div&gt;"; } } } ?&gt; &lt;form action='register.php' method='post' id='register'&gt; &lt;table class='table table-responsive'&gt; &lt;tr&gt; &lt;td class='width-30-percent'&gt;Firstname&lt;/td&gt; &lt;td&gt;&lt;input type='text' name='firstname' class='form-control' required value="&lt;?php echo isset($_POST['firstname']) ? htmlspecialchars($_POST['firstname'], ENT_QUOTES) : ""; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Lastname&lt;/td&gt; &lt;td&gt;&lt;input type='text' name='lastname' class='form-control' required value="&lt;?php echo isset($_POST['lastname']) ? htmlspecialchars($_POST['lastname'], ENT_QUOTES) : ""; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Contact Number&lt;/td&gt; &lt;td&gt;&lt;input type='text' name='contact_number' class='form-control' required value="&lt;?php echo isset($_POST['contact_number']) ? htmlspecialchars($_POST['contact_number'], ENT_QUOTES) : ""; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Address&lt;/td&gt; &lt;td&gt;&lt;textarea name='address' class='form-control' required&gt;&lt;?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address'], ENT_QUOTES) : ""; ?&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Email&lt;/td&gt; &lt;td&gt;&lt;input type='email' name='email' class='form-control' required value="&lt;?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES) : ""; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Password&lt;/td&gt; &lt;td&gt;&lt;input type='password' name='password' class='form-control' required /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Confirm Password&lt;/td&gt; &lt;td&gt; &lt;input type="password" name="confirm_password" class="form-control" required /&gt; &lt;p&gt;&lt;/p&gt; &lt;div class="alert alert-danger"&gt;Passwords do not match!&lt;/div&gt; &lt;p&gt;&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt; &lt;button type="submit" class="btn btn-primary"&gt; &lt;span class="glyphicon glyphicon-plus"&gt;&lt;/span&gt; Register &lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php // include page footer HTML require_once "layout_foot.php"; ?&gt; </code></pre> <h3>reset_password.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // include login checker require_once "login_checker.php"; // include classes require_once "config/database.php"; require_once "objects/user.php"; // get database connection $database = new Database(); $db = $database-&gt;getConnection(); // initialize objects $user = new User($db); // header HTML require_once "layout_head.php"; ?&gt; &lt;div class='col-sm-12'&gt; &lt;?php // get given access code $access_code = isset($_GET['access_code']) ? $_GET['access_code'] : die("Access code not found."); // check if access code exists $user-&gt;access_code = $access_code; if (!$user-&gt;accessCodeExists()) { die('Access code not found.'); } else { // if form was posted if ($_POST) { // set values to object properties $user-&gt;password = $_POST['password']; // reset password if ($user-&gt;updatePassword()) { header("Location: {$home_url}login.php?action=password_reset"); } else { echo "&lt;div class='alert alert-danger'&gt;Unable to reset password.&lt;/div&gt;"; } } ?&gt; &lt;form action='&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?&gt;?access_code=&lt;?php echo $access_code; ?&gt;' method='post'&gt; &lt;table class='table table-hover table-responsive table-bordered'&gt; &lt;tr&gt; &lt;td&gt;Password&lt;/td&gt; &lt;td&gt;&lt;input type='password' name='password' class='form-control' required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;button type='submit' class='btn btn-primary'&gt;Reset Password&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } // include page footer HTML require_once "layout_foot.php"; ?&gt; </code></pre> <h3>verify.php</h3> <pre><code>&lt;?php // core configuration require_once "config/core.php"; // include classes require_once 'config/database.php'; require_once 'objects/user.php'; // get database connection $database = new Database(); $db = $database-&gt;getConnection(); // initialize objects $user = new User($db); // set access code $user-&gt;access_code = isset($_GET['access_code']) ? $_GET['access_code'] : ""; // verify if access code exists if (!$user-&gt;accessCodeExists()) { die("ERROR: Access code not found."); } else { // update status $user-&gt;status = 1; $user-&gt;updateStatusByAccessCode(); // and the redirect header("Location: {$home_url}login.php?action=account_verified"); } ?&gt; </code></pre> <h3>user.php</h3> <pre><code>&lt;?php // 'user' object class User { // database connection and table name private $conn; private $table_name = "users"; // object properties public $id; public $firstname; public $lastname; public $email; public $contact_number; public $address; public $password; public $access_level; public $access_code; public $status; public $created; public $modified; // constructor public function __construct($db) { $this-&gt;conn = $db; } // check if given email exist in the database function emailExists() { // query to check if email exists $query = "SELECT id, firstname, lastname, access_level, password, status FROM " . $this-&gt;table_name . " WHERE email = ? LIMIT 0,1"; // prepare the query $stmt = $this-&gt;conn-&gt;prepare($query); // sanitize $this-&gt;email = htmlspecialchars(strip_tags($this-&gt;email)); // bind given email value $stmt-&gt;bindParam(1, $this-&gt;email); // execute the query $stmt-&gt;execute(); // get number of rows $num = $stmt-&gt;rowCount(); // if email exists, assign values to object properties for easy access and use for php sessions if ($num&gt;0) { // get record details / values $row = $stmt-&gt;fetch(PDO::FETCH_ASSOC); // assign values to object properties $this-&gt;id = $row['id']; $this-&gt;firstname = $row['firstname']; $this-&gt;lastname = $row['lastname']; $this-&gt;access_level = $row['access_level']; $this-&gt;password = $row['password']; $this-&gt;status = $row['status']; // return true because email exists in the database return true; } // return false if email does not exist in the database return false; } // create new user record function create() { // to get time stamp for 'created' field $this-&gt;created = date('Y-m-d H:i:s'); // insert query $query = "INSERT INTO " . $this-&gt;table_name . " SET firstname = :firstname, lastname = :lastname, email = :email, contact_number = :contact_number, address = :address, password = :password, access_level = :access_level, access_code = :access_code, status = :status, created = :created"; // prepare the query $stmt = $this-&gt;conn-&gt;prepare($query); // sanitize $this-&gt;firstname = htmlspecialchars(strip_tags($this-&gt;firstname)); $this-&gt;lastname = htmlspecialchars(strip_tags($this-&gt;lastname)); $this-&gt;email = htmlspecialchars(strip_tags($this-&gt;email)); $this-&gt;contact_number = htmlspecialchars(strip_tags($this-&gt;contact_number)); $this-&gt;address = htmlspecialchars(strip_tags($this-&gt;address)); $this-&gt;password = htmlspecialchars(strip_tags($this-&gt;password)); $this-&gt;access_level = htmlspecialchars(strip_tags($this-&gt;access_level)); $this-&gt;access_code = htmlspecialchars(strip_tags($this-&gt;access_code)); $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status)); // bind the values $stmt-&gt;bindParam(':firstname', $this-&gt;firstname); $stmt-&gt;bindParam(':lastname', $this-&gt;lastname); $stmt-&gt;bindParam(':email', $this-&gt;email); $stmt-&gt;bindParam(':contact_number', $this-&gt;contact_number); $stmt-&gt;bindParam(':address', $this-&gt;address); // hash the password before saving to database $password_hash = password_hash($this-&gt;password, PASSWORD_BCRYPT); $stmt-&gt;bindParam(':password', $password_hash); $stmt-&gt;bindParam(':access_level', $this-&gt;access_level); $stmt-&gt;bindParam(':access_code', $this-&gt;access_code); $stmt-&gt;bindParam(':status', $this-&gt;status); $stmt-&gt;bindParam(':created', $this-&gt;created); // execute the query, also check if query was successful if ($stmt-&gt;execute()) { return true; } else { $this-&gt;showError($stmt); return false; } } public function showError($stmt) { echo "&lt;pre&gt;"; print_r($stmt-&gt;errorInfo()); echo "&lt;/pre&gt;"; } // read all user records function readAll($from_record_num, $records_per_page) { // query to read all user records, with limit clause for pagination $query = "SELECT id, firstname, lastname, email, contact_number, access_level, created FROM " . $this-&gt;table_name . " ORDER BY id DESC LIMIT ?, ?"; // prepare query statement $stmt = $this-&gt;conn-&gt;prepare($query); // bind limit clause variables $stmt-&gt;bindParam(1, $from_record_num, PDO::PARAM_INT); $stmt-&gt;bindParam(2, $records_per_page, PDO::PARAM_INT); // execute query $stmt-&gt;execute(); // return values return $stmt; } // used for paging users public function countAll() { // query to select all user records $query = "SELECT id FROM " . $this-&gt;table_name . ""; // prepare query statement $stmt = $this-&gt;conn-&gt;prepare($query); // execute query $stmt-&gt;execute(); // get number of rows $num = $stmt-&gt;rowCount(); // return row count return $num; } // used in email verification feature function updateStatusByAccessCode() { // update query $query = "UPDATE " . $this-&gt;table_name . " SET status = :status WHERE access_code = :access_code"; // prepare the query $stmt = $this-&gt;conn-&gt;prepare($query); // sanitize $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status)); $this-&gt;access_code = htmlspecialchars(strip_tags($this-&gt;access_code)); // bind the values from the form $stmt-&gt;bindParam(':status', $this-&gt;status); $stmt-&gt;bindParam(':access_code', $this-&gt;access_code); // execute the query if ($stmt-&gt;execute()) { return true; } return false; } // used in forgot password feature function updateAccessCode() { // update query $query = "UPDATE " . $this-&gt;table_name . " SET access_code = :access_code WHERE email = :email"; // prepare the query $stmt = $this-&gt;conn-&gt;prepare($query); // sanitize $this-&gt;access_code = htmlspecialchars(strip_tags($this-&gt;access_code)); $this-&gt;email = htmlspecialchars(strip_tags($this-&gt;email)); // bind the values from the form $stmt-&gt;bindParam(':access_code', $this-&gt;access_code); $stmt-&gt;bindParam(':email', $this-&gt;email); // execute the query if ($stmt-&gt;execute()) { return true; } return false; } // check if given access_code exist in the database function accessCodeExists() { // query to check if access_code exists $query = "SELECT id FROM " . $this-&gt;table_name . " WHERE access_code = ? LIMIT 0,1"; // prepare the query $stmt = $this-&gt;conn-&gt;prepare($query); // sanitize $this-&gt;access_code = htmlspecialchars(strip_tags($this-&gt;access_code)); // bind given access_code value $stmt-&gt;bindParam(1, $this-&gt;access_code); // execute the query $stmt-&gt;execute(); // get number of rows $num = $stmt-&gt;rowCount(); // if access_code exists if ($num&gt;0) { // return true because access_code exists in the database return true; } // return false if access_code does not exist in the database return false; } // used in forgot password feature function updatePassword() { // update query $query = "UPDATE " . $this-&gt;table_name . " SET password = :password WHERE access_code = :access_code"; // prepare the query $stmt = $this-&gt;conn-&gt;prepare($query); // sanitize $this-&gt;password = htmlspecialchars(strip_tags($this-&gt;password)); $this-&gt;access_code = htmlspecialchars(strip_tags($this-&gt;access_code)); // bind the values from the form $password_hash = password_hash($this-&gt;password, PASSWORD_BCRYPT); $stmt-&gt;bindParam(':password', $password_hash); $stmt-&gt;bindParam(':access_code', $this-&gt;access_code); // execute the query if ($stmt-&gt;execute()) { return true; } return false; } } ?&gt; </code></pre> <h3>utils.php</h3> <pre><code>&lt;?php class Utils { function getToken($length=32) { $token = ""; $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz"; $codeAlphabet.= "0123456789"; for ($i = 0;$i&lt;$length;$i++) { $token .= $codeAlphabet[$this-&gt;crypto_rand_secure(0, strlen($codeAlphabet))]; } return $token; } function crypto_rand_secure($min, $max) { $range = $max - $min; if ($range &lt; 0) { return $min; // not so random... } $log = log($range, 2); $bytes = (int) ($log / 8) + 1; // length in bytes $bits = (int) $log + 1; // length in bits $filter = (int) (1 &lt;&lt; $bits) - 1; // set all lower bits to 1 do { $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))); $rnd = $rnd &amp; $filter; // discard irrelevant bits } while ($rnd &gt;= $range); return $min + $rnd; } // send email using built in php mailer public function sendEmailViaPhpMail($send_to_email, $subject, $body) { $from_name = ""; $from_email = ""; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: {$from_name} &lt;{$from_email}&gt; \n"; if (mail($send_to_email, $subject, $body, $headers)) { return true; } else { return false; } } } ?&gt; </code></pre> <h3>core.php</h3> <pre><code>&lt;?php // show error reporting error_reporting(E_ALL); // start php session session_start(); // set your default time-zone date_default_timezone_set('Europe/London'); // home page url $home_url = "http://localhost/"; ?&gt; </code></pre> <h3>database.php</h3> <pre><code>&lt;?php // used to get mysql database connection class Database { // specify your own database credentials private $host = ""; private $db_name = ""; private $username = ""; private $password = ""; public $conn; // get the database connection public function getConnection() { $this-&gt;conn = null; try { $this-&gt;conn = new PDO("mysql:host=" . $this-&gt;host . ";dbname=" . $this-&gt;db_name, $this-&gt;username, $this-&gt;password); } catch (PDOException $exception) { echo "Connection error: " . $exception-&gt;getMessage(); } return $this-&gt;conn; } } ?&gt; </code></pre> <h3>admin/index.php</h3> <pre><code>&lt;?php // core configuration require_once "../config/core.php"; // check if logged in as administrator require_once "login_checker.php"; // header HTML require 'layout_head.php'; ?&gt; &lt;div class='col-md-12'&gt; &lt;p&gt;Hi, &lt;?php echo $_SESSION['firstname']; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php // include page footer HTML require_once 'layout_foot.php'; ?&gt; </code></pre> <h3>admin/login_checker.php</h3> <pre><code>&lt;?php // login checker for the 'Administrator' access level // if the session value is empty, the user has not yet logged in, redirect the user to the login page if (empty($_SESSION['logged_in'])) { header("Location: {$home_url}login.php?action=not_yet_logged_in"); } // if the access level detected was not 'Administrator', redirect the user to login page else if ($_SESSION['access_level']!="Administrator") { header("Location: {$home_url}login.php?action=not_admin"); } else { // no problem, stay on current page } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T15:54:14.280", "Id": "396729", "Score": "0", "body": "Where does $require_login variable come from? It doesn't seem to be defined anywhere" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T16:00:28.777"...
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T15:26:42.087", "Id": "205693", "Score": "2", "Tags": [ "php", "authentication", "pdo", "authorization" ], "Title": "PHP Login Checker Stage" }
205693
<p>On interview I was asked to write method with following contract:</p> <pre><code>boolean checkList(List&lt;Long&gt; list, long sum){...} </code></pre> <p>for example it has to return <strong>true</strong> for arguments:<br> (<code>{1,2,3,4,5,6}</code>, <code>9</code>) because 4+5 = 9</p> <p>and it have to return <strong>false</strong> for arguments: </p> <p>(<code>{0,10,30}</code>, <code>11</code>) because there are no combination of 2 elements with sum 11</p> <p>I suggested code like this:</p> <pre><code>boolean checkList(List&lt;Long&gt; list, long expectedSum) { if (list.size() &lt; 2) { return false; } for (int i = 0; i &lt; list.size() - 1; i++) { for (int k = i; k &lt; list.size(); k++) { if ((list.get(i) + list.get(k)) == expectedSum) { return true; } } } return false; } </code></pre> <p>But interviewer asked me to improve the solution. How?</p>
[]
[ { "body": "<p>Your solution is inefficient: for a list of length <em>n</em>, the worst-case running time is O(<em>n</em><sup>2</sup>), because you may need to test every possible pair of numbers.</p>\n\n<p>A better algorithm would be to sort the list first. (Maybe it's already sorted? You didn't specify, but ...
{ "AcceptedAnswerId": "205723", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T16:50:49.607", "Id": "205696", "Score": "1", "Tags": [ "java", "algorithm", "interview-questions", "k-sum" ], "Title": "Determine a list contains two elements with a given sum" }
205696
<p>In order to learn C++ I decided to code a Chip8 emulator following a tutorial. When I came across the idea of a flag register and decided it would be fun to implement in order to get familiar with bitwise operations. I'd like this review to center on what can be improved from the point of view of C++, but of course any other suggestions and improvements are welcome. </p> <pre><code>class FlagRegister { private: unsigned char state = 0x00; enum Flag: unsigned char { CF = 0x01, PF = 0x02, AF = 0x04, ZF = 0x08, TF = 0x10, IF = 0x20, DF = 0x40, OF = 0x80 }; bool checkFlag(Flag flagToCheck) { return (bool) ((this-&gt;state &gt;&gt; (flagToCheck - 1)) % 2); } void setFlag(Flag flagToSet) { this-&gt;state = this-&gt;state | flagToSet; } void unsetFlag(Flag flagToUnset) { this-&gt;state = (this-&gt;state &amp; (~flagToUnset)); } public: bool checkCF() { return this-&gt;checkFlag(CF); } void setCF() { this-&gt;setFlag(CF); } void unsetCF() { this-&gt;unsetFlag(CF); } // Idem for all other flags. }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T18:38:34.993", "Id": "396735", "Score": "0", "body": "Welcome to Code Review! It would be helpful to reviewers (and yourself) if you provided a short program demonstrating the class in use." } ]
[ { "body": "<p>I see some things that may help you improve your program.</p>\n\n<h2>Avoid writing <code>this</code></h2>\n\n<p>The overuse of <code>this</code> clutters the code and makes things harder to understand. For example, the current code contains this:</p>\n\n<pre><code>void setFlag(Flag flagToSet) {\n...
{ "AcceptedAnswerId": "205712", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T17:57:53.550", "Id": "205699", "Score": "2", "Tags": [ "c++", "beginner", "bitwise", "enum", "virtual-machine" ], "Title": "C++ class for a flag register in a Chip8 emulator" }
205699
<p>As an academic exercise, I decided to implement a continuous shuffler, as seen on casino blackjack tables. It operates by storing a "linked loop" (a linked list with the last element linked to the first) and walking a random number of steps around the loop when an item is removed.</p> <pre><code>public abstract class BaseShuffler&lt;T&gt; { ///&lt;summary&gt;Returns a random int in the range [0,max)&lt;/summary&gt; protected abstract int GetNextRandom(int max); private Node _current = null; private int _count = 0; public int Count { get { return _count; } } public void Add(T value) { var newNode = new Node(value); if (_count &lt;= 0) { //form the loop _current = newNode; _current.Next = _current; } else { //insert into loop after current node var next = _current.Next; _current.Next = newNode; newNode.Next = next; } _count++; } public T Pop() { if (_count &lt;= 0) throw new InvalidOperationException("Shuffler is empty"); //walk a random number of steps round the loop for (int i = 0; i &lt; GetNextRandom(_count); i++) { _current = _current.Next; } //remove next node from loop var next = _current.Next; var nextnext = _current.Next.Next; _current.Next = nextnext; _count--; if (_count &lt;= 0) { //remove circular reference so we don't break refcounting for GC _current.Next = null; _current = null; } return next.Value; } private class Node { public Node Next { get; set; } public T Value =&gt; _value; private readonly T _value; public Node(T value) { _value = value; } } public bool Any() { return _count &gt; 0; } } public sealed class Shuffler&lt;T&gt; : BaseShuffler&lt;T&gt; { private Random _random; public Shuffler() { _random = new Random(); } public Shuffler(int seed) { _random = new Random(seed); } protected override int GetNextRandom(int max) { return _random.Next(max); } } </code></pre> <p>However, it appears to have a bias towards the returning an item near the end of the list as its first item: using the following test code</p> <pre><code>void Main() { var shuffler = new Shuffler&lt;(Rank rank, Suit suit)&gt;(); foreach (Suit suit in Enum.GetValues(typeof(Suit))) foreach (Rank rank in Enum.GetValues(typeof(Rank))) { shuffler.Add((rank, suit)); } while (shuffler.Any()) { var card = shuffler.Pop(); Console.Out.WriteLine($"{card.rank} of {card.suit}"); } } enum Suit { Clubs, Diamonds, Hearts, Spades } enum Rank { Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace } </code></pre> <p>I get a Spade most commonly as the first card, occasionally a Heart, and Clubs or Diamonds seemingly never. Is there a way to remove the bias from my algorithm without entirely removing the limit on the random number generator, which could then produce a large number of steps to take, slowing the program down? If I remove the limit, my test case changes from sub-millisecond runtime to around 0.15 seconds - but without the bias (I'm running in LinqPad as a test bed).</p>
[]
[ { "body": "<p>As for the immediate problem, changing the initial start position, after all the cards have been added, to a random position should remove the bias:</p>\n\n<pre><code>public void SetStart()\n{\n int limit = GetNextRandom(_count)\n for (int i = 0; i &lt; limit; i++)\n {\n _current =...
{ "AcceptedAnswerId": "205754", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T18:31:06.657", "Id": "205701", "Score": "2", "Tags": [ "c#", "playing-cards", "shuffle" ], "Title": "Continuous Shuffler with \"linked loop\"" }
205701
<p>This is my attempt at implementing a <a href="https://en.wikipedia.org/wiki/Binary_heap" rel="nofollow noreferrer">Binary heap</a>. I made an abstract base class <code>Heap</code> with an abstract property controlling whether it is a min-heap or a max-heap. </p> <p>One thing I've been struggling with was which <code>collections.generic</code> interfaces to apply to the class. Enumerating the heap only makes a bit of sense. At the same time, it is a collection, but I'm not sure if all the interface methods really make sense for a Heap. So any pointers for that would be welcome.</p> <h2>Abstract <code>Heap&lt;T&gt;</code></h2> <pre><code> public abstract class Heap&lt;T&gt; : IEnumerable&lt;T&gt;, ICollection&lt;T&gt; where T : IComparable { private T[] innerT; private int capacity = 1; private int numberOfLevels = 1; public int Count { get; private set; } = 0; public bool IsReadOnly =&gt; false; protected abstract bool CloserToRoot(int comparison); public Heap() { innerT = new T[capacity]; } public Heap(int capacity) { innerT = new T[capacity]; this.capacity = capacity; this.numberOfLevels = CapacityToLevels(capacity); } public Heap(IEnumerable&lt;T&gt; sequence) { if (sequence == null) { throw new ArgumentNullException(nameof(sequence)); } foreach (var item in sequence) { Add(item); } } public void Add(T item) { Count++; if (Count == capacity) { Resize(); } innerT[Count - 1] = item; UpHeap(); } private int Find(T item) { return FindInternal(item, 0); } private int FindInternal(T item, int index) { if (index &gt;= Count) { return -1; // end of the heap. } var comp = innerT[index].CompareTo(item); if (comp == 0) { // Found it! return index; } else if (CloserToRoot(comp)) { // Still possible to be lower. var rightChild = IndexToRightChildNode(index); var leftChild = rightChild - 1; var rightResult = FindInternal(item, rightChild); var leftResult = FindInternal(item, leftChild); if (rightResult &gt;= 0) { return rightResult; } if (leftResult &gt;= 0) { return leftResult; } } return -1; // Nope :( Either both children were -1 or this index has a value lower than item; } private void UpHeap() { var currentNode = Count - 1; var parentNode = IndexToParentNode(currentNode); while (currentNode != 0 &amp;&amp; CloserToRoot(innerT[currentNode].CompareTo(innerT[parentNode]))) { Swap(currentNode, parentNode); currentNode = parentNode; parentNode = IndexToParentNode(currentNode); } } private void DownHeap(int startingIndex) { int currentIndex; var largestIndex = startingIndex; do { currentIndex = largestIndex; var rightChild = IndexToRightChildNode(currentIndex); var leftChild = rightChild - 1; if (leftChild &lt; Count &amp;&amp; CloserToRoot(innerT[leftChild].CompareTo(innerT[largestIndex]))) { largestIndex = leftChild; } if (rightChild &lt; Count &amp;&amp; CloserToRoot(innerT[rightChild].CompareTo(innerT[largestIndex]))) { largestIndex = rightChild; } Swap(largestIndex, currentIndex); } while (largestIndex != currentIndex); } private void Swap(int a, int b) { var placeholder = innerT[a]; innerT[a] = innerT[b]; innerT[b] = placeholder; } private static int CapacityToLevels(int capacity) { var Log2 = Math.Log(2); return (int)Math.Ceiling(Math.Log(capacity + 1) / Log2); } private static int IndexToRightChildNode(int index) { return 2 * index + 2; } private static int IndexToParentNode(int index) { return (index - 1) / 2; } private void Resize() { capacity = capacity &lt;&lt; 1 | 1; numberOfLevels++; Array.Resize(ref innerT, capacity); } public IEnumerator&lt;T&gt; GetEnumerator() { return (IEnumerator&lt;T&gt;)innerT.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return innerT.GetEnumerator(); } public void Clear() { capacity = 1; numberOfLevels = 1; innerT = new T[capacity]; } public bool Contains(T item) { return Find(item) != -1; } public void CopyTo(T[] array, int arrayIndex) { if (arrayIndex &lt; 0 || arrayIndex &gt;= Count) { throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } innerT.CopyTo(array, arrayIndex); } public bool Remove(T item) { var index = Find(item); if (index == -1) { return false; } innerT[index] = default(T); Swap(index, Count - 1); Count--; DownHeap(index); return true; } } </code></pre> <h2>MaxHeap</h2> <pre><code> public class MaxHeap&lt;T&gt; : Heap&lt;T&gt; where T : IComparable { public MaxHeap() { } public MaxHeap(int capacity) : base(capacity) { } public MaxHeap(IEnumerable&lt;T&gt; sequence) : base(sequence) { } protected override bool CloserToRoot(int comparison) =&gt; comparison &gt; 0; } </code></pre> <h2>MinHeap</h2> <pre><code> public class MinHeap&lt;T&gt; : Heap&lt;T&gt; where T : IComparable { public MinHeap() { } public MinHeap(int capacity) : base(capacity) { } public MinHeap(IEnumerable&lt;T&gt; sequence) : base(sequence) { } protected override bool CloserToRoot(int comparison) =&gt; comparison &lt; 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T13:47:02.300", "Id": "397157", "Score": "2", "body": "[`CompareTo`](https://docs.microsoft.com/en-us/dotnet/api/system.icomparable.compareto) is not guaranteed to return -1..+1, only the sign (or zero) is relevant." }, { "Co...
[ { "body": "<p>I don't see much to improve from algorithmic point of view. So I will focus on Object Oriented design.</p>\n\n<ol>\n<li><p>How about doing it similarly to Sort method? I mean instead of making abstract method, try just injecting Comparator into generic Heap implementation.</p></li>\n<li><p>People ...
{ "AcceptedAnswerId": "206147", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T19:06:29.203", "Id": "205702", "Score": "6", "Tags": [ "c#", "heap" ], "Title": "Binary heap implementation with a generic base class" }
205702
<p>I was bored, so I decided to write a very basic HTTP Request/Response parser in C++.</p> <p>Some Notes:</p> <ul> <li>This isn't meant to be a complete implementation of the HTTP protocol</li> <li>This isn't meant to be the fastest/smallest/best library out there for this kind of thing.</li> <li>It's a lot of code, I don't expect anyone to read all of it, but any advice regarding "modern C++" (see below) is welcome.</li> </ul> <p>I'm mainly looking for comments about my "moden C++" skills, since I'm always trying to improve these.</p> <p>One thing I would love though, are tips for places where I could use some more "modern" features (think things like <code>std::optional, std::variant, ...</code> (These are all things I've heard of and used on very rare occasions, but I really want to see if I can use them more often))</p> <p>Since I did this out of pure boredom, everything is in a single file, I'll split it up in a few sections for this post though:</p> <p>(all code except main() is in the HTTP namespace, I won't include it in every bit of code)</p> <p>HTTP Namespace member (for convenience):</p> <pre><code>namespace HTTP { constexpr static std::string_view LINE_END = "\r\n"; ... } </code></pre> <p>HTTP Method Enum:</p> <pre><code>enum class Method { GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH }; std::string to_string(Method method) { switch(method) { case Method::GET: return "GET"; case Method::HEAD: return "HEAD"; case Method::POST: return "POST"; case Method::PUT: return "PUT"; case Method::DELETE: return "DELETE"; case Method::TRACE: return "TRACE"; case Method::OPTIONS: return "OPTIONS"; case Method::CONNECT: return "CONNECT"; case Method::PATCH: return "PATCH"; } } Method method_from_string (const std::string&amp; method) noexcept { if (method == to_string(Method::GET)) { return Method::GET; } else if (method == to_string(Method::HEAD)) { return Method::HEAD; } else if (method == to_string(Method::POST)) { return Method::POST; } else if (method == to_string(Method::PUT)) { return Method::PUT; } else if (method == to_string(Method::DELETE)) { return Method::DELETE; } else if (method == to_string(Method::TRACE)) { return Method::TRACE; } else if (method == to_string(Method::OPTIONS)) { return Method::OPTIONS; } else if (method == to_string(Method::CONNECT)) { return Method::CONNECT; } else if (method == to_string(Method::PATCH)) { return Method::PATCH; } } </code></pre> <p>Enum to represent HTTP Version:</p> <pre><code>enum class Version { HTTP_1_0, HTTP_1_1, HTTP_2_0 }; std::string to_string(Version version) { switch(version) { case Version::HTTP_1_0: return "HTTP/1.0"; case Version::HTTP_1_1: return "HTTP/1.1"; case Version::HTTP_2_0: return "HTTP/2.0"; } } Version version_from_string (const std::string&amp; version) noexcept { if (version == to_string(Version::HTTP_1_0)) { return Version::HTTP_1_0; } else if (version == to_string(Version::HTTP_1_1)) { return Version::HTTP_1_1; } else if (version == to_string(Version::HTTP_2_0)) { return Version::HTTP_2_0; } } </code></pre> <p>HTTP Header Class:</p> <pre><code>class Header { private: std::string key; std::string value; public: Header (const std::string&amp; key, const std::string&amp; value) noexcept: key(key), value(value) { } void set_value (const std::string&amp; value) noexcept { this-&gt;value = value; } const std::string&amp; get_key() const noexcept { return this-&gt;key; } std::string serialize() const noexcept { std::string header; header += this-&gt;key; header += ": "; header += this-&gt;value; header += LINE_END; return header; } static Header deserialize(const std::string&amp; header) { std::vector&lt;std::string&gt; segments = split(header, " "); const std::string key = segments[0].substr(0, segments[0].size() - 1); segments.erase(segments.begin()); const std::string value = concat(segments, " "); return Header(key, value); } }; </code></pre> <p>HTTP Request Class:</p> <pre><code>class Request { private: Version version; Method method; std::string resource; std::map&lt;std::string, Header&gt; headers; public: Request(Method method, const std::string&amp; resource, const std::map&lt;std::string, Header&gt;&amp; headers, Version version = Version::HTTP_1_1) noexcept: version(version), method(method), resource(resource), headers(headers) { } std::string serialize() const noexcept { std::string request; request += to_string(this-&gt;method); request += " "; request += this-&gt;resource; request += " "; request += to_string(this-&gt;version); request += LINE_END; for (const std::pair&lt;const std::string, Header&gt;&amp; header : this-&gt;headers) { request += header.second.serialize(); } request += LINE_END; return request; } static Request deserialize(const std::string&amp; request) { std::vector&lt;std::string&gt; lines = split(request, std::string(LINE_END)); if (lines.size() &lt; 1) { throw std::runtime_error("HTTP Request ('" + std::string(request) + "') consisted of " + std::to_string(lines.size()) + " lines, should be &gt;= 1."); } std::vector&lt;std::string&gt; segments = split(lines[0], " "); if (segments.size() != 3) { throw std::runtime_error("First line of HTTP request ('" + std::string(request) + "') consisted of " + std::to_string(segments.size()) + " space separated segments, should be 3."); } const Method method = method_from_string(segments[0]); const std::string resource = segments[1]; const Version version = version_from_string(segments[2]); std::map&lt;std::string, Header&gt; headers; for (std::size_t i = 1; i &lt; lines.size(); i++) { if (lines[i].size() &gt; 0) { const Header header = Header::deserialize(lines[i]); headers.insert(std::make_pair(header.get_key(), header)); } } return Request(method, resource, headers, version); } }; </code></pre> <p>HTTP Response class:</p> <pre><code>class Response { private: int responseCode; Version version; std::map&lt;std::string, Header&gt; headers; std::string body; public: constexpr static int OK = 200; constexpr static int CREATED = 201; constexpr static int ACCEPTED = 202; constexpr static int NO_CONTENT = 203; constexpr static int BAD_REQUEST = 400; constexpr static int FORBIDDEN = 403; constexpr static int NOT_FOUND = 404; constexpr static int REQUEST_TIMEOUT = 408; constexpr static int INTERNAL_SERVER_ERROR = 500; constexpr static int BAD_GATEWAY = 502; constexpr static int SERVICE_UNAVAILABLE = 503; Response (int responseCode, Version version, const std::map&lt;std::string, Header&gt;&amp; headers, const std::string&amp; body) noexcept: responseCode(responseCode), headers(headers), body(body) { } int get_response_code() const noexcept { return this-&gt;responseCode; } const std::string&amp; get_body() const noexcept { return this-&gt;body; } const std::map&lt;std::string, Header&gt; get_headers() const noexcept { return this-&gt;headers; } static Response deserialize(const std::string&amp; response) noexcept { std::vector&lt;std::string&gt; segments = split(response, std::string(LINE_END) + std::string(LINE_END)); std::string headerSegment = segments[0]; segments.erase(segments.begin()); std::string body = concat(segments); std::vector&lt;std::string&gt; headerLines = split(headerSegment, std::string(LINE_END)); const std::string&amp; responseCodeLine = headerLines[0]; std::vector&lt;std::string&gt; responseCodeSegments = split(responseCodeLine, " "); Version version = version_from_string(responseCodeSegments[0]); int responseCode = std::stoi(responseCodeSegments[1]); headerLines.erase(headerLines.begin()); std::map&lt;std::string, Header&gt; headers; for (const std::string&amp; line : headerLines) { const Header header = Header::deserialize(line); headers.insert(std::make_pair(header.get_key(), header)); } return Response(responseCode, version, headers, body); } }; </code></pre> <p>The code uses 2 string manipulation methods split() and concat(), they look like this:</p> <pre><code>std::vector&lt;std::string&gt; split(const std::string&amp; str, const std::string&amp; delim) noexcept { std::vector&lt;std::string&gt; tokens = std::vector&lt;std::string&gt;(); std::string strCopy = str; std::size_t pos = 0; std::string token; while ((pos = strCopy.find(delim)) != std::string::npos) { token = strCopy.substr(0, pos); strCopy.erase(0, pos + delim.length()); tokens.push_back(token); } if (strCopy.length() &gt; 0) { tokens.push_back(strCopy); } return tokens; } std::string concat(const std::vector&lt;std::string&gt;&amp; strings, const std::string&amp; delim = "") noexcept { std::string result; for (std::size_t i = 0; i &lt; strings.size(); i++) { result += strings[i]; if ((i + 1) != strings.size()) { result += delim; } } return result; } </code></pre> <p>And here's a main to test it all:</p> <pre><code>int main (int argc, char* argv[]) { if (argc != 4) { std::cout &lt;&lt; "USAGE: ./http.elf [HOST-NAME] [RESOURCE] [OUTPUT-FILE]" &lt;&lt; std::endl; return -1; } std::string host (argv[1]); std::string resource (argv[2]); std::string outputFile (argv[3]); HTTP::Header hostHdr = HTTP::Header("Host", host); HTTP::Header dntHdr = HTTP::Header("DNT", "1"); std::map&lt;std::string, HTTP::Header&gt; headers; headers.insert(std::make_pair(hostHdr.get_key(), hostHdr)); headers.insert(std::make_pair(dntHdr.get_key(), dntHdr)); HTTP::Request request (HTTP::Method::GET, resource, headers); std::string httpRequest = request.serialize(); int socketFileDesc = Sockets::C::Client::connect(std::string(host), 80); int error = send(socketFileDesc, httpRequest.c_str(), httpRequest.size(), 0); if (error == -1) { throw std::runtime_error("Failed to send data to " + std::string(host) + ":80."); } char buffer [8192]; int numBytes = recv(socketFileDesc, buffer, 8192, 0); if (numBytes == -1) { throw std::runtime_error("Failed to receive data from " + std::string(host) + ":80."); } close(socketFileDesc); HTTP::Response response = HTTP::Response::deserialize(std::string(buffer)); std::ofstream filestream (outputFile); filestream &lt;&lt; response.get_body(); filestream.close(); return 0; } </code></pre> <p>The compiled program needs to be run like this: <code>http.elf example.net / index.html</code></p> <p>This should normally save the <code>/</code> page from <code>example.net</code> to <code>index.html</code></p> <p>I'm aware that the way I'm receiving the response isn't the best way (The 8192-character buffer might be a bit small to receive complex websites). I'll probably start working on a wrapper class for TCP sockets that I can use until C++20 (Which will hopefully include the results of the networking TS) which should handle this sort of thing much better.</p> <p>The connect() function was written using Beej's guide to network programming, this code is out of the scope of the review, should you wish to test this code, you can find the complete file here: <a href="https://gist.github.com/ThomasCassimon/304122739a3c24cd65319a489f1e88a8" rel="noreferrer">https://gist.github.com/ThomasCassimon/304122739a3c24cd65319a489f1e88a8</a></p> <p>It compiles on my machine (x86_64 Linux, using clang 7) with the following command line: <code>clang++ -std=c++17 http.cpp -o http.elf</code></p> <p>I've tested this code by sending requests to my Raspberry Pi which is running an Apache Webserver with a very basic 'hello-world'-esque index page.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T19:48:23.700", "Id": "396747", "Score": "0", "body": "What else is in your `HTTP` namespace?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T19:54:59.020", "Id": "396752", "Score": "0", "b...
[ { "body": "<h2>General Comments:</h2>\n\n<p>This does not compile for me:</p>\n\n<pre><code>if (method == to_string(Method::GET))\n ^^^^^^^^^\n</code></pre>\n\n<p>Is this supposed to be <code>std::to_string</code>? Or a home written method.</p>\n\n<p>Either way that seems like a very inefficient me...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-16T19:19:37.950", "Id": "205704", "Score": "8", "Tags": [ "c++", "http" ], "Title": "Very basic C++ HTTP Parser" }
205704
<p>I made this Python code that prints a sample string and ensures that the input of the user agrees with the sample, and then do an action with this inputted string, in this case a multiplication table.</p> <p>I've made this code to practice some Python concepts, and I do not know if I did everything correctly and <strong>"in a pythonic way"</strong>. I'd like to know if there's anything in this code that can be improved and things I could have done otherwise.</p> <pre><code>import re from time import sleep class StringController(object): def __init__(self, *args, **kwargs): self.regexp = re.compile('(?i)^show me the multiplication table of [0-9]* from [0-9]* to [0-9]*$') def __enter__(self, *args, **kwargs): print('Example string: show me the multiplication table of 10 from 5 to 20') self.inputedstring = input('Input: ') print('-'*50) sleep(1) return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: print('{}: {}'.format(exc_type.__name__, 'You must use the provided string')) else: print('-'*50) del self.inputedstring if __name__ == '__main__': myobject = StringController() while True: try: with myobject as strcon: multiplication_table = list(range(int(myobject.inputedstring.split(' ')[8]), int(myobject.inputedstring.split(' ')[10])+1)) results = list(map(lambda x : x*int(myobject.inputedstring.split(' ')[6]), multiplication_table)) if myobject.regexp.match(myobject.inputedstring): print('\n'.join(str(results) for results in results)) else: raise UserWarning('You must use the provided string') except (ValueError, IndexError) as WrongInput: print("\n") del WrongInput finally: del strcon </code></pre> <p>Output: </p> <p><a href="https://i.stack.imgur.com/Z90Ly.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z90Ly.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T02:53:33.733", "Id": "396903", "Score": "0", "body": "There's no need for `<pre>` tags; you should just use indentation. I fixed the `&quot`s as well." } ]
[ { "body": "<h1>Bug</h1>\n\n<p>The regex is flawed, consider this:</p>\n\n<pre><code>&gt;&gt;&gt; print(re.match(pat, 'show me the multiplication table of from to '))\n&gt;&gt;&gt; &lt;re.Match object; span=(0, 46), match='show me the multiplication table of from to '&gt;\n</code></pre>\n\n<p>That is because...
{ "AcceptedAnswerId": "205912", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T00:59:00.257", "Id": "205716", "Score": "0", "Tags": [ "python", "object-oriented", "python-3.x" ], "Title": "Control the input of the user according to a sample string and get some info from it" }
205716
<p>I'm creating a window class in C++ to provide a bit of abstraction for a GLFW window.</p> <p><strong>window.h</strong></p> <pre><code>#pragma once #define GLFW_INCLUDE_VULKAN #include &lt;GLFW/glfw3.h&gt; class Window { GLFWwindow* m_Window; GLFWmonitor* m_Monitor; const char* m_Title; GLFWimage m_Icon[1]; int m_Width, m_Height; int m_PosX, m_PosY; bool m_Fullscreen; public: Window(int width, int height, const char* title, const char* iconPath); ~Window(); GLFWwindow* getWindow(); const char** getRequiredExtensions(); private: void queryVulkanSupport(); void initGLFW(); void createWindow(); void setIcon(const char* path); void center(); void setFullscreen(); void setWindowSizeCallback(); static void static_WindowSizeCallback(GLFWwindow* window, int width, int height); void windowSizeCallback(int width, int height); void setKeyCallback(); static void static_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); void keyCallback(int key, int scancode, int action, int mods); }; </code></pre> <p><strong>window.cpp</strong></p> <pre><code>#include "window.h" #define STB_IMAGE_IMPLEMENTATION #include &lt;stb/stb_image.h&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; Window::Window(int width, int height, const char* title, const char* iconPath) : m_Fullscreen(false), m_Width(width), m_Height(height), m_Title(title) { initGLFW(); queryVulkanSupport(); m_Monitor = glfwGetPrimaryMonitor(); createWindow(); setIcon(iconPath); setWindowSizeCallback(); setKeyCallback(); } Window::~Window() { glfwDestroyWindow(m_Window); glfwTerminate(); } GLFWwindow* Window::getWindow() { return m_Window; } const char** Window::getRequiredExtensions() { uint32_t count; const char** extensions = glfwGetRequiredInstanceExtensions(&amp;count); return extensions; } void Window::queryVulkanSupport() { if (!glfwVulkanSupported()) { throw std::runtime_error("Vulkan not supported!"); } } void Window::initGLFW() { if (!glfwInit()) { throw std::runtime_error("Failed to initialize GLFW!"); } } void Window::createWindow() { glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, nullptr, nullptr); if (!m_Window) { throw std::runtime_error("Could not create GLFW window!"); } glfwSetWindowUserPointer(m_Window, this); center(); } void Window::setIcon(const char* path) { m_Icon[0].pixels = stbi_load(path, &amp;m_Icon[0].width, &amp;m_Icon[0].height, 0, 4); if (m_Icon[0].pixels) glfwSetWindowIcon(m_Window, 1, m_Icon); } void Window::center() { const GLFWvidmode* vidMode = glfwGetVideoMode(m_Monitor); glfwSetWindowPos(m_Window, (vidMode-&gt;width - m_Width) / 2, (vidMode-&gt;height - m_Height) / 2); } void Window::setFullscreen() { if (!m_Fullscreen) { const GLFWvidmode* vidMode = glfwGetVideoMode(m_Monitor); glfwGetWindowPos(m_Window, &amp;m_PosX, &amp;m_PosY); glfwGetWindowSize(m_Window, &amp;m_Width, &amp;m_Height); glfwSetWindowMonitor(m_Window, m_Monitor, 0, 0, vidMode-&gt;width, vidMode-&gt;height, vidMode-&gt;refreshRate); glfwSetWindowSize(m_Window, vidMode-&gt;width, vidMode-&gt;height); m_Fullscreen = !m_Fullscreen; } else { glfwSetWindowMonitor(m_Window, nullptr, m_PosX, m_PosY, m_Width, m_Height, 0); glfwSetWindowSize(m_Window, m_Width, m_Height); m_Fullscreen = !m_Fullscreen; } } void Window::setWindowSizeCallback() { glfwSetWindowSizeCallback(m_Window, static_WindowSizeCallback); } void Window::static_WindowSizeCallback(GLFWwindow* window, int width, int height) { Window* actualWindow = (Window*) glfwGetWindowUserPointer(window); actualWindow-&gt;windowSizeCallback(width, height); } void Window::windowSizeCallback(int width, int height) { glfwSetWindowSize(m_Window, width, height); } void Window::setKeyCallback() { glfwSetKeyCallback(m_Window, static_KeyCallback); } void Window::static_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { Window* actualWindow = (Window*) glfwGetWindowUserPointer(window); actualWindow-&gt;keyCallback(key, scancode, action, mods); } void Window::keyCallback(int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE &amp;&amp; action == GLFW_PRESS) glfwSetWindowShouldClose(m_Window, true); if (key == GLFW_KEY_F11 &amp;&amp; action == GLFW_RELEASE) setFullscreen(); } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "window.h" int main() { Window window(600, 300, "Vulkan engine!", "include/Ressources/VulkanIcon.png"); while (!glfwWindowShouldClose(window.getWindow())) { glfwPollEvents(); } } </code></pre> <p>The code works as intended. I'm really new to c++ though and I assume there are tons I could improve about this class, not just in terms of speed, but also structure.</p> <p>I'm especially concerned with the way I get around the fact that GLFW callbacks are static. In my callbacks I want to access methods in my class and so I create a pointer to the actual 'window user' using glfwGetWindowUserPointer, to access the actual class methods an member variables.</p> <p>Still I'm just looking for any thoughts on how to improve this code.</p> <p>Links to <a href="http://www.glfw.org/" rel="nofollow noreferrer">GLFW</a> and <a href="https://github.com/nothings/stb" rel="nofollow noreferrer">STB</a>.</p>
[]
[ { "body": "<h2>Use default member initialization where appropriate</h2>\n\n<p>You always want to set <code>m_Fullscreen</code> to <code>false</code> when creating a new <code>Window</code>. Instead of setting this variable in the constructor, just initialize it where you declare it:</p>\n\n<pre><code>class Wind...
{ "AcceptedAnswerId": "205895", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T01:57:21.367", "Id": "205717", "Score": "3", "Tags": [ "c++", "beginner", "object-oriented", "pointers", "callback" ], "Title": "C++ wrapper for GLFW window object" }
205717
<p>I am relatively new to C# and would like to see if what I have been using for my exception handling, message and logging is along industry standards. I have created a simple class for the Error Handler and for the logging I use <a href="https://logging.apache.org/log4net/" rel="nofollow noreferrer">Log4Net</a>. After reading <a href="https://rads.stackoverflow.com/amzn/click/0132350882" rel="nofollow noreferrer">Clean Code</a>, I was thinking about separating <code>DisplayMessage</code> into 2 different procedures for the message and logging. The log file is usually written to a file server so multiple users can access it; I have enabled <code>MinimalLock</code> for this purpose. For my example, I have changed the log path to <code>C:\Temp\</code>. An example of a project I use the Error Handler class and logging in is on <a href="https://github.com/Office-projects/Script-Help" rel="nofollow noreferrer">GitHub</a>. For reference, I am using Visual Studio 2017 Community.</p> <hr> <h3>ErrorHandler.cs</h3> <pre><code>using System; using System.Windows.Forms; using log4net; [assembly: log4net.Config.XmlConfigurator(Watch = true)] /// &lt;summary&gt; /// Used to handle exceptions /// &lt;/summary&gt; public class ErrorHandler { private static readonly ILog log = LogManager.GetLogger(typeof(ErrorHandler)); /// &lt;summary&gt; /// Used to produce an error message and create a log record /// &lt;example&gt; /// &lt;code lang="C#"&gt; /// ErrorHandler.DisplayMessage(ex); /// &lt;/code&gt; /// &lt;/example&gt; /// &lt;/summary&gt; /// &lt;param name="ex"&gt;Represents errors that occur during application execution.&lt;/param&gt; /// &lt;remarks&gt;&lt;/remarks&gt; public static void DisplayMessage(Exception ex) { System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1); System.Reflection.MethodBase caller = sf.GetMethod(); string currentProcedure = (caller.Name).Trim(); string errorMessageDescription = ex.ToString(); errorMessageDescription = System.Text.RegularExpressions.Regex.Replace(errorMessageDescription, @"\r\n+", " "); //the carriage returns were messing up my log file string msg = "Contact your system administrator. A record has been created in the log file." + Environment.NewLine; msg += "Procedure: " + currentProcedure + Environment.NewLine; msg += "Description: " + ex.ToString() + Environment.NewLine; log.Error("[PROCEDURE]=|" + currentProcedure + "|[USER NAME]=|" + Environment.UserName + "|[MACHINE NAME]=|" + Environment.MachineName + "|[DESCRIPTION]=|" + errorMessageDescription); MessageBox.Show(msg, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } </code></pre> <h3>Usage Example:</h3> <pre><code>/// &lt;summary&gt; /// Return the count of items in a delimited list /// &lt;/summary&gt; /// &lt;param name="valueList"&gt;Represents the list of values in a string &lt;/param&gt; /// &lt;param name="delimiter"&gt;Represents the list delimiter &lt;/param&gt; /// &lt;returns&gt;the number of values in a delimited string&lt;/returns&gt; public int GetListItemCount(string valueList, string delimiter) { try { string[] comboList = valueList.Split((delimiter).ToCharArray()); return comboList.GetUpperBound(0) + 1; } catch (Exception ex) { ErrorHandler.DisplayMessage(ex); return 0; } } </code></pre> <hr> <h3>Log4Net</h3> <p><a href="https://i.stack.imgur.com/MwCFF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MwCFF.png" alt="screenshot"></a></p> <h3>app.config</h3> <pre><code>&lt;log4net&gt; &lt;appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline"/&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name="FileAppender" type="log4net.Appender.FileAppender"&gt; &lt;file value="C:\Temp\MyLogFile.log"/&gt; &lt;appendToFile value="true"/&gt; &lt;lockingModel type="log4net.Appender.FileAppender+MinimalLock"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date|%-5level|%message%newline"/&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;root&gt; &lt;level value="ALL"/&gt; &lt;appender-ref ref="FileAppender"/&gt; &lt;/root&gt; &lt;/log4net&gt; </code></pre>
[]
[ { "body": "<p>I'm not familiar with log4net, so I will focus on the code itself.</p>\n\n<p>Here is a list of what could be improved:</p>\n\n<ul>\n<li>--- Style ---</li>\n<li><code>ErrorHandler</code> should be a <code>static</code> class to prevent <code>new</code>ing up an instance of it</li>\n<li>Lack of <cod...
{ "AcceptedAnswerId": "205863", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T04:14:14.700", "Id": "205724", "Score": "1", "Tags": [ "c#", "beginner", "error-handling", "logging" ], "Title": "Error-Handling Class and Logging" }
205724
<p>I wrote a code like below - It is <code>nuxt.js</code>, which is one of the Vue frameworks. This code will be expected to</p> <ul> <li>When change event triggered, update <code>data</code> value. There would be some logic to alter passed data</li> <li>At the same time, it connected with <code>data</code> value to apply input box changing</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>&lt;template&gt; &lt;div&gt; &lt;!-- I got question here --&gt; &lt;input type="text" ref="receiver" @change="applyData('receiver')" v-model="deliveryInfo.receiver" /&gt; &lt;button type="button" @click="test"&gt;TEST&lt;/button&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { data: function () { return { deliveryInfo: { receiver: '' } } }, methods: { applyData: function (refName) { let ref = this.$refs[refName]; if (ref) { let temp = {}; temp[refName] = ref.value; this.applyAddress(temp); } else { console.log("There is no " + refName + " in this.$refs"); } }, applyAddress: function (options) { this.deliveryInfo = Object.assign({}, this.deliveryInfo, options); this.$emit('applyChildData', this.deliveryInfo); }, test: function () { console.log('set John Doe'); this.deliveryInfo = Object.assign({}, this.deliveryInfo, {receiver: 'John Doe'}); console.log('After change ', this.deliveryInfo); // It triggers applyData method and change input element value // But when I remove v-model in input value, it is not working } } } &lt;/script&gt;</code></pre> </div> </div> </p> <p>And it works as expected.</p> <p>However, using <code>v-model</code> and <code>@change</code> at the same tag looks weird to me since both of tag manipulates the connected value(in this case, it would be <code>deliveryInfo.receiver</code>)</p> <p>Is this code OK to use in production project? Thanks!</p> <p>FYI, in my real case, it applied to a phone number. I want to show a phone number without dashes in a browser, but data should be saved with dashes.</p> <p>So when people type in the input, <code>@change</code> alter data to insert dashes. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T04:48:41.810", "Id": "396776", "Score": "0", "body": "The point is `@change` and `v-model` at the same time is OK or not. I comment this since it seems the point of the post is not clear enough" } ]
[ { "body": "<h2>Responding to Your question</h2>\n\n<p>This is good use of <a href=\"https://vuejs.org/v2/api/#ref\" rel=\"nofollow noreferrer\"><code>ref</code></a> and <code>Object.assign()</code> but normally this would be a good place to use a <a href=\"https://vuejs.org/v2/guide/computed.html#Watchers\" rel...
{ "AcceptedAnswerId": "205759", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T04:46:25.393", "Id": "205725", "Score": "1", "Tags": [ "javascript", "ecmascript-6", "vue.js" ], "Title": "duplicated operator(or attribute) on the same input control - v-model and @change" }
205725
<p>I started out creating a simple game in an Object Oriented way to practice. </p> <p>The rules are pretty simple</p> <ul> <li>There are two players </li> <li>You let one player choose if they want Heads or Tails.</li> <li>You assign the leftover option to the other player.</li> <li>You simulate a coin flip and say who won that game.</li> </ul> <p>More than the logic, naming conventions etc. I was looking at the most object-oriented way of structuring code to implement this from this exercise. </p> <p>I created three classes for this, the <code>Player</code>, <code>Coin</code> and <code>CoinGame</code> and an <code>enum</code> as well. </p> <p>The Player Class</p> <pre><code>enum CoinOptions { Heads, Tails } internal class Player { public string playerName { get; set; } public CoinOptions coinOption { get; set; } public Player(string name) { playerName = name; } public CoinOptions chooseCoinOption() { //Simulate the user picking one option //Console.WriteLine("Chose a coin option"); //Console.ReadKey(); //Lets Assume they pick Heads coinOption = CoinOptions.Heads; return coinOption; } public void setCoinOption(CoinOptions opponent) { coinOption = opponent == CoinOptions.Heads ? CoinOptions.Tails : CoinOptions.Heads; } public bool didPlayerWin(CoinOptions winningFlip) { return winningFlip == coinOption; } } </code></pre> <p>Coin class</p> <pre><code>class Coin { private Random random; public Coin(Random rand) { random = rand; } public CoinOptions flipCoin() { double probability = random.NextDouble(); return probability &gt; 0.5 ? CoinOptions.Heads : CoinOptions.Tails; } } </code></pre> <p>CoinGame Class</p> <pre><code>internal class CoinGame { private List&lt;Player&gt; players = new List&lt;Player&gt;(Enumerable.Repeat(default(Player), 2)); private Coin coin; private CoinOptions winningFlip; public CoinGame(Coin coinUsed, List&lt;string&gt; playerNames = null) { for (int i = 0; i &lt; players.Count; i++) { var playerName = playerNames != null ? playerNames[i] : $"player{i}"; players[i] = new Player(playerName); } coin = coinUsed; } public void playCoinFlip() { int chooseIndex = new Random().Next(2); int applyIndex = chooseIndex == 0 ? 1 : 0; var selectedOption = players[chooseIndex].chooseCoinOption(); players[applyIndex].setCoinOption(selectedOption); winningFlip = coin.flipCoin(); } public void gameResult() { foreach (var player in players) { if(player.didPlayerWin(winningFlip)) { Console.WriteLine($"The player {player.playerName} won choosing {player.coinOption}"); } else { Console.WriteLine($"The player {player.playerName} lost choosing {player.coinOption}"); } } } } </code></pre> <p>And the calling code</p> <pre><code>class Program { static void Main(string[] args) { var coin = new Coin(new Random(12312)); var coinGame = new CoinGame(coin); coinGame.playCoinFlip(); coinGame.gameResult(); Console.ReadKey(); } } </code></pre> <p>My main concern is if there is a better strategy to </p> <ul> <li>Initialize the players in the game</li> <li>Allowing a random user to choose their coin option while simultaneously setting the other user with the leftover option</li> </ul>
[]
[ { "body": "<h2>Smurf naming convention</h2>\n\n<p><a href=\"https://blog.codinghorror.com/new-programming-jargon/\" rel=\"noreferrer\">Link</a></p>\n\n<pre><code>internal class Player\n{\n public string playerName { get; set; }\n</code></pre>\n\n<p><code>playerName</code> is redundant since it's a preoperty ...
{ "AcceptedAnswerId": "205738", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T05:55:29.743", "Id": "205726", "Score": "1", "Tags": [ "c#", "object-oriented", "game", "design-patterns" ], "Title": "Flip coin Game in an Object oriented way" }
205726
<p>Working doubly linked list using C++ and templates, I tried to make it by myself. I tried to use head and tail as buffers and make a simple implementation. Please help me understand what I have done wrong, done good and could have done worse.</p> <pre><code>#pragma once #include &lt;iostream&gt; template &lt;typename T&gt; struct node { T value; node* prev = nullptr; node* next = nullptr; }; template &lt;typename T&gt; class LList { public: LList&lt;T&gt;(); ~LList(); T&amp; get(const int&amp; pos) const; void insert(const T&amp; value, const int&amp; pos); T&amp; remove(const int&amp; pos); private: int n_elements; node&lt;T&gt; *head = new node&lt;T&gt;; node&lt;T&gt; *tail = new node&lt;T&gt;; }; template&lt;typename T&gt; LList&lt;T&gt;::LList() { n_elements = 0; head-&gt;next = tail; tail-&gt;prev = head; } template&lt;typename T&gt; LList&lt;T&gt;::~LList() { } template&lt;typename T&gt; T&amp; LList&lt;T&gt;::get(const int &amp; pos) const { node&lt;T&gt; *temp = head; for (int i = 0; i &lt;= pos; i++) temp = temp-&gt;next; return temp-&gt;value; } template&lt;typename T&gt; void LList&lt;T&gt;::insert(const T &amp; value, const int &amp; pos) { node&lt;T&gt; *temp = new node&lt;T&gt;; temp-&gt;value = value; node&lt;T&gt; *prev = head; node&lt;T&gt; *next = head-&gt;next; for (int i = 0; i &lt; pos; i++) { prev = prev-&gt;next; next = next-&gt;next; } prev-&gt;next = temp; next-&gt;prev = temp; temp-&gt;prev = prev; temp-&gt;next = next; ++n_elements; } template&lt;typename T&gt; T &amp; LList&lt;T&gt;::remove(const int &amp; pos) { node&lt;T&gt; *prev = head; node&lt;T&gt; *curr = head-&gt;next; node&lt;T&gt; *next = curr-&gt;next; for (int i = 0; i &lt; pos; i++) { prev = prev-&gt;next; curr = curr-&gt;next; next = next-&gt;next; } prev-&gt;next = next; next-&gt;prev = prev; T value = curr-&gt;value; delete curr; --n_elements; return value; } </code></pre> <hr> <pre><code>#include &lt;iostream&gt; #include "LList.h" int main() { LList &lt;double&gt; mylist; mylist.insert(20, 0); mylist.insert(30, 1); mylist.insert(40, 2); mylist.insert(30, 2); mylist.insert(10, 0); std::cout &lt;&lt; "removing: " &lt;&lt; mylist.remove(0) &lt;&lt; std::endl; mylist.insert(10, 0); mylist.insert(10, 0); mylist.insert(10, 0); std::cout &lt;&lt; "removing: " &lt;&lt; mylist.remove(3) &lt;&lt; std::endl; std::cout &lt;&lt; "removing: " &lt;&lt; mylist.remove(2) &lt;&lt; std::endl; std::cout &lt;&lt; "removing: " &lt;&lt; mylist.remove(1) &lt;&lt; std::endl; std::cout &lt;&lt; mylist.get(0) &lt;&lt; std::endl; std::cout &lt;&lt; mylist.get(1) &lt;&lt; std::endl; std::cout &lt;&lt; mylist.get(2) &lt;&lt; std::endl; std::cout &lt;&lt; mylist.get(3) &lt;&lt; std::endl; system("pause"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T07:09:52.917", "Id": "396785", "Score": "0", "body": "Welcome to Code Review! Does the current code work the way you want it to?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T09:30:20.073", "Id"...
[ { "body": "<h1>Includes</h1>\n<p><code>&lt;iostream&gt;</code> isn't needed by the header, so don't include it there.</p>\n<h1>Null pointer</h1>\n<p>When I try to run the code, I get an attempt to dereference a null pointer at the first <code>remove(0)</code>, which crashes the program. This is because <code>r...
{ "AcceptedAnswerId": "205741", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T06:54:25.603", "Id": "205728", "Score": "2", "Tags": [ "c++", "linked-list" ], "Title": "Doubly linked list using C++ and templates" }
205728
<p>I'm attempting the <code>Graph Algorithms</code> section in CLRS right now. Here's an iterative DFS using a stack called <code>nodes</code>.</p> <p><code>T</code> is a vector of <code>pair</code>(s) of <code>ints</code> which store timestamps for each node.</p> <p><code>T[node].first = discovery time</code></p> <p><code>T[node].second = finishing time</code></p> <p><code>P</code> is a vector recording Parents for each node in the DFS-Tree.</p> <p><code>N</code> is number of nodes in a given <code>Directed Graph</code>, which is represented using the <code>Adjacency List</code> representation as <code>G</code>. So <code>G[node]</code> represents the <code>Adjacency List</code> (as a <code>vector</code> of <code>ints</code>) for <code>node</code> in <code>G</code>.</p> <p><code>cycleFound</code> is a boolean for detecting a cycle in <code>G</code>.</p> <pre><code>void stackDFS(vector&lt;vector&lt;int&gt;&gt;&amp; G, vector&lt;pair&lt;int, int&gt;&gt;&amp; T, vector&lt;int&gt;&amp; P, int N, bool* cycleFound) { stack&lt;int&gt; nodes; int Time = 0; int u, v; for (u = 1; u &lt;= N; u++) { if (T[u].first == 0) { nodes.push(u); while (!nodes.empty()) { v = nodes.top(); nodes.pop(); if (T[v].first == 0) { T[v].first = ++Time; // we push it back before expanding it's children // so it can be popped again and it's // finishing time can be added in "else if". // if it's popped from stack and it's already been // discovered, then by OUR stack's logic, it's children // have already been expanded, so it's fin-time can // now be added. nodes.push(v); for (auto w = G[v].begin(); w != G[v].end(); w++) { if (T[*w].first == 0) { // cout &lt;&lt; "Tree Edge encountered...(" &lt;&lt; v &lt;&lt; ", " &lt;&lt; *w &lt;&lt; ")" &lt;&lt; endl; P[*w] = v; nodes.push(*w); } // this is different from the else-if condition below // here, edges are being examined, and if a back-edge // is found, we say there's a cycle. // Back-Edge: v.d &lt; u.d &lt; u.f &lt; v.f // for an edge u --&gt; v else if (T[*w].second == 0) { // cout &lt;&lt; "Back Edge encountered...(" &lt;&lt; v &lt;&lt; ", " &lt;&lt; *w &lt;&lt; ")" &lt;&lt; endl; *cycleFound = true; } } } // don't wanna re-update finish-times again and again // cuz that would be wrong computations. // A node can be pushed multiple times on stack if // current DFS-path has edges to it from multiple nodes // and our node is still marked undiscovered. // Eg- node s in graph from CLRS pg 611, fig22.6, ex22.3-2 // Thus, only update fin-time once, when node finishes // for the first time. else if (T[v].second == 0) T[v].second = ++Time; } } } } </code></pre> <p>I tested this on two different digraphs, one cyclic and the other acyclic.</p> <p><code>Input 1: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6; acyclic</code></p> <p><code>Input 2: graph from CLRS pg 611, fig22.6; has three cyclic</code></p> <p>It correctly detects cycles and the timestamps computed make sense. So I think this implementation is correct, but I'm not sure. I wrote some comments in the code to explain my logic, but it's mostly intuition. Is this a correct implementation of DFS? Will it always compute timestamps correctly?</p> <p>Also, how could I classify edges in this code? I'm having trouble classifying Forward and Cross Edges. In recursive DFS it's simpler cuz of the nested recursive structure:</p> <pre><code>void DFSVisit(vector&lt;vector&lt;int&gt;&gt;&amp; G, vector&lt;pair&lt;int, int&gt;&gt;&amp; T, vector&lt;int&gt;&amp; P, int curNode, int* Time, bool* cycleFound) { (*Time)++; T[curNode].first = *Time; for (auto i = G[curNode].begin(); i != G[curNode].end(); i++) { if (T[*i].first == 0) { cout &lt;&lt; "Tree Edge encountered...(" &lt;&lt; curNode &lt;&lt; ", " &lt;&lt; *i &lt;&lt; ")" &lt;&lt; endl; P[*i] = curNode; DFSVisit(G, T, P, *i, Time, cycleFound); } // cycle is present if node (*i) if encountered from curNode // such that (*i) hasn't yet finished, meaning (*i) has been // encountered again in the current DFS traversal, thus // edge (curNode, *i) is a back edge which completes the cycle else if (T[*i].second == 0) { cout &lt;&lt; "Back Edge encountered...(" &lt;&lt; curNode &lt;&lt; ", " &lt;&lt; *i &lt;&lt; ")" &lt;&lt; endl; *cycleFound = true; } else { // only specifying condition for discovery times // is enough here because T&amp;B edges have already // classified above, and for C-edges, *i needs to // be discovered first. if (T[curNode].first &lt; T[*i].first) cout &lt;&lt; "Forward Edge encountered...(" &lt;&lt; curNode &lt;&lt; ", " &lt;&lt; *i &lt;&lt; ")" &lt;&lt; endl; else cout &lt;&lt; "Cross Edge encountered...(" &lt;&lt; curNode &lt;&lt; ", " &lt;&lt; *i &lt;&lt; ")" &lt;&lt; endl; } } (*Time)++; T[curNode].second = *Time; } </code></pre> <p>If I try these same conditions in the Iterative DFS, it doesn't work because there's no recursive structure, in other words, all outgoing edges from <code>current node</code> are classified as <code>Tree Edges</code>, since all outgoing edges are examined together in the <code>for-loop</code> in Iterative-DFS, even though some of them might be forward edges.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T07:04:19.387", "Id": "205729", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "graph" ], "Title": "Correctness of iterative DFS for cycle detection" }
205729
<p>I have a dictionary structured as <code>{a_1: [((b_11,c_11),d_11), ((b_12, c_12), d_12), ...], a_2: [...], ...}</code>. </p> <p>I want to extract the maximum abs(c) among all the possible c values. Currently I'm doing this throught two for loops. One for each a, and other for each of set {b,c,d}. </p> <pre><code>elements = { 0: [((0, -4), 1)], 1: [((1, -5), 1), ((0, -4), 1)], 2: [((2, -3), 1)], 3: [((3, -2), 1), ((0, -5), 1)], } max_c = 0 for a in list(elements): for (b, c), d in elements[a]: max_c = max(max_c, abs(c)) </code></pre> <p>Is there any way to do this without the for loops? and if it is, is it pythonic? or I should keep this way because it's more understandable?</p> <p>Thanks in advance.</p>
[]
[ { "body": "<p>If you were to extract all <code>abs(c)</code> into a list, you could use <code>max</code> over that list.</p>\n\n<p>Fortunately, this is easy using your loops and a list-comprehension:</p>\n\n<pre><code>Cs = [\n abs(value)\n for collection in elements.values()\n for (_, value), _ in coll...
{ "AcceptedAnswerId": "205743", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T08:32:25.887", "Id": "205733", "Score": "3", "Tags": [ "python", "hash-map" ], "Title": "Search in a nested list of a dictionary" }
205733
<p>I have two types that don't share any interface but have similar properties and that I need to compare for equality.</p> <p>One of them is comming from a 3rd party library and one of them is mine. I obviously cannot add any interface to the foreign type and honestly I don't want to create any wrapper for both of them in order to just use it once for some linq. I prefer to have something that lasts longer and can be reused for other projects.</p> <p>I used these to types for testing but they might of course have many other properties - and as a matter of fact my two actual types have exactly the same properties as this example:</p> <blockquote> <pre><code>class PersonLib1 { public string FirstName { get; set; } public string LastName { get; set; } } class PersonLib2 { public string FirstName { get; set; } public string LastName { get; set; } } </code></pre> </blockquote> <hr> <h2>API</h2> <p>I solved this problem by implementing the <code>IEqualityComparer&lt;object&gt;</code> as a <code>DuckEqualityComparer</code> - its name comes from the idea of <a href="https://devopedia.org/duck-typing" rel="noreferrer">Duck Typing</a> - this is, since both types share some common or similar properties they must be the same.</p> <p>My comparer allows the user to specify the exact types and their comparison logic. The order of the types is not relevant and it tries both combinations.</p> <p>I used additional blocks of <code>{}</code> inside the <code>Equals</code> method to be able to reuse the short variable names.</p> <pre><code>class DuckEqualityComparer&lt;Tx, Ty&gt; : IEqualityComparer&lt;object&gt; { private readonly Func&lt;Tx, Ty, bool&gt; _equals; private readonly Func&lt;Tx, int&gt; _getHashCodeX; private readonly Func&lt;Ty, int&gt; _getHashCodeY; private DuckEqualityComparer(Func&lt;Tx, Ty, bool&gt; equals, Func&lt;Tx, int&gt; getHashCodeX, Func&lt;Ty, int&gt; getHashCodeY) { _equals = equals; _getHashCodeX = getHashCodeX; _getHashCodeY = getHashCodeY; } public new bool Equals(object x, object y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; { if (x is Tx tx &amp;&amp; y is Ty ty &amp;&amp; Equals(tx, ty)) return true; } { if (x is Ty ty &amp;&amp; y is Tx tx &amp;&amp; Equals(tx, ty)) return true; } return false; } private bool Equals(Tx x, Ty y) { if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; return _equals(x, y); } public int GetHashCode(object obj) { switch (obj) { case Tx x: return _getHashCodeX(x); case Ty y: return _getHashCodeY(y); default: return 0; } } public static IEqualityComparer&lt;object&gt; Create(Func&lt;Tx, Ty, bool&gt; equals, Func&lt;Tx, int&gt; getHashCodeX, Func&lt;Ty, int&gt; getHashCodeY) { return new DuckEqualityComparer&lt;Tx, Ty&gt;(equals, getHashCodeX, getHashCodeY); } } </code></pre> <p>Why didn't I use tuples? Because they don't allow me to use other then the default comparer on the property level.</p> <p>Is this an acceptable solution or is there anything that could be done better?</p> <hr> <h2>Example</h2> <p>This is how I use it:</p> <pre><code>var p1 = new PersonLib1 { FirstName = "John", LastName = "Doe" }; var p2 = new PersonLib2 { FirstName = "JOHN", LastName = "Doe" }; var p3 = new PersonLib2 { FirstName = "Joh", LastName = "Doe" }; var stringComparer = StringComparer.OrdinalIgnoreCase; var personComparer = DuckEqualityComparer&lt;PersonLib1, PersonLib2&gt;.Create( equals: (x, y) =&gt; stringComparer.Equals(x.FirstName, y.FirstName) &amp;&amp; stringComparer.Equals(x.LastName, y.LastName), getHashCodeX: x =&gt; stringComparer.GetHashCode(x.FirstName) + stringComparer.GetHashCode(x.LastName), getHashCodeY: y =&gt; stringComparer.GetHashCode(y.FirstName) + stringComparer.GetHashCode(y.LastName) ); personComparer.Equals(p1, p2).Dump(); personComparer.Equals(p2, p1).Dump(); personComparer.Equals(p1, p3).Dump(); personComparer.Equals(p3, p1).Dump(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T10:09:05.613", "Id": "396802", "Score": "0", "body": "Maybe you can take a look at [AutoFixture/SemanticComparison](https://github.com/AutoFixture/SemanticComparison) which allows doing this kind of stuff. The documentation is spars...
[ { "body": "<p>You can shorten the syntax a bit and increase readability by using the <code>is</code> or <code>==</code> operators instead of <code>ReferenceEquals</code>:</p>\n\n<pre><code>public new bool Equals(object x, object y)\n{\n if (ReferenceEquals(x, y)) return true;\n if (x is null || y is null)...
{ "AcceptedAnswerId": "205772", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T09:27:46.800", "Id": "205736", "Score": "6", "Tags": [ "c#", "duck-typing" ], "Title": "Comparing similar types that don't share any interface" }
205736
<p>I have a report with a group by filter. A stored procedure returns all the data and maps it to <code>IEnumerable&lt;EventListRow&gt;</code>. The code should then group the data as per the user group by selection.</p> <p>In the following code, only the GroupID and GroupName changes each time. Is there a better way to write the code that avoids duplicating the following code in each case statement:</p> <pre><code>EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) </code></pre> <p>Or maybe there is just a better way to write it in general. Here is the full method:</p> <pre><code>public virtual IEnumerable&lt;EventListGroup&gt; GetEventsGrouped(IEnumerable&lt;EventListRow&gt; eventList, GroupByEventData groupBy) { var eventListGrouped = Enumerable.Empty&lt;EventListGroup&gt;(); switch (groupBy) { case GroupByEventData.Hour: eventListGrouped = eventList .GroupBy(e =&gt; new { e.StartDateTime.Date, e.StartDateTime.Hour }) .Select(group =&gt; new EventListGroup { GroupID = group.Min(e =&gt; e.StartDateTime.CimToSql()), GroupName = group.Min(e =&gt; e.StartDateTime.ToString("MMM dd yyyy HH:00tt")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.Day: eventListGrouped = eventList .GroupBy(e =&gt; new { e.Date }) .Select(group =&gt; new EventListGroup { GroupID = group.Min(e =&gt; e.Date.CimToSql()), GroupName = group.Min(e =&gt; e.Date.ToString("MMM dd yyyy")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.Week: eventListGrouped = eventList .GroupBy(e =&gt; new { Week = e.StartDateTime.GetWeekNumber(), e.StartDateTime.Year }) .Select(group =&gt; new EventListGroup { GroupID = group.Min(e =&gt; e.StartDateTime.CimToSql()), GroupName = "Wk " + group.Key.Week + ", " + group.Key.Year, EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.Month: eventListGrouped = eventList .GroupBy(e =&gt; new { e.StartDateTime.Month, e.StartDateTime.Year }) .Select(group =&gt; new EventListGroup { GroupID = group.Min(e =&gt; e.StartDateTime.CimToSql()), GroupName = group.Key.Month + "/" + group.Key.Year, EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.Year: eventListGrouped = eventList .GroupBy(e =&gt; new { e.StartDateTime.Year }) .Select(group =&gt; new EventListGroup { GroupID = group.Min(e =&gt; e.StartDateTime.CimToSql()), GroupName = group.Key.Year.ToString(), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.Job: eventListGrouped = eventList .GroupBy(e =&gt; e.JobID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.JobName ?? "No Job")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.Product: eventListGrouped = eventList .GroupBy(e =&gt; e.ProductID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.ProductName ?? "No Product")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.System: eventListGrouped = eventList .GroupBy(e =&gt; e.SystemID) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.SystemName ?? "No System")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.EventDefinition: eventListGrouped = eventList .GroupBy(e =&gt; e.EventDefinitionID) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.EventDefinitionName ?? "No Event Definition")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.EventCategory01: eventListGrouped = eventList .GroupBy(e =&gt; e.EventCategory01ID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.EventCategory01Name ?? "Unassigned")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.EventCategory02: eventListGrouped = eventList .GroupBy(e =&gt; e.EventCategory02ID ?? e.EventCategory01ID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.EventCategory01Name ?? "Unassigned") + (e.EventCategory02Name != null ? (this.GetEventCategoryDelimiter() + e.EventCategory02Name) : "")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.EventCategory03: eventListGrouped = eventList .GroupBy(e =&gt; e.EventCategory03ID ?? e.EventCategory02ID ?? e.EventCategory01ID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.EventCategory01Name ?? "Unassigned") + (e.EventCategory02Name != null ? (this.GetEventCategoryDelimiter() + e.EventCategory02Name) : "") + (e.EventCategory03Name != null ? (this.GetEventCategoryDelimiter() + e.EventCategory03Name) : "")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.EventCategory04: eventListGrouped = eventList .GroupBy(e =&gt; e.EventCategory04ID ?? e.EventCategory03ID ?? e.EventCategory02ID ?? e.EventCategory01ID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.EventCategory01Name ?? "Unassigned") + (e.EventCategory02Name != null ? (this.GetEventCategoryDelimiter() + e.EventCategory02Name) : "") + (e.EventCategory03Name != null ? (this.GetEventCategoryDelimiter() + e.EventCategory03Name) : "") + (e.EventCategory04Name != null ? (this.GetEventCategoryDelimiter() + e.EventCategory04Name) : "")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.EventCode: eventListGrouped = eventList .GroupBy(e =&gt; e.EventCodeID ?? -1) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.EventCodeName ?? "Unassigned")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; case GroupByEventData.OeeEventType: eventListGrouped = eventList .GroupBy(e =&gt; e.OeeEventType) .Select(group =&gt; new EventListGroup { GroupID = group.Key.ToString(), GroupName = group.Max(e =&gt; (e.OeeEventTypeName ?? "None")), EventDurationSeconds = group.Sum(e =&gt; e.EventDurationSeconds), EventCount = group.Count(), OeeEventTypeColourHex = group.Max(e =&gt; e.OeeEventTypeColourHex), OeeEventTypeName = group.Max(e =&gt; e.OeeEventTypeName) }); break; default: Log.WriteError(string.Format("Group by: \"{0}\" not coded for", groupBy), "EventService.GetEventsGrouped"); break; } return eventListGrouped; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T13:01:15.513", "Id": "396833", "Score": "2", "body": "Welcome to Code Review. The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for t...
[ { "body": "<p>You can write a factory to construct EventGroupList:</p>\n\n<pre><code>var groupFunc = new Func&lt;IGrouping&lt;EventListRow&gt;, EventListGroup&gt;(row =&gt; ...);\n</code></pre>\n\n<p>Then just select using the factory:</p>\n\n<pre><code>.Select(groupFunc);\n</code></pre>\n", "comments": [ ...
{ "AcceptedAnswerId": "205767", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T12:48:59.180", "Id": "205748", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "Grouping report data by one of two criteria" }
205748
<p>I recently rewrote my object pool design to <span class="math-container">\$O(n)\$</span> complexity. I did this using a linked list, which is not native in JavaScript. It does not, unfortunately, automatically assign <code>null</code> to a value when you free it.</p> <pre><code>const Pool = function() { const Free = new WeakMap, Next = new WeakMap, Default = new WeakMap, {setPrototypeOf, defineProperty, getOwnPropertyNames, freeze} = Object, {toString, hasOwnProperty} = {}, empty = ( obj, template ) =&gt; { let templateNames = getOwnPropertyNames( template ), ownNames = getOwnPropertyNames( obj ); for ( let name of [...templateNames, ...ownNames] ) { if( hasOwnProperty.call( template, name ) ) { if( typeof template[name] === 'object' ) { obj[name] = empty( obj[name], template[name] ); } else { obj[name] = template[name]; } } else { delete obj[name]; } } return obj; }, deepFreeze = (object) =&gt; { let propNames = getOwnPropertyNames(object); for (const name of propNames) { let value = object[name]; object[name] = value &amp;&amp; typeof value === "object" ? deepFreeze(value) : value; } return Object.freeze(object); }, deepClone = (object) =&gt; { let result = {}, propNames = getOwnPropertyNames(object); for (let name of propNames) { let value = object[name]; result[name] = value &amp;&amp; typeof value === "object" ? deepClone(value) : value; } return setPrototypeOf(result, object.__proto__); }; class Pool { constructor(obj, size) { Default.set(this, deepClone(obj)); Free.set(this, Array(size).fill().map((item) =&gt; { return deepClone(obj); }).map((item, index, array) =&gt; { return Next.set(item, array[index + 1] || null), item; })[0]); } allocate() { let result = Free.get(this); Free.set(this, Next.get(result)); return result; } free(obj) { if (Next.has(obj)) { Next.set(obj, Free.get(this)); Free.set(this, obj); Promise.resolve().then(empty.bind(null, obj, Default.get(this))); return; } } } return Pool; }(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T00:08:20.097", "Id": "396895", "Score": "0", "body": "Could you provide a usage example. Object pools are used to increase performance by side stepping allocation and GC overheads. For traditional pools the performance margins are s...
[ { "body": "<h1>Some problems</h1>\n<h2>Complex, indeterminate, non intuitive behaviour</h2>\n<p>There is a fundamental flaw in the <code>Pool</code> object due to the use of a resolved promise to reset the object.</p>\n<p>Calling <code>free</code> and <code>allocate</code> in the same execution context will res...
{ "AcceptedAnswerId": "205788", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T15:15:10.227", "Id": "205757", "Score": "2", "Tags": [ "javascript", "performance", "ecmascript-6", "complexity" ], "Title": "O(n) Object Pool" }
205757
<p>This code is a digital periodic table that I am working on, but it is taking forever as it is very long and I would like to shorten it.</p> <pre><code>#This is the intro sentence that explains the way my element index works. print("Welcome to my element index! You must enter the name of an element with a capital letter. Also you are able to type a capital letter to see lists of elements beginning with that letter. Any element with N/A next to it is not in the index at the moment. To see all of the letter lists you have to type the letters in alphabetical order. For example if you want to see F and after you want to see A, you have to restart the program to see A. And if you want to see Fluorine and then after Hydrogen, you have to restart the program to see Hydrogen.") #This is the variable that the user inputs the element they want to find or the letter to find an element. input_ = input("Please enter the name or first capital letter of an element:") #This very big chunk of code is the entire alphabetical list system. It checks what letter the input_ variable has and displays the list of that letter. if input_ == "A": print("Elements beginning with the letter A: Aluminium Argon Arsenic Astatine(N/A) Americium(N/A) Actinium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "B": print("Elements beginning with the letter B: Berylium Boron Bromine Bismuth(N/A) Bohrium(N/A") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "C": print("Elements beginning with the letter C: Carbon Chlorine Calcium Chromium Cobalt Copper Cadmium Caesium(N/A) Copernicium(N/A) Cerium(N/A) Curium(N/A) Californium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "D": print("Elements beginning with the letter D: Dubnium(N/A) Darmstadtium(N/A) Dysprosium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "E": print("Elements beginning with the letter E: Europium(N/A) Einsteinium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "F": print("Elements beginning with the letter F: Fluorine Francium(N/A) Fermium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "G": print("Elements beginning with the letter G: Gallium Germanium Gold(N/A) Gadolinium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "H": print("Elements beginning with the letter H: Hydrogen Helium Hafnium(N/A) Hassium(N/A) Holmium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "I": print("Elements beginning with the letter I: Iron Iodine Iridium(N/A) Indium") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "J": print("There are no elements beginning with the letter J") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "K": print("Elements beginning with the letter K: Krypton") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "L": print("Elements beginning with the letter L: Lithium Lead(N/A) Lanthanum(N/A) Lutetium(N/A) Lawrencium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "M": print("Elements beginning with the letter M: Magnesium Magnanese Molybdenum Meitnerium(N/A) Mendelevium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "N": print("Elements beginning with the letter N: Nitrogen Neon Nickel Niobium Neodymium(N/A) Nobelium(N/A) Neptunium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "O": print("Elements beginning with the letter O: Oxygen Osmium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "P": print("Elements beginning with the letter P: Potassium Phosphorus Platinum(N/A) Plutonium(N/A) Promethium(N/A) Protactinium(N/A) Praseodymium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "Q": print("There are no elements beginning with the letter Q") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "R": print("Elements beginning with the letter R: Rubidium Ruthenium(N/A) Rhodium(N/A) Radon(N/A) Rhenium(N/A) Radium(N/A) Rutherfordium(N/A) Roentgenium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "S": print("Elements beginning with the letter S: Sodium Silicon Sulphur Scandium Selenium Strontium Silver Seaborgium(N/A) Samarium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "T": print("Elements beginning with the letter T: Titanium Technetium Tin Tellurium(N/A) Tantalum(N/A) Tungsten(N/A) Thallium(N/A) Terbium(N/A) Thulium(N/A) Thorium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "U": print("Elements beginning with the letter U: Urainium(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "V": print("Elements beginning with the letter V: Vanadium") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "W": print("There are no elements beginning with the letter W") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "X": print("Elements beginning with the letter X: Xenon(N/A)") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "Y": print("Elements beginning with the letter Y: Yttrium Ytterbium(N/A") input_ = input("Please enter the name or first capital letter of an element:") elif input_ == "Z": print("Elements beginning with the letter Z: Zirconium") input_ = input("Please enter the name or first capital letter of an element:") #This chunk of code is the actual elements that you search up. This time, it checks what element the input_ variable has and displays the information of that element. if input_ == "Hydrogen": print("Element: Hydrogen Symbol: H Atomic Number: 1 Atomic Mass: 1 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Helium": print("Element: Helium Symbol: He Atomic Number: 2 Atomic Mass: 4 Group: Noble Gases") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Lithium": print("Element: Lithium Symbol: Li Atomic Number: 3 Atomic Mass: 7 Group: Alkali Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Berylium": print("Element: Berylium Symbol: Be Atomic Number: 4 Atomic Mass: 9 Group: Alkaline Earth Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Boron": print("Element: Boron Symbol: B Atomic Number: 5 Atomic Mass: 11 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Carbon": print("Element: Carbon Symbol: C Atomic Number: 6 Atomic Mass: 12 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Nitrogen": print("Element: Nitrogen Symbol: N Atomic Number: 7 Atomic Mass: 14 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Oxygen": print("Element: Oxygen Symbol: O Atomic Number: 8 Atomic Mass: 16 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Fluorine": print("Element: Fluorine Symbol: F Atomic Number: 9 Atomic Mass: 19 Group: Halogens") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Neon": print("Element: Neon Symbol: Ne Atomic Number: 10 Atomic Mass: 20 Group: Noble Gasses") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Sodium": print("Element: Sodium Symbol: Na Atomic Number: 11 Atomic Mass: 23 Group: Alkali Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Magnesium": print("Element: Magnesium Symbol: Mg Atomic Number: 12 Atomic Mass: 24 Group: Alkaline Earth Metal") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Aluminium": print("Element: Aluminium Symbol: Al Atomic Number: 13 Atomic Mass: 27 Group: Other Metals") input_ = input("Please enter the name or first capital letter of an element") if input_ == "Silicon": print("Element: Silicon Symbol: Si Atomic Number: 14 Atomic Mass: 28 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Phosphorus": print("Element: Phosphorus Symbol: P Atomic Number: 15 Atomic Mass: 31 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Sulphur": print("Element: Sulphur Symbol: S Atomic Number: 16 Atomic Mass: 32 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Chlorine": print("Element: Chlorine Symbol: Cl Atomic Number: 17 Atomic Mass: 35.5 Group: Halogens") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Argon": print("Element: Argon Symbol: Ar Atomic Number: 18 Atomic Mass: 40 Group: Noble Gasses") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Potassium": print("Element: Potassium Symbol: K Atomic Number: 19 Atomic Mass: 39 Group: Alkali Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Calcium": print("Element: Calcium Symbol: Ca Atomic Number: 20 Atomic Mass: 40 Group: Alkaline Earth Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Scandium": print("Element: Scandium Symbol: Sc Atomic Number: 21 Atomic Mass: 45 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Titanium": print("Element: Titanium Symbol: Ti Atomic Number: 22 Atomic Mass: 48 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Vanadium": print("Element: Vanadium Symbol: V Atomic Number: 23 Atomic Mass: 51 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Chromium": print("Element: Chromium Symbol: Cr Atomic Number: 24 Atomic Mass: 52 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Manganese": print("Element: Manganese Symbol: Mn Atomic Number: 25 Atomic Mass: 55 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Iron": print("Element: Iron Symbol: Fe Atomic Number: 26 Atomic Mass: 56 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Cobalt": print("Element: Cobalt Symbol: Co Atomic Number: 27 Atomic Mass: 59 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Nickel": print("Element: Nickel Symbol: Ni Atomic Number: 28 Atomic Mass: 59 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Copper": print("Element: Copper Symbol: Cu Atomic Number: 29 Atomic Mass: 63.5 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Zinc": print("Element: Zinc Symbol: Zn Atomic Number: 30 Atomic Mass: 65 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Gallium": print("Element: Gallium Symbol: Ga Atomic Number: 31 Atomic Mass: 70 Group: Other Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Germanium": print("Element: Germanium Symbol: Ge Atomic Number: 32 Atomic Mass: 73 Group: Other Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Arsenic": print("Element: Arsenic Symbol: As Atomic Number: 33 Atomic Mass: 75 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Selenium": print("Element: Selenium Symbol: Se Atomic Number: 34 Atomic Mass: 79 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Bromine": print("Element: Bromine Symbol: Br Atomic Number: 35 Atomic Mass: 80 Group: Halogens") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Krypton": print("Element: Krypton Symbol: Kr Atomic Number: 36 Atomic Mass: 84 Group: Noble Gasses") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Rubidium": print("Element: Rubidium Symbol: Rb Atomic Number: 37 Atomic Mass: 85 Group: Alkali Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Strontium": print("Element: Strontium Symbol: Sr Atomic Number: 38 Atomic Mass: 88 Group: Alkaline Earth Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Yttrium": print("Element: Yttrium Symbol: Y Atomic Number: 39 Atomic Mass: 89 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Zirconium": print("Element: Zirconium Symbol: Zr Atomic Number: 40 Atomic Mass: 91 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Niobium": print("Element: Niobium Symbol: Nb Atomic Number: 41 Atomic Mass: 93 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Molybdenum": print("Element: Molybdenum Symbol: Mo Atomic Number: 42 Atomic Mass: 96 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Technetium": print("Element: Technetium Symbol: Tc Atomic Number: 43 Atomic Mass: 98 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Ruthenium": print("Element: Ruthenium Symbol: Ru Atomic Number: 44 Atomic Mass: 101 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Rhodium": print("Element: Rhodium Symbol: Rh Atomic Number: 45 Atomic Mass: 103 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Palladium": print("Element: Palladium Symbol: Pd Atomic Number: 46 Atomic Mass: 106 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Silver": print("Element: Silver Symbol: Ag Atomic Number: 47 Atomic Mass: 108 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Cadmium": print("Element: Cadmium Symbol: Cd Atomic Number: 48 Atomic Mass: 112 Group: Transition Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Indium": print("Element: Indium Symbol: In Atomic Number: 49 Atomic Mass: 115 Group: Other Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Tin": print("Element: Tin Symbol: Sn Atomic Number: 50 Atomic Mass: 119 Group: Other Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Antimony": print("Element: Antimony Symbol: Sb Atomic Number: 51 Atomic Mass: 122 Group: Other Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Tellurium": print("Element: Tellurium Symbol: Te Atomic Number: 52 Atomic Mass: 128 Group: Non Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Iodine": print("Element: Iodine Symbol: I Atomic Number: 53 Atomic Mass: 127 Group: Halogens") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Xenon": print("Element: Xenon Symbol: Xe Atomic Number: 54 Atomic Mass: 131 Group: Noble Gasses") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Caesium": print("Element: Caesium Symbol: Cs Atomic Number: 55 Atomic Mass: 133 Group: Alkali Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Barium": print("Element: Barium Symbol: Ba Atomic Number: 56 Atomic Mass: 137 Group: Alkaline Earth Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Lanthanum": print("Element: Lanthanum Symbol: La Atomic Number: 57 Atomic Mass: 139 Group: Rare Earth Metals") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Cerium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Praseodymium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Neodymium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Promethium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Samarium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Europium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Gadolinium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Terbium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Dysprosium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Holmium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Erbium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Thulium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Ytterbium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Lutetium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Hafnium": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Tantalum": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Tungsten": print("") input_ = input("Please enter the name or first capital letter of an element:") if input_ == "Rhenium": print("") input_ = input("Please enter the name or first capital letter of an element:") </code></pre>
[]
[ { "body": "<p>Here's the thing: you should probably store all of these elements in a file of some sort (say <code>elements.txt</code>). The format of the file can be as follows:</p>\n\n<pre><code>Hydrogen Element: Hydrogen Symbol: H Atomic Number: 1 Atomic Mass: 1 Group: Non Metals\nHelium Element: Helium ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T19:47:34.977", "Id": "205770", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "Index for the elements of the periodic table" }
205770
<p>This code is looping over polygons geometries vertices in order to create a list of deltas (distance) between vertices coordinates to compact the geometry before sending it into the web.</p> <p>Geometry output is expected to be on this format: <code>[[x0, y0, (x0-x1), (y0-y1), (x1-x2), (y1-y2)]]</code> </p> <p>The output is a JSON object containing a list of features attributes and geometry deltas like this one:</p> <pre><code>{ features: [ { attributes : {"CD_MUNCP" : 00000, "NOM_MUNCP": "Name1"}, geometry : [[5767767, -834778, -10, 199, 99, 332, 9, -9], [5787767, -837709, 123, 33, -31, 121, 0, 12330]] } ] } </code></pre> <p>I am using <code>IEnumerable&lt;&gt;</code> to create the geometry deltas because I thought it would be faster, but it appears this is not really compatible with JSON serialization (it takes very long to serialize) so I transform them using <code>.ToList()</code>.</p> <p>The most important thing with the code is the performance. It seems the bottleneck is the JSON serialization that takes more than 50% of the processing time.</p> <p><strong>Is there some optimizations or workarounds I can do to improve the performance?</strong></p> <pre><code>using System; using System.Collections.Generic; using fastJSON; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.esriSystem; namespace DesktopConsoleApplication1 { class Program { static void Main(string[] args) { var watch = System.Diagnostics.Stopwatch.StartNew(); Result result = new Result { features = CreateResultFeatures().ToList() }; string output = JSON.ToJSON(result); watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds); Console.ReadLine(); } public class Result { public IEnumerable&lt;ResultFeature&gt; features { get; set; } } public class ResultFeature { public Dictionary&lt;string, dynamic&gt; attributes { get; set; } public IEnumerable&lt;IEnumerable&lt;int&gt;&gt; geometry { get; set; } } public static IEnumerable&lt;ResultFeature&gt; CreateResultFeatures() { IWorkspace gdbWorkspace = FileGdbWorkspaceFromPath(@"\\vnageop1\geod\Maxime\test.gdb"); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)gdbWorkspace; IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(@"GEO09E04_MUNCP_GEN"); IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = "CD_MUNCP, NOM_MUNCP, SHAPE"; int cd_muncp_idx = featureClass.FindField("CD_MUNCP"); int nom_muncp_idx = featureClass.FindField("NOM_MUNCP"); using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor cursor = featureClass.Search(queryFilter, false); comReleaser.ManageLifetime(cursor); IFeature feature = null; while ((feature = cursor.NextFeature()) != null) { ResultFeature resultFeature = new ResultFeature { attributes = new Dictionary&lt;string,dynamic&gt; { { "CD_MUNCP", Convert.ToString(feature.Value[cd_muncp_idx]) }, { "NOM_MUNCP", Convert.ToString(feature.Value[nom_muncp_idx]) } }, geometry = PolygonToDeltas(feature.Shape as IPolygon4).ToList() }; yield return resultFeature; } } } public static IEnumerable&lt;IEnumerable&lt;int&gt;&gt; PolygonToDeltas(IPolygon4 polygon) { IGeometryBag exteriorRingGeometryBag = polygon.ExteriorRingBag; IGeometryCollection exteriorRingGeometryCollection = exteriorRingGeometryBag as IGeometryCollection; for (int i = 0; i &lt; exteriorRingGeometryCollection.GeometryCount; i++) { IGeometry exteriorRingGeometry = exteriorRingGeometryCollection.get_Geometry(i); IPointCollection exteriorRingPointCollection = exteriorRingGeometry as IPointCollection; yield return CreateDeltas(exteriorRingPointCollection); IGeometryBag interiorRingGeometryBag = polygon.get_InteriorRingBag(exteriorRingGeometry as IRing); IGeometryCollection interiorRingGeometryCollection = interiorRingGeometryBag as IGeometryCollection; for (int k = 0; k &lt; interiorRingGeometryCollection.GeometryCount; k++) { IGeometry interiorRingGeometry = interiorRingGeometryCollection.get_Geometry(k); IPointCollection interiorRingPointCollection = interiorRingGeometry as IPointCollection; yield return CreateDeltas(exteriorRingPointCollection); } } } private static IEnumerable&lt;int&gt; CreateDeltas(IPointCollection pointCollection) { int previous_x = (int)pointCollection.get_Point(0).X; int previous_y = (int)pointCollection.get_Point(0).Y; yield return previous_x; yield return previous_y; for (int i = 1; i &lt; pointCollection.PointCount; i++) { int current_x = (int)pointCollection.get_Point(i).X; int current_y = (int)pointCollection.get_Point(i).Y; yield return previous_x - current_x; yield return previous_y - current_y; previous_x = current_x; previous_y = current_y; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T07:45:22.067", "Id": "396926", "Score": "0", "body": "Without having run it, I'd say the bottleneck is the `dynamic`. It doesn't look like it's necessary. Try to replace it with a strong type and see how it performs then." }, { ...
[ { "body": "<p>I haven't access to the ESRI assemblies, so it's impossible to test and comment about performance, but in this:</p>\n\n<blockquote>\n<pre><code>public static IEnumerable&lt;IEnumerable&lt;int&gt;&gt; PolygonToDeltas(IPolygon4 polygon)\n{\n IGeometryBag exteriorRingGeometryBag = polygon.ExteriorRi...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T19:53:12.717", "Id": "205771", "Score": "1", "Tags": [ "c#", "performance", ".net" ], "Title": "JSON serialization object with huge IEnumerable" }
205771
<p>Here is a simple text-based version of connect four I made. I have been building this in an attempt to improve my Java skills (and possibly mention on my resume).</p> <p>My goals with this project are as follows:</p> <ol> <li><p>Clean, optimize, and restructure: code, classes, and game logic based on feedback.</p></li> <li><p>Transform this program from text-based to graphics based using JavaFX</p></li> <li><p>Add computer AI logic to face a challenging opponent (assuming this is feasible to implement at my current skill level)</p></li> </ol> <p>ConnectFour.java:</p> <pre><code>import java.util.HashSet; import java.util.Set; public class ConnectFour { private final int[][] gameBoard; private static final int ROWS = 6; private static final int COLUMNS = 7; private static final int RED = 1; private static final int YELLOW = 2; public ConnectFour(Player playerOne, Player playerTwo) { this.gameBoard = new int[ROWS][COLUMNS]; //Initialize each position in the game board to empty for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLUMNS; j++) { gameBoard[i][j] = -1; } } } public boolean makeMove(Player player, int column) { /* Since row position is determined by how many pieces are currently in a given column, we only need to choose a column position and the row position will be determined as a result. */ //Decrement the column value by 1, as our array is zero indexed. column--; //Check if the column chosen is valid if (column &lt; 0 || column &gt;= COLUMNS) { System.out.println("Column choice must be between positive and be no greater than 6!"); return false; } //Check if the column chosen is already full if (isColumnFull(column)) { System.out.println("That column is already full!"); return false; } /*Otherwise, start from the bottom of the column and change the value in the first open row to the player's number*/ else { for (int i = ROWS - 1; i &gt;= 0; i--) { if (gameBoard[i][column] == -1) { gameBoard[i][column] = player.getPlayerNumber(); break; } } return true; } } public int validateGameBoard() { //1.) Check each row for four sequential pieces of the same color //2.) Check each column for four sequential pieces of the same color //3.) check each diagonal(with more than four spaces along it) for four sequential pieces of the same color //Return -1 if no current winner //Return 0 if the board is full, indicating a tie //Return 1 if player one wins //Return 2 if player 2 wins if (isBoardFull()) { System.out.println("The board is full!"); return 0; } int checkRows = validateRows(); int checkColumns = validateColumns(); int checkDiagonals = validateDiagonals(); if (checkRows == 1 || checkColumns == 1 || checkDiagonals == 1) { return 1; } else if (checkRows == 2 || checkColumns == 2 || checkDiagonals == 2) { return 2; } else { return -1; } } private int validateRows() { //System.out.println("Now validating rows"); //To validate the rows we do the following: //1.) For each row, we select a slice of 4 columns. //2.) We place each of these column values in a hash set. //3.) Since hash sets do not allow duplicates, we will easily know if our group of 4 were the same number(color) //4.) We repeat this process for each group of four columns in the row, for every row of the board. for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLUMNS - 3; j++) { Set&lt;Integer&gt; pieceSet = new HashSet&lt;Integer&gt;(); pieceSet.add(gameBoard[i][j]); pieceSet.add(gameBoard[i][j + 1]); pieceSet.add(gameBoard[i][j + 2]); pieceSet.add(gameBoard[i][j + 3]); if (pieceSet.size() == 1) { if (pieceSet.contains(RED)) { //Player One Wins return RED; } else if (pieceSet.contains(YELLOW)) { //Player Two Wins return YELLOW; } } } } return -1; } private int validateColumns() { //System.out.println("Now validating columns"); //To validate the columns, we use a similar hash set validation process to the row validation. // The key difference is, for every column, we select a slice of 4 rows. // each time we grab one of these slices, we check the hash set exactly the way we did the the row validator for (int j = 0; j &lt; COLUMNS; j++) { for (int i = ROWS - 1; i &gt;= 3; i--) { Set&lt;Integer&gt; pieceSet = new HashSet&lt;Integer&gt;(); pieceSet.add(gameBoard[i][j]); pieceSet.add(gameBoard[i - 1][j]); pieceSet.add(gameBoard[i - 2][j]); pieceSet.add(gameBoard[i - 3][j]); if (pieceSet.size() == 1) { //We have a winner if (pieceSet.contains(RED)) { //Player 1 Wins return RED; } else if (pieceSet.contains(YELLOW)) { //Player 2 Wins return YELLOW; } } } } return -1; } private int validateDiagonals() { //Start by moving across the first row(left to right), and check all diagonals that can fit more than 4 pieces. //System.out.println("Now validating diagonals left to right"); //Validating the diagonals is more involved than the last two validations: /*First, move across the first row, validating all left diagonals (diagonals which connect the top row to the left most column)*/ //Note that not every diagonal will contain 4 positions, so we can skip such diagonals for (int i = 3; i &lt; COLUMNS; i++) { int j = 0; // Check each left diagonal in the first row int k = i; while (k - 3 &gt;= 0 &amp;&amp; j + 3 &lt; ROWS) { Set&lt;Integer&gt; pieces = new HashSet&lt;&gt;(); pieces.add(gameBoard[j][k]); pieces.add(gameBoard[j + 1][k - 1]); pieces.add(gameBoard[j + 2][k - 2]); pieces.add(gameBoard[j + 3][k - 3]); if (pieces.size() == 1) { if (pieces.contains(RED)) { return RED; } else if (pieces.contains(YELLOW)) { return YELLOW; } } j++; k--; } } /*Then we move down the right most column and validate each diagonal which connects this column to the bottom row*/ //Note that our previous top row diagonal validator will have checked the fist column's diagonal already for (int i = 1; i &lt; 3;i++) { int j = i; // set the row number to change with i int k = COLUMNS - 1;// only traverse the last column while (j + 3 &lt; ROWS &amp;&amp; k - 3 &gt;= 0) { Set&lt;Integer&gt; pieces = new HashSet&lt;&gt;(); pieces.add(gameBoard[j][k]); pieces.add(gameBoard[j + 1][k - 1]); pieces.add(gameBoard[j + 2][k - 2]); pieces.add(gameBoard[j + 3][k - 3]); if (pieces.size() == 1) { if (pieces.contains(RED)) { return RED; } else if (pieces.contains(YELLOW)) { return YELLOW; } } j++; k--; } } //System.out.println("Now validating diagonals right to left"); /*Now we repeat the above process, but begin by validating each right diagonal(diagonals which connect the top row to the rightmost column*/ //Note we can again ignore diagonals that are shorter than 4 board positions for (int i = COLUMNS - 4; i &gt;= 0; i--) { //Moving across the top row from right to left, validate each diagonal int j = 0; //Move across the first row int k = i;// set the column number to change with i while (j + 3 &lt; ROWS &amp;&amp; k + 3 &lt; COLUMNS) { Set&lt;Integer&gt; pieces = new HashSet&lt;&gt;(); pieces.add(gameBoard[j][k]); pieces.add(gameBoard[j + 1][k + 1]); pieces.add(gameBoard[j + 2][k + 2]); pieces.add(gameBoard[j + 3][k + 3]); if (pieces.size() == 1) { if (pieces.contains(RED)) { return RED; } else if (pieces.contains(YELLOW)) { return YELLOW; } } j++; k++; } } /* Lastly, move down the leftmost column and check each diagonal which connects the left most column to the bottom row*/ for (int i = 1; i &lt; 3; i++) { //validate each diagonal here int j = i;// set the row number to change with i; int k = 0;// before entering the while loop, begin at the first column(column 0); while (j + 3 &lt; ROWS &amp;&amp; k + 3 &lt; COLUMNS) { Set&lt;Integer&gt; pieces = new HashSet&lt;&gt;(); pieces.add(gameBoard[j][k]); pieces.add(gameBoard[j + 1][k + 1]); pieces.add(gameBoard[j + 2][k + 2]); pieces.add(gameBoard[j + 3][k + 3]); if (pieces.size() == 1) { if (pieces.contains(RED)) { return RED; } else if (pieces.contains(YELLOW)) { return YELLOW; } } j++; k++; } } return -1; } private boolean isColumnFull(int columnNumber) { /*Based on the way pieces are placed in a game of connect four, if the very first row of a column has a piece in it, the column must be full.*/ if (gameBoard[0][columnNumber] == -1) { return false; } else { return true; } } private boolean isBoardFull() { //If any value in our board is -1, the board is not full for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLUMNS; j++) { if (gameBoard[i][j] == -1) { return false; } } } //Otherwise the board is full return true; } public void printGameBoard() { System.out.println("=============================="); //Display the number for each column System.out.println("1 2 3 4 5 6 7"); for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLUMNS; j++) { if (gameBoard[i][j] == RED) { System.out.print("R "); } else if (gameBoard[i][j] == YELLOW) { System.out.print("Y "); } else { System.out.print("- "); } } System.out.println(); } System.out.println("=============================="); } public void clearBoard() { //Reset all board positions to -1 for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLUMNS; j++) { gameBoard[i][j] = -1; } } } } </code></pre> <p>Player.java:</p> <pre><code>public class Player { private final String name; private static int counter = 0; private int playerNumber; //private Scanner scanner = new Scanner(System.in); public Player(String name) { //Initialize player number to increment based on how many instances there have been of the class this.name = name; this.counter++; this.playerNumber = counter; } public String getName() { return name; } public int getPlayerNumber() { return playerNumber; } } </code></pre> <p>Main.Java:</p> <pre><code>import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { //Create two players and get their names from user input System.out.println("Welcome to Connect Four!"); System.out.println("Player 1 please enter your name: "); String player1_name = scanner.nextLine(); System.out.println("Player 2 Enter your name: "); String player2_name = scanner.nextLine(); Player playerOne = new Player(player1_name); Player playerTwo = new Player(player2_name); System.out.println(playerOne.getName() + " will be red (R on the board)"); System.out.println(playerTwo.getName() + " will be yellow (Y on the board)\n"); ConnectFour connectFour = new ConnectFour(playerOne,playerTwo); connectFour.printGameBoard(); System.out.println("\n"); boolean hasWon = false; while(hasWon == false){ System.out.println(playerOne.getName() + ", Please enter a column to make your move"); int move = scanner.nextInt(); while(connectFour.makeMove(playerOne, move) == false){ System.out.println("Please try again: "); move =scanner.nextInt(); } connectFour.printGameBoard(); int winner = connectFour.validateGameBoard(); whoWon(winner); if(winner != -1){ hasWon = false; break; } System.out.println(playerTwo.getName() + ", Please enter a column to make your move"); move = scanner.nextInt(); while(connectFour.makeMove(playerTwo, move) == false){ System.out.println("Please try again: "); move =scanner.nextInt(); } connectFour.printGameBoard(); winner = connectFour.validateGameBoard(); whoWon(winner); if(winner != -1){ hasWon = false; break; } } } private static void whoWon(int winner){ if(winner == 0){ System.out.println("It's a tie!"); } else if(winner == 1){ System.out.println("Player One wins!"); } else if(winner == 2){ System.out.println("Player Two wins!"); } else{ System.out.println("No winner yet!\n"); } } } </code></pre>
[]
[ { "body": "<p>Based on your stated goals, I would offer the following suggestions.</p>\n\n<h1>Separate the game model from the game UI</h1>\n\n<p>You have a text-based game. You want a JavaFX based game. The text-based game is outputting messages to the console. When you have the JavaFX based game, you won't...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T20:36:40.963", "Id": "205773", "Score": "3", "Tags": [ "java", "object-oriented", "game", "connect-four" ], "Title": "Basic Connect Four game" }
205773
<p>I am trying to create a directory, but I have to check whether <code>/usr</code> is present initially, later <code>/usr/local</code> is present and so on, is this an elegant way of writing it?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main () { char str[] ="/usr/local/mnt/"; char path[40] = {0}; char temp[40] = {0}; char *slash = "/"; char *pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str,"/"); printf (" First one %s\n",pch); while (pch != NULL) { snprintf(path, sizeof(path), "%s%s%s", temp, slash, pch); strncpy(temp, path, 40); if (stat(path, &amp;sb) == 0 &amp;&amp; S_ISDIR(sb.st_mode)){ printf("Directory path already exists\n"); } else{ if(mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0){ printf("directory creation error"); return -1; } } pch = strtok (NULL, "/"); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T20:56:58.740", "Id": "396889", "Score": "4", "body": "The code doesn't compile. `sb` is not declared, and the header files are missing. To avoid the closing votes, please update the code to compile cleanly." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T20:37:34.343", "Id": "205774", "Score": "3", "Tags": [ "c", "file-system" ], "Title": "Trying to create a directory if it doesn't exist" }
205774
<p>I started learning Rust a few hours ago with the Rust Book (2018 edition) and as part of one of the <a href="https://doc.rust-lang.org/book/2018-edition/ch03-05-control-flow.html#summary" rel="nofollow noreferrer">exercises</a> decided to make a temperature converter. I wanted to make sure it handled all inputs properly in an idiomatic fashion. The code is as follows:</p> <pre><code>use std::io; use std::io::Write; use std::str::FromStr; fn main() { println!("Welcome to the temperature converter!"); println!("Pick a conversion:"); println!("[1] Fahrenheit to Celsius"); println!("[2] Celsius to Fahrenheit"); let choice: u32 = loop { let value = read_value_from_input("&gt; ", "Please enter a valid integer!"); if value == 1 || value == 2 { break value; } println!("Please enter a valid choice (0 or 1)!"); }; if choice == 1 { let temperature: f64 = read_value_from_input("Enter the temperature to convert: ", "Please enter a valid floating point variable!"); println!("{:.2} Β°F is {:.2} Β°C.", temperature, (temperature - 32f64) * 5f64 / 9f64); } else if choice == 2 { let temperature: f64 = read_value_from_input("Enter the temperature to convert: ", "Please enter a valid floating point variable!"); println!("{:.2} Β°C is {:.2} Β°F.", temperature, temperature * 9f64 / 5f64 + 32f64); } else { println!("{} was not a valid choice!", choice); } } fn read_value_from_input&lt;T: FromStr&gt;(prompt: &amp;str, error_message: &amp;str) -&gt; T { let result: T = loop { print!("{}", prompt); io::stdout().flush().expect("Unable to flush STDOUT!"); let mut input_value = String::new(); io::stdin().read_line(&amp;mut input_value) .expect(error_message); match input_value.trim().parse() { Ok(value) =&gt; break value, Err(_) =&gt; { println!("{}", error_message); continue; } } }; result } </code></pre> <p>Here are the things I want to know from this code review:</p> <ul> <li>Is my code idiomatic Rust? Does it follow its coding conventions, style, etc.?</li> <li>Does my code handle all erroneous inputs properly?</li> <li>Can the code be shortened or optimized in any way?</li> </ul>
[]
[ { "body": "<blockquote>\n <p>Is my code idiomatic Rust? Does it follow its coding conventions, style, etc.?</p>\n</blockquote>\n\n<p>It's pretty close. There are a couple of things I would recommend changing:</p>\n\n<ol>\n<li><p>Use <code>match</code> whenever multiple branches in your flow are based upon a si...
{ "AcceptedAnswerId": "206082", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T20:40:18.640", "Id": "205775", "Score": "3", "Tags": [ "beginner", "validation", "rust", "unit-conversion" ], "Title": "Temperature converter in Rust with input error handling" }
205775
<p><strong>General Magento questions may be asked on <a href="https://magento.stackexchange.com">Magento Stack Exchange</a>.</strong></p> <p><a href="https://magento.com/" rel="nofollow noreferrer">Magento</a> is an e-commerce platform written in <a href="/questions/tagged/php" class="post-tag" title="show questions tagged &#39;php&#39;" rel="tag">php</a> atop the <a href="/questions/tagged/zend-framework" class="post-tag" title="show questions tagged &#39;zend-framework&#39;" rel="tag">zend-framework</a>, available under both open-source and commercial licenses. It is written in an advanced object-oriented idiom that uses the <a href="/questions/tagged/mvc" class="post-tag" title="show questions tagged &#39;mvc&#39;" rel="tag">mvc</a> pattern and <a href="/questions/tagged/xml" class="post-tag" title="show questions tagged &#39;xml&#39;" rel="tag">xml</a> configuration files, aiming for flexibility and extensibility. It is owned and maintained by Adobe.</p> <p>Magento is aimed at merchants who need an online presence, but who find that a completely bespoke storefront does not suit their needs, budget, or scale. Magento's features include baked-in support of multiple languages and currencies, search engine optimization techniques, and automated email marketing. Basic Magento configuration and administration can be performed by end-users with minimal technical background, and the third-party ecosystem around Magento offers extensive customization of appearance and functionality for storefronts. Magento offers a developer certification program to help store owners find partners in the Magento ecosystem, and to help developers consolidate their grasp of Magento internals.</p> <p>A central feature of Magento is the templating and extension system, based on OOP inheritance and composition principles and largely configured by XML files, it provides a plugin API, it allows developers to modify almost any feature of Magento by working with the abstraction layers provided by the framework. Several subsystems (Layout and DataFlow) employ meta-programming facilities via XML, and the MVC pattern is supported by factory methods for instantiation of helper classes (Models, Helpers, and Blocks).</p> <p>Magento is a heavily abstracted software system. Most of Magento's code, and nearly all third-party code, is organized into modules, and the functionality of modules is programmatically exposed. Modules can be enabled or disabled individually, easing integration into existing stores. Magento's persistent storage is usually MySQL, and its data about a store's products are based on <a href="https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model" rel="nofollow noreferrer">the Entity-Attribute-Value model</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T23:17:38.360", "Id": "205781", "Score": "0", "Tags": null, "Title": null }
205781
Magento is an e-commerce platform written in PHP atop the Zend framework.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T23:17:38.360", "Id": "205782", "Score": "0", "Tags": null, "Title": null }
205782
<p>Please review my <a href="https://en.wikipedia.org/wiki/Breadth-first_search" rel="nofollow noreferrer">Breadth-first search</a> algorithm implementation in Java for finding the shortest path on a 2D grid map with obstacles.</p> <p>The <code>findPath()</code> method receives a map array of integers where <code>0</code> is an empty cell, and <code>1</code> is an obstacle, the function returns a list of coordinates which is the optimal path or <code>null</code> if such path does not exist.</p> <p><em>This code is not a thread-safe, I have no intention of making it such.</em></p> <pre><code> import java.util.LinkedList; import java.awt.Point; /** * Created by Ilya Gazman on 10/17/2018. */ public class BFS { private static final boolean DEBUG = false; public Point[] findPath(int[][] map, Point position, Point destination) { if (isOutOfMap(map, position)) { return null; } if (isOutOfMap(map, destination)) { return null; } if (isBlocked(map, position)) { return null; } if (isBlocked(map, destination)) { return null; } LinkedList&lt;Point&gt; queue1 = new LinkedList&lt;&gt;(); LinkedList&lt;Point&gt; queue2 = new LinkedList&lt;&gt;(); queue1.add(position); map[position.y][position.x] = -1; int stepCount = 2; while (!queue1.isEmpty()) { if(queue1.size() &gt;= map.length * map[0].length){ throw new Error("Map overload"); } for (Point point : queue1) { if (point.x == destination.x &amp;&amp; point.y == destination.y) { Point[] optimalPath = new Point[stepCount - 1]; computeSolution(map, point.x, point.y, stepCount - 1, optimalPath); resetMap(map); return optimalPath; } LinkedList&lt;Point&gt; finalQueue = queue2; int finalStepCount = stepCount; lookAround(map, point, (x, y) -&gt; { if (isBlocked(map, x, y)) { return; } Point e = new Point(x, y); finalQueue.add(e); map[e.y][e.x] = -finalStepCount; }); } if (DEBUG) { printMap(map); } queue1 = queue2; queue2 = new LinkedList&lt;&gt;(); stepCount++; } resetMap(map); return null; } private void resetMap(int[][] map) { for (int y = 0; y &lt; map.length; y++) { for (int x = 0; x &lt; map[0].length; x++) { if (map[y][x] &lt; 0) { map[y][x] = 0; } } } } private boolean isBlocked(int[][] map, Point p) { return isBlocked(map, p.x, p.y); } private boolean isBlocked(int[][] map, int x, int y) { int i = map[y][x]; return i &lt; 0 || i == 1; } private void printMap(int[][] map) { //noinspection ForLoopReplaceableByForEach for (int i = 0, mapLength = map.length; i &lt; mapLength; i++) { int[] aMap = map[i]; for (int x = 0; x &lt; map[0].length; x++) { System.out.print(aMap[x] + "\t"); } System.out.println(); } System.out.println("****************************************"); } private void computeSolution(int[][] map, int x, int y, int stepCount, Point[] optimalPath) { if (isOutOfMap(map, x, y) || map[y][x] == 0) { return; } if ( -stepCount != map[y][x]) { return; } Point p = new Point(x, y); optimalPath[stepCount - 1] = p; lookAround(map, p, (x1, y1) -&gt; computeSolution(map, x1, y1, stepCount - 1, optimalPath)); } private void lookAround(int[][] map, Point p, Callback callback) { callback.look(map, p.x + 1, p.y + 1); callback.look(map, p.x - 1, p.y + 1); callback.look(map, p.x - 1, p.y - 1); callback.look(map, p.x + 1, p.y - 1); callback.look(map, p.x + 1, p.y); callback.look(map, p.x - 1, p.y); callback.look(map, p.x, p.y + 1); callback.look(map, p.x, p.y - 1); } private static boolean isOutOfMap(int[][] map, Point p) { return isOutOfMap(map, p.x, p.y); } private static boolean isOutOfMap(int[][] map, int x, int y) { if (x &lt; 0 || y &lt; 0) { return true; } return map.length &lt;= y || map[0].length &lt;= x; } private interface Callback { default void look(int[][] map, int x, int y) { if (isOutOfMap(map, x, y)) { return; } onLook(x, y); } void onLook(int x, int y); } } </code></pre> <p>Usage:</p> <pre><code>public static void main(String... args) { int[][] myMap = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 1, 1, 1, 1}, {0, 0, 0, 1, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 1, 1, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0}, }; Point[] path = new BFS().findPath(myMap, new Point(8, 0), new Point(8, 2)); for (Point point : path) { System.out.println(point.x + ", " + point.y); } } </code></pre> <p>Output:</p> <pre><code>8, 0 7, 0 6, 0 5, 0 4, 1 4, 2 5, 3 6, 2 7, 2 8, 2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T14:55:21.883", "Id": "397469", "Score": "0", "body": "Is this actually working?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T15:00:41.383", "Id": "397470", "Score": "0", "body": "@Krzys...
[ { "body": "\n<p>I'm unfamiliar with the algorithm. It looks neat, but I couldn't tell you if it's optimal or not. Most optimization comes from improving the way you go about the algorithm, so I'll suggest stuff for readability.</p>\n<h1>Don't stutter</h1>\n<p>When you check <code>isOutOfMap()</code> for <code>p...
{ "AcceptedAnswerId": "206073", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T23:23:09.217", "Id": "205783", "Score": "3", "Tags": [ "java", "algorithm", "pathfinding", "breadth-first-search" ], "Title": "Java breadth-first search for finding the shortest path on a 2D grid with obstacles" }
205783
<p>I am going through Elements of Programming Interview by Aziz, Lee and Prakash one of the questions is how to determine if a string can be permuted to a palindrome. For example <code>edified</code> can be permuted to <code>deified</code> and now its a palindrome.</p> <p>So my first implementation is this:</p> <pre><code>bool CanFormPalindrome(const string&amp; s) { std::unordered_map&lt;char, int&gt; letter_count; for(char c : s) { letter_count[c]++; } int odd_letter_count = 0; for(std::pair&lt;char, int&gt; letter : letter_count) { if(letter.second%2 != 0) { odd_letter_count++; } } return odd_letter_count &lt;= 1; } </code></pre> <p>After I passed all the tests I saw the book's cleaner and sleeker implementation (compared to my implementation) which is:</p> <blockquote> <pre><code>bool CanFormPalindrome(const string&amp; s) { std::unordered_set&lt;char&gt; char_counter; for(char c : s) { if(char_counter.count(c)) { char_counter.erase(c); } else { char_counter.insert(c); } } return char_counter.size() &lt;= 1; } </code></pre> </blockquote> <p>When I saw the time difference the tester timed my test at around 30 ms and the book's implementation at around 100 ms. I am wondering why my implementation is faster than the book's. My suspicion is that the calls to <code>unordered_set</code>'s <code>count</code>, <code>erase</code>, and <code>insert</code> probably is the main bottle neck as opposed to just insert it just once and increment the value if it exists. </p> <p>Another question is if you were to ask this on an interview would you care about the space time complexity over speed? Obviously the unordered_set is far more space efficient than the unordered_map, but if its for greater performance gain can we take up more space?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T10:09:16.210", "Id": "396951", "Score": "1", "body": "It would be great if you would provide the benchmarking code, and some data about the benchmarking process so we could compare with own versions." }, { "ContentLicense": ...
[ { "body": "<p>I much prefer your solution. It's easy to read and straightforward. The difference in size between the 2 is probably not that much. Their code has an <code>unordered_set</code> with a few elements in it. Your code has an <code>unordered_map</code> with likely 26 elements in it. We're talking about...
{ "AcceptedAnswerId": "205786", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-17T23:56:21.180", "Id": "205784", "Score": "10", "Tags": [ "c++", "performance", "palindrome" ], "Title": "Determining if a string can be permuted to a palindrome" }
205784
<p>I am new to programming and started learning with Automate the Boring Stuff with Python. I just completed chapter 3's <a href="https://automatetheboringstuff.com/chapter3/" rel="noreferrer">"Collatz sequence" project</a>.</p> <p>I was wondering what would you do differently and why? Trying to learn how to think like a programmer and become more efficient.</p> <pre><code>def collatz(number): global nextNumber if number % 2 == 0: nextNumber = (number//2) print(nextNumber) else: nextNumber = (3*number+1) print(nextNumber) print('Type in an integer.') integer=input() if integer.isdigit() ==True: collatz(int(integer)) while nextNumber !=1: collatz(nextNumber) while integer.isdigit() != True : print('Please try again.') integer=input() collatz(int(integer)) while nextNumber !=1: collatz(nextNumber) print('Thank you!') </code></pre>
[]
[ { "body": "<p>One thing you’ll want to learn is not to repeat yourself, when coding. </p>\n\n<p>Consider:</p>\n\n<pre><code>def collatz(number):\n global nextNumber\n if number % 2 == 0:\n nextNumber = number//2\n print(nextNumber)\n else:\n nextNumber = 3*number+1\n print(...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T02:01:39.763", "Id": "205785", "Score": "15", "Tags": [ "python", "collatz-sequence" ], "Title": "Automate the Boring Stuff with Python - The Collatz sequence project" }
205785
<p>I've created a very plain version of <strong><em>page flip onscroll</em></strong>. I made it to look like turning the pages of a book. It looks OK on browsers I have (Firefox 52.9, Chrome 49, IE8). Though the <a href="https://caniuse.com/#feat=transforms3d" rel="nofollow noreferrer">effect doesn't work on IE8</a> and similar old browsers, it still doesn't look messy. I want to use this presentation method on a website.</p> <ul> <li>Are there any parts of the code that I need to create a <strong>fallback</strong> for?</li> <li>Could this page be faster?</li> <li>Are there any <strong>accessibility</strong> concerns?</li> <li>Are there any '<strong>Best</strong> Coding <strong>Practices</strong>' that I need to include here?</li> <li>Any other <strong>improvements</strong>?</li> </ul> <p>New Question:</p> <ul> <li>Will this effect make viewing a page <strong>uncomfortable on touch devices</strong>?</li> </ul> <p>CodePen: <a href="https://codepen.io/ZechariahRaman/pen/NOYbXL/" rel="nofollow noreferrer">https://codepen.io/ZechariahRaman/pen/NOYbXL/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var h = 0, r = 1, y = 0, yh = 1, section = document.getElementsByTagName("section"), d = section[0]; function load() { h = window.innerHeight; r = 180 / h; for (var i = section.length - 1; i &gt;= 0; i--) { section[i].style.position = "fixed"; } } function turn() { y = window.pageYOffset; if (y == 0) { section[0].style.transform = "initial"; } if (y &gt;= 0 &amp;&amp; y &lt; h) { yh = y; d = section[0]; section[1].style.transform = "initial"; } if (y &gt;= h &amp;&amp; y &lt; h * 2) { yh = y - h; d = section[1]; } d.style.transform = "perspective(" + h * 5 + "px) rotate3d(1,0,0," + r * yh + "deg)"; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; box-sizing: border-box; } body { background-color: #274171; height: 300vh; } section { transform-origin: top; transition: all 0.3s ease; } #p1 { z-index: 3; background-color: #d9bd75; } #p2 { z-index: 2; background-color: #67a893; } #p3 { z-index: 1; background-color: #353cc9; } .page { margin: 1vh 9vw; height: 98vh; width: 80vw; display: flex; } p { margin: auto; font-size: 5em; padding: 0.5em; color: #fff; background-color: rgba(19, 41, 79, 0.7); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body onload="load()" onresize="load()" onscroll="turn()"&gt; &lt;section id="p1" class="page"&gt; &lt;p&gt;Hi&lt;/p&gt; &lt;/section&gt; &lt;section id="p2" class="page"&gt; &lt;p&gt;Short Story&lt;/p&gt; &lt;/section&gt; &lt;section id="p3" class="page"&gt; &lt;p&gt;The End&lt;/p&gt; &lt;/section&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T07:17:13.090", "Id": "396918", "Score": "0", "body": "\"It works OK on browsers I have (Firefox, Chrome, IE8). But I want to use this presentation method on a website.\" Yes, websites are usually viewed with a browser. Is there a pr...
[ { "body": "<h3>Declare variables in the smallest possible scope</h3>\n\n<p>It's recommended to declare variables in the smallest scope where they are needed.\nThat way, the variable will not be visible where it should not be,\nand therefore it cannot be modified accidentally by mistake.\nIt also makes understan...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T06:59:40.197", "Id": "205793", "Score": "3", "Tags": [ "javascript", "performance", "css", "animation", "user-interface" ], "Title": "Plain Page Flip Effect" }
205793
<p>What I want my code to do is that if we're on day 3 then we want to increase the week by 1. But if week number is 3 we want to reset the week to 1. The code below works but can it be simplified?</p> <p>Java code</p> <pre><code>public int calculateNextWeek(int week, int day) { if (day == 3) { if (week == 3) { return 1; } else { return week + 1; } } return week; } </code></pre> <p>Example data and expected output:</p> <pre><code>day = 3, week = 1 =&gt; 2 day = 3, week = 3 =&gt; 1 day = 1, week = 1 =&gt; 1 day = 1, week = 3 =&gt; 3 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T08:35:37.753", "Id": "396935", "Score": "0", "body": "Should be posted on [StackOverflow](https://stackoverflow.com/). CodeReview is for improving working code, not fixing broken code." }, { "ContentLicense": "CC BY-SA 4.0",...
[ { "body": "<p>You can use the modulo operator to wrap around your <code>week</code> counter:</p>\n\n<pre><code>public int calculateNextWeek(int week, int day) {\n if (day == 3) {\n return (week % 3) + 1;\n }\n\n return week;\n}\n</code></pre>\n", "comments": [], "meta_data": { "Com...
{ "AcceptedAnswerId": "205802", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T08:18:39.500", "Id": "205797", "Score": "1", "Tags": [ "java" ], "Title": "Calculation of next week number (constrained by max 3) with rollover" }
205797
<p>The rules of the game are pretty simple. I'll put it here in case people don't know them </p> <p>It's a two player game hand game where they alternate being a batsman and a bowler. Who decides to do what initially is determined by a toss.</p> <p>These are the hand gestures which has a corresponding score <a href="https://i.stack.imgur.com/B5q6V.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B5q6V.jpg" alt="enter image description here"></a></p> <ul> <li>Both the batsman and the bowler throw their hands at the same time to one of the poses shown in the diagram.</li> <li>The runs of each pose are added to the batsman’s score.</li> <li>If both of them throw the same pose, the batsman is out and the score he scored is the target for the next batsman</li> </ul> <p>I tried to re-create this game in the most OO way possible. </p> <p>Here is my <code>Player</code> class</p> <pre><code>public class Player { public string Name { get; set; } public int TotalScore { get; private set; } public List&lt;int&gt; Scores { get; private set; } private static Random random; internal CoinOptions coinOption; public Player(string name) { random = new Random(); Name = name; Scores = new List&lt;int&gt;(); } public int Play() { return random.Next(6); } internal void AddScore(int score) { this.TotalScore += score; this.Scores.Add(score); } } </code></pre> <p><code>Coin</code> class for the Toss</p> <pre><code>internal static class Coin { private static Random random = new Random(); public static CoinOptions FlipCoin() { var probability = random.Next(1); return (CoinOptions)probability; } } </code></pre> <p>And the core logic in the <code>HandCricketGame</code> class</p> <pre><code>public class HandCricket { Player playerOne, playerTwo; private Player batsman, bowler; private int inningsCount = 0; public HandCricket(Player one, Player two) { playerOne = one; playerTwo = two; } public GameResultSummary Play() { var tossResult = Toss(); var gameResult = new GameResultSummary() { TossResult = tossResult }; setBatsamanAndBowler(tossResult); gameResult.Innings.Add(new Innings() { Batsman = batsman, Bowler = bowler }); playInnings(); inningsCount += 1; switchBatsmanAndBowler(); gameResult.Innings.Add(new Innings() { Batsman = batsman, Bowler = bowler }); playInnings(); gameResult.GameResult.DoesGameHaveResult = true; if (batsman.TotalScore &gt; bowler.TotalScore) { gameResult.GameResult.Winner = batsman; } else if (batsman.TotalScore &lt; bowler.TotalScore) { gameResult.GameResult.Winner = bowler; } else { gameResult.GameResult.DoesGameHaveResult = false; } return gameResult; } private TossResult Toss() { playerOne.coinOption = CoinOptions.Heads; playerTwo.coinOption = CoinOptions.Tails; var winningFlip = Coin.FlipCoin(); var winningPlayer = winningFlip == playerOne.coinOption ? playerOne : playerTwo; return new TossResult() { TossWinningPlayer = winningPlayer, TossWinningPlayerSelection = PlayingOptions.Bat }; } private void playInnings() { int batsmanScore, bowlingScore; while(true) { batsmanScore = batsman.Play(); bowlingScore = bowler.Play(); if((batsmanScore == bowlingScore) || (inningsCount &gt; 0 &amp;&amp; batsman.TotalScore &gt; bowler.TotalScore)) { break; } batsman.AddScore(batsmanScore); } } private void switchBatsmanAndBowler() { var tempObject = batsman; batsman = bowler; bowler = tempObject; } private void setBatsamanAndBowler(TossResult tossResult) { if(tossResult.TossWinningPlayerSelection == PlayingOptions.Bat) { batsman = tossResult.TossWinningPlayer; bowler = getOpponentPlayerObject(tossResult.TossWinningPlayer); } else { bowler = tossResult.TossWinningPlayer; batsman = getOpponentPlayerObject(tossResult.TossWinningPlayer); } } private Player getOpponentPlayerObject(Player firstPlayer) { if (ReferenceEquals(playerOne, firstPlayer)) { return playerTwo; } return playerOne; } } </code></pre> <p><code>GameResultSummary</code> Class</p> <pre><code>public class GameResultSummary { internal TossResult TossResult { get; set; } internal GameResult GameResult { get; set; } internal List&lt;Innings&gt; Innings { get; set; } public GameResultSummary() { Innings = new List&lt;Innings&gt;(); GameResult = new GameResult(); } public void GameSummary() { Console.WriteLine(string.Format("Player {0} won the toss and elected to {1}", TossResult.TossWinningPlayer.Name, TossResult.TossWinningPlayerSelection.ToString())); foreach (var player in Innings) { Console.WriteLine(string.Format("Player {0} played and scored {1}", player.Batsman.Name, player.Batsman.TotalScore)); } if(GameResult.DoesGameHaveResult) { Console.WriteLine(string.Format("{0} won the game", GameResult.Winner.Name)); } else { Console.WriteLine(string.Format("Game was drawn")); } } } </code></pre> <p><code>GameResult</code> class </p> <pre><code>class GameResult { internal Player Winner { get; set; } internal bool DoesGameHaveResult { get; set; } } </code></pre> <p><code>Innings</code> Class</p> <pre><code>public class Innings { public Player Batsman { get; set; } public Player Bowler { get; set; } } </code></pre> <p><code>Toss Result</code> Class</p> <pre><code>public class TossResult { public Player TossWinningPlayer { get; set; } public PlayingOptions TossWinningPlayerSelection { get; set; } } </code></pre> <p>And a bunch of Enums</p> <pre><code>public enum CoinOptions { Heads = 0, Tails = 1 } public enum PlayingOptions { Bat = 0, Bowl = 1 } </code></pre> <p>The <code>handCricketGame</code> and the <code>Player</code> class are the most important ones here. What started as an OO approach I feel looks less like it when it is done. </p> <p>The majority of it has to do with the <code>Play</code> method. Could you please suggest on how it can be written in a more OO way</p>
[]
[ { "body": "<p><strong>Using Better Abstractions</strong> </p>\n\n<p><strong>Player Class</strong> </p>\n\n<p>The <code>Player</code> class has properties that do not really belong there. The <code>Scores</code> property is more suited as a property in the <code>HandCricketGame</code> class since the player can ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T09:15:47.820", "Id": "205806", "Score": "4", "Tags": [ "c#", "object-oriented", "game" ], "Title": "Simple Hand Cricket Game in Object Oriented Way" }
205806
<p>This is my first Go project. Coming from a Java developer background, this code just smells very bad. But, cannot figure out better way to do this.</p> <p>It's a small app to find suggested flight destinations based on one or more origins (by their airport-codes, called <code>codes</code>below). Basically finding flights that have the same destination and about the same arrival times.</p> <pre><code>// SuggestDestinations takes a list of origin airport codes, an earliest arrival time and a latest arrival time and // returns a map, where the destination is the key, and the suggested flights. func (service *FlightService) SuggestDestinations(codes []string, earliestArrival, latestArrival time.Time) (destinationMap map[string][]internal.Flight, err error) { rows, err := service.db.Query(selectFlightsSQL, pq.Array(codes), earliestArrival, latestArrival) if err != nil { return nil, err } defer rows.Close() var m map[string][]internal.Flight m = make(map[string][]internal.Flight) for rows.Next() { var a internal.Flight var origin, destination, airline string if e := rows.Scan(&amp;origin, &amp;destination, &amp;airline, &amp;a.Departure, &amp;a.Arrival); err != nil { return nil, e } a.Origin, err = service.GetAirport(origin) a.Destination, err = service.GetAirport(destination) a.Airline, err = service.GetAirline(airline) // Filter out destinations which is one of the origins if !contains(codes, a.Destination.Code) { m[a.Destination.Code] = append(m[a.Destination.Code], a) } } // Delete destinations for which there are not flights from every given origin for k := range m { if !containsAllCodes(m[k], codes) { delete(m, k) } } return m, nil } </code></pre> <p>Where containsAllCodes looks like this:</p> <pre><code>func containsAllCodes(flights []internal.Flight, codes []string) bool { containsAllOrigin := true for _, c := range codes { containsOrigin := false for _, f := range flights { containsOrigin = containsOrigin || f.Origin.Code == c } containsAllOrigin = containsAllOrigin &amp;&amp; containsOrigin } return containsAllOrigin } </code></pre>
[]
[ { "body": "<blockquote>\n <p>... this code just smells very bad. But, cannot figure out better way\n to do this.</p>\n</blockquote>\n\n<p>Let's look at a more complete, more fragrant implementation.</p>\n\n<hr>\n\n<p>For data, you are using PostgreSQL: <code>db.Query(selectFlightsSQL, pq.Array(codes), ...)</c...
{ "AcceptedAnswerId": "206340", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T10:00:41.917", "Id": "205807", "Score": "1", "Tags": [ "go" ], "Title": "Finding suggested flight destinations from database in Golang" }
205807
<p>This Java code project was submitted for a job opportunity but was marked down for showing "bad habits that could be difficult to unlearn" but I am mystified by what this means. Any takers please. How could it be approached differently or improved.</p> <p>I have removed any reference to the company involved, but the challenge was framed this way:</p> <h3>Problem description</h3> <blockquote> <p>An employee survey has been conducted, and you've been asked to figure out useful insights from it. You are given the data as a flat CSV file for all employees across the company, containing at least the following columns:</p> <pre><code>divisionId, teamId, managerId, employeeId, firstName, lastName, birthdate </code></pre> <p>For example, one record (row) of the CSV file looks like the following:</p> <pre><code>1,7,3,24,Jon,Snow,1986-12-26 </code></pre> <h3>Objective</h3> <p>Based on the structure above, write a piece of code which takes the CSV above as input, and creates a JSON object that looks like the following:</p> <pre><code>{ "divisions": { "#divisionId": { "teams": { "#teamId": { "managers": { "#managerId": { "employees": { "#employeeId": { "id": "#employeeId", "firstName": "Jon", "lastName": "Snow", "birthdate": "1986-12-26" } } } } } } } } } </code></pre> <p>NOTE: You can find the data set as <code>data.csv</code> in the <code>/data</code> directory.</p> <h3>Questions</h3> <ol> <li>What is the big-O runtime complexity of the algorithm you’ve just written?</li> <li>Can you write the code such that all IDs are in ascending order in the JSON output?</li> <li>Can you create this such that the list of employees is sorted by their full name? (bonus points if you create a mechanism for arbitrary sort order, e.g., variable/multiple sort fields, ascending and/or descending order)</li> <li>[BONUS] Can you calculate the average age across the company, divisions, teams, and managers?</li> </ol> <p><strong>NOTE:</strong> for each of the extra questions, you can create different command-line arguments that changes the mode of the application. However, this is only a suggestion, and are you free to take any alternative approach you may wish.</p> <h3>Requirements</h3> <p>Unless explicitly requested otherwise, we expect the following to be used:</p> <ul> <li>Java 8</li> <li>Gradle as the build system</li> <li>Any necessary libraries (e.g., Jackson for JSON)</li> </ul> </blockquote> <h3>Code:</h3> <p>CSVData.Java</p> <pre><code>package org.challenge.csv; import java.util.Arrays; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; /* * Base class for CSV data * */ public class CSVData { private transient final String[] fieldsInCSVHeader; protected CSVData(String[] fieldsInCSVHeader) { this.fieldsInCSVHeader = fieldsInCSVHeader; } @JsonIgnore public List&lt;String&gt; getHeaderFields() { return Arrays.asList(fieldsInCSVHeader); } public enum SortDirection { ASCENDING, DESCENDING } } </code></pre> <p>CSVParser.java</p> <pre><code>package org.challenge.csv; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.List; import java.util.Objects; import static java.util.stream.Collectors.*; import org.challenge.csv.survey.SurveyCSVParser; import org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData; /** * Base class for CSV parsers * */ public class CSVParser { private final File csvFile; private final short minimumFieldsPerLine; private final String seperatorOfFields; private List&lt;String&gt; linesOfCSVFile; protected CSVParser(File csvFile, short minimumFieldsPerLine, String seperatorOfFields) { this.csvFile = csvFile; this.minimumFieldsPerLine = minimumFieldsPerLine; this.seperatorOfFields = seperatorOfFields; } public static Parser createSurveyParser(File csvFile, SurveyCSVData.Employee.SortOrder order, CSVData.SortDirection direction) { Objects.requireNonNull(csvFile); return new SurveyCSVParser(csvFile, order, direction); } public static Parser createSurveyParser(File csvFile) { return new SurveyCSVParser(csvFile, SurveyCSVData.Employee.SortOrder.ORIGINAL, CSVData.SortDirection.ASCENDING); } protected boolean fileExists() { return csvFile.exists() &amp;&amp; csvFile.canRead(); } protected boolean fileIsCorrectlyFormatted() { readFile(); return linesOfCSVFile.size() &gt; 0 &amp;&amp; linesOfCSVFile.get(0).split(seperatorOfFields).length &gt;= minimumFieldsPerLine; } protected List&lt;String&gt; fileLines() { readFile(); return linesOfCSVFile.stream().skip(1).collect(toList()); } private synchronized void readFile() { try { if (null == linesOfCSVFile) { if (true == fileExists()) linesOfCSVFile = Files.readAllLines(csvFile.toPath()); // NOTE - BufferedReader may be preferred for very large files, can then process line by line or in chunks... } } catch (IOException e) { // NOTE - Retry in a limited loop, ... throw new RuntimeException("FAILED to read file content"); } } } </code></pre> <p>Parser.java</p> <pre><code>package org.challenge.csv; import java.util.Optional; /* * Interface defining CSV parser functions * */ public interface Parser { /** * Parse CSV file into an object structure * @return CSV data object */ Optional&lt;CSVData&gt; parse(); } </code></pre> <p>JSONWriter.java</p> <pre><code>package org.challenge.json; import org.challenge.csv.CSVData; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Class for writing JSON data from object graph via Jackson libraries * */ public final class JSONWriter { private final CSVData csvData; public JSONWriter(CSVData csvData) { this.csvData = csvData; } public String write() throws JsonProcessingException { ObjectMapper objectToJsonMapper = new ObjectMapper(); String jsonStringRepresentation = objectToJsonMapper.writeValueAsString(csvData); return jsonStringRepresentation; } } </code></pre> <p>SurveyCSVParser.java</p> <pre><code>package org.challenge.csv.survey; import java.io.File; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.StringTokenizer; import java.util.TreeMap; import org.challenge.csv.CSVData; import org.challenge.csv.CSVParser; import org.challenge.csv.Parser; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * Class for parsing CSV data related to employee survey * */ public final class SurveyCSVParser extends CSVParser implements Parser { private static final short MIN_TOKENS_PER_LINE = 7; private static final String SEPERATOR_OF_TOKENS = ","; private final SurveyCSVData.Employee.SortOrder sortOrderOfDataOrEmployees; private final CSVData.SortDirection sortDirectionOfEmployees; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-M-d"); public SurveyCSVParser(File csvFile, SurveyCSVData.Employee.SortOrder sortOrderOfDataOrEmployees, CSVData.SortDirection sortDirectionOfEmployees) { super(csvFile, MIN_TOKENS_PER_LINE, SEPERATOR_OF_TOKENS); this.sortOrderOfDataOrEmployees = sortOrderOfDataOrEmployees; this.sortDirectionOfEmployees = sortDirectionOfEmployees; } @Override public Optional&lt;CSVData&gt; parse() { SurveyCSVData csvDataParsed = null; if (fileExists() &amp;&amp; fileIsCorrectlyFormatted()) { List&lt;String&gt; linesOfCSV = fileLines(); SurveyCSVData csvData = new SurveyCSVData(sortOrderOfDataOrEmployees); try { if (SurveyCSVData.Employee.SortOrder.ORIGINAL != sortOrderOfDataOrEmployees) linesOfCSV.parallelStream().forEach(l -&gt; processLineOfCSV(l, csvData, sortOrderOfDataOrEmployees, sortDirectionOfEmployees)); else linesOfCSV.stream().forEach(l -&gt; processLineOfCSV(l, csvData, sortOrderOfDataOrEmployees, sortDirectionOfEmployees)); csvDataParsed = csvData; } catch (Exception e) { throw new RuntimeException("FAILED to parse CSV file"); // NOTE - Should a "bad" line prevent the remainder of the parse? } } return Optional.ofNullable(csvDataParsed); } private static void processLineOfCSV(String line, SurveyCSVData data, SurveyCSVData.Employee.SortOrder sortOrderOfDataOrEmployees, CSVData.SortDirection sortDirectionOfEmployees) { StringTokenizer tokenizer = new StringTokenizer(line, SEPERATOR_OF_TOKENS); short indexOfTokenFound = 0; String divisionId = null, teamId = null, managerId = null, employeeId = null, lastName = null, firstName = null, birthdate = null; while (tokenizer.hasMoreTokens() &amp;&amp; indexOfTokenFound &lt; MIN_TOKENS_PER_LINE) { String token = tokenizer.nextToken(); switch (indexOfTokenFound) { case 0: divisionId = token; break; case 1: teamId = token; break; case 2: managerId = token; break; case 3: employeeId = token; break; case 4: firstName = token; break; case 5: lastName = token; break; case MIN_TOKENS_PER_LINE-1: birthdate = token; break; default: assert false; } indexOfTokenFound++; } if (indexOfTokenFound &gt;= MIN_TOKENS_PER_LINE) buildSurveyData(divisionId, teamId, managerId, employeeId, firstName, lastName, birthdate, data, sortOrderOfDataOrEmployees, sortDirectionOfEmployees); } private static synchronized void buildSurveyData(String divisionId, String teamId, String managerId, String employeeId, String firstName, String lastName, String birthdate, SurveyCSVData data, SurveyCSVData.Employee.SortOrder sortOrderOfDataOrEmployees, CSVData.SortDirection direction) { Objects.requireNonNull(divisionId); Objects.requireNonNull(teamId); Objects.requireNonNull(managerId); Objects.requireNonNull(employeeId); Objects.requireNonNull(firstName); Objects.requireNonNull(lastName); Objects.requireNonNull(birthdate); Integer divisionIdBox = Integer.parseInt(divisionId); Integer teamIdBox = Integer.parseInt(teamId); Integer managerIdBox = Integer.parseInt(managerId); Integer employeeIdBox = Integer.parseInt(employeeId); if (false == data.divisions.containsKey(divisionIdBox)) data.divisions.put(divisionIdBox, new SurveyCSVData.Division(divisionIdBox, sortOrderOfDataOrEmployees)); SurveyCSVData.Division division = data.divisions.get(divisionIdBox); if (false == division.teams.containsKey(teamIdBox)) division.teams.put(teamIdBox, division.createTeam(teamIdBox)); SurveyCSVData.Team team = division.teams.get(teamIdBox); if (false == team.managers.containsKey(managerIdBox)) team.managers.put(managerIdBox, team.createManager(managerIdBox, direction)); SurveyCSVData.Manager manager = team.managers.get(managerIdBox); if (false == manager.employees.containsKey(employeeIdBox)) manager.employees.put(employeeIdBox, manager.createEmployee(employeeIdBox, firstName, lastName, birthdate)); // NOTE - Duplicates will not be added more than once } /** * * Class representing survey data * */ public final static class SurveyCSVData extends CSVData { private static final short VERSION = 1; // NOTE - Good idea to apply version to data structures private Map&lt;Integer, Division&gt; divisions; public SurveyCSVData(Employee.SortOrder sortOrderOfDataOrEmployees) { super(new String[] {"divisionId", "teamId", "managerId", "employeeId", "lastName", "firstName", "birthdate"}); if (Employee.SortOrder.ORIGINAL == sortOrderOfDataOrEmployees) divisions = new LinkedHashMap &lt;&gt;(); else divisions = new TreeMap&lt;&gt;(); } public void addDivision(Integer id, Division division) { Objects.requireNonNull(id); Objects.requireNonNull(division); divisions.put(id, division); } public Map&lt;Integer, Division&gt; getDivisions() { return Collections.unmodifiableMap(divisions); } /** * Class representing division in survey data */ public final static class Division { private Map&lt;Integer, Team&gt; teams; private transient final Integer id; private final Employee.SortOrder sortOrderOfDataOrEmployees; public Division(Integer id, Employee.SortOrder sortOrderOfDataOrEmployees) { this.id = id; this.sortOrderOfDataOrEmployees = sortOrderOfDataOrEmployees; if (Employee.SortOrder.ORIGINAL == sortOrderOfDataOrEmployees) teams = new LinkedHashMap &lt;&gt;(); else teams = new TreeMap&lt;&gt;(); } @JsonIgnore public Integer getId() { return id; } public void addTeam(Integer id, Team team) { Objects.requireNonNull(id); Objects.requireNonNull(team); teams.put(id, team); } public Team createTeam(Integer id) { return new Team(id, sortOrderOfDataOrEmployees); } public Map&lt;Integer, Team&gt; getTeams() { return Collections.unmodifiableMap(teams); } } /** * Class representing team in survey data */ public final static class Team { private Map&lt;Integer, Manager&gt; managers; private transient final Integer id; private final Employee.SortOrder sortOrderOfDataOrEmployees; public Team(Integer id, Employee.SortOrder sortOrderOfDataOrEmployees) { this.id = id; this.sortOrderOfDataOrEmployees = sortOrderOfDataOrEmployees; if (Employee.SortOrder.ORIGINAL == sortOrderOfDataOrEmployees) managers = new LinkedHashMap &lt;&gt;(); else managers = new TreeMap&lt;&gt;(); } @JsonIgnore public Integer getId() { return id; } public void addManager(Integer id, Manager manager) { Objects.requireNonNull(id); Objects.requireNonNull(manager); managers.put(id, manager); } public Manager createManager(Integer id, CSVData.SortDirection sortDirectionOfEmployees) { return new Manager(id, sortOrderOfDataOrEmployees, sortDirectionOfEmployees); } public Map&lt;Integer, Manager&gt; getManagers() { return Collections.unmodifiableMap(managers); } } /** * Class representing manager in survey data */ public final static class Manager { private final Employee.SortOrder sortOrderOfDataOrEmployees; private final CSVData.SortDirection sortDirectionOfEmployees; private transient Map&lt;Integer, Employee&gt; employees; private transient final Integer id; public Manager(Integer id, Employee.SortOrder sortOrderOfDataOrEmployees, CSVData.SortDirection sortDirectionOfEmployees) { this.id = id; this.sortOrderOfDataOrEmployees = sortOrderOfDataOrEmployees; this.sortDirectionOfEmployees = sortDirectionOfEmployees; if (Employee.SortOrder.ORIGINAL == sortOrderOfDataOrEmployees) employees = new LinkedHashMap &lt;&gt;(); else employees = new TreeMap&lt;&gt;(); } @JsonIgnore public Integer getId() { return id; } public void addEmployee(Integer id, Employee employee) { Objects.requireNonNull(id); Objects.requireNonNull(employee); employees.put(id, employee); } public Employee createEmployee(Integer id, String firstName, String lastName, String birthdate) { return new Employee(id, firstName, lastName, birthdate); } public Map&lt;Integer, Employee&gt; getEmployees() { return Collections.unmodifiableMap(employees); } @JsonProperty("employees") public Map&lt;Integer, Employee&gt; getOrderedEmployees() { Map&lt;Integer, Employee&gt; orderedMapOfEmployees; if ((Employee.SortOrder.ID == sortOrderOfDataOrEmployees &amp;&amp; CSVData.SortDirection.ASCENDING == sortDirectionOfEmployees) || Employee.SortOrder.ORIGINAL == sortOrderOfDataOrEmployees) orderedMapOfEmployees = employees; else { Comparator&lt;Integer&gt; valueComparator = (k1, k2) -&gt; { Employee e1 = employees.get(k1); Employee e2 = employees.get(k2); int compare = 0; if(null != e1 &amp;&amp; null != e2) { switch (sortOrderOfDataOrEmployees) { case ID: compare = Integer.valueOf(e1.id).compareTo(Integer.valueOf(e2.id)); break; case LASTNAME: compare = e1.lastName.compareTo(e2.lastName); break; case FIRSTNAME: compare = e1.firstName.compareTo(e2.firstName); break; case BIRTHDATE: compare = e1.birthdate.compareTo(e2.birthdate); break; default: assert false; break; } if (CSVData.SortDirection.DESCENDING == sortDirectionOfEmployees) compare = -compare; } else throw new NullPointerException("Comparator does not support null values"); return compare; }; Map&lt;Integer, Employee&gt; sortedMapOfEmployees = new TreeMap&lt;&gt;(valueComparator); sortedMapOfEmployees.putAll(employees); orderedMapOfEmployees = sortedMapOfEmployees; } return orderedMapOfEmployees; } @Override public String toString() { return Objects.toString(employees); } } /** * Class representing employee in survey data */ public final static class Employee { private final int id; private final String firstName; private final String lastName; private final String birthdate; private transient final LocalDate birthdateDateType; public Employee(int id, String firstName, String lastName, String birthdate) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.birthdate = birthdate; this.birthdateDateType = LocalDate.parse(birthdate, FORMATTER); // NOTE - Formatter is not thread safe } public int getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getBirthdate() { return birthdate; } @JsonIgnore public LocalDate getBirthdateDateType() { return birthdateDateType; } @Override public String toString() { return "(id='" + id + "', firstName='" + firstName + "', lastName='" + lastName + "', birthdate='" + birthdate + "')"; } public enum SortOrder { ORIGINAL, ID, LASTNAME, FIRSTNAME, BIRTHDATE } } } } </code></pre> <p>AgeCalculator.java</p> <pre><code>package org.challenge.analysis; import java.time.Period; import java.util.Optional; /** * Interface for obtaining average age from survey data at different scopes * */ public interface AgeCalculator { /** * Calculate average age of employees within a specified scope * @param scope enum value * @param id of division, team or manager, can be not present for company scope * @return Period of time showing the average age * @exception AgeCalculatorException if id is not present for non-company scope */ Period getAverageAge(Scope scope, Optional&lt;Integer&gt; id) throws AgeCalculatorException; public enum Scope { COMPANY, DIVISION, TEAM, MANAGER } /** * Exception class for age calculator */ class AgeCalculatorException extends Exception { private static final long serialVersionUID = 1L; AgeCalculatorException(String message) { super(message); } AgeCalculatorException(String message, Exception inner) { super(message, inner); } } } </code></pre> <p>SurveyAnalyzer.java</p> <pre><code>package org.challenge.analysis; import java.time.Duration; import java.time.LocalDate; import java.time.Period; import java.util.Objects; import java.util.Optional; import org.challenge.csv.survey.SurveyCSVParser; /** * Class implementing average age calculations on survey data * */ public final class SurveyAnalyzer implements AgeCalculator { private final SurveyCSVParser.SurveyCSVData surveyData; public SurveyAnalyzer(SurveyCSVParser.SurveyCSVData surveyData) { this.surveyData = surveyData; } @Override public Period getAverageAge(Scope scope, Optional&lt;Integer&gt; id) throws AgeCalculator.AgeCalculatorException { if (AgeCalculator.Scope.COMPANY != scope &amp;&amp; (null == id || false == id.isPresent())) throw new AgeCalculator.AgeCalculatorException("For non-COMPANY scope an identifier is required"); long totalDaysAgeOfEmployeesInScope, totalEmployeesInScope; switch (scope) { default: //case COMPANY: totalDaysAgeOfEmployeesInScope = surveyData.getDivisions().values().parallelStream() .flatMap(d -&gt; d.getTeams().values().parallelStream()) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .mapToLong(e -&gt; Duration.between(e.getBirthdateDateType().atStartOfDay(), LocalDate.now().atStartOfDay()).toDays()).sum(); totalEmployeesInScope = surveyData.getDivisions().values().parallelStream() .flatMap(d -&gt; d.getTeams().values().parallelStream()) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .count(); break; case DIVISION: totalDaysAgeOfEmployeesInScope = surveyData.getDivisions().values().parallelStream() .filter(d -&gt; Objects.equals(d.getId(), id.get())) .flatMap(d -&gt; d.getTeams().values().parallelStream()) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .mapToLong(e -&gt; Duration.between(e.getBirthdateDateType().atStartOfDay(), LocalDate.now().atStartOfDay()).toDays()).sum(); totalEmployeesInScope = surveyData.getDivisions().values().parallelStream() .filter(d -&gt; Objects.equals(d.getId(), id.get())) .flatMap(d -&gt; d.getTeams().values().parallelStream()) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .count(); break; case TEAM: totalDaysAgeOfEmployeesInScope = surveyData.getDivisions().values().parallelStream() .flatMap(d -&gt; d.getTeams().values().parallelStream()) .filter(t -&gt; Objects.equals(t.getId(), id.get())) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .mapToLong(e -&gt; Duration.between(e.getBirthdateDateType().atStartOfDay(), LocalDate.now().atStartOfDay()).toDays()).sum(); totalEmployeesInScope = surveyData.getDivisions().values().parallelStream() .flatMap(d -&gt; d.getTeams().values().parallelStream()) .filter(t -&gt; Objects.equals(t.getId(), id.get())) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .count(); break; case MANAGER: totalDaysAgeOfEmployeesInScope = surveyData.getDivisions().values().parallelStream() .flatMap(d -&gt; d.getTeams().values().parallelStream()) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .filter(m -&gt; Objects.equals(m.getId(), id.get())) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .mapToLong(e -&gt; Duration.between(e.getBirthdateDateType().atStartOfDay(), LocalDate.now().atStartOfDay()).toDays()).sum(); totalEmployeesInScope = surveyData.getDivisions().values().parallelStream() .flatMap(d -&gt; d.getTeams().values().parallelStream()) .flatMap(t -&gt; t.getManagers().values().parallelStream()) .filter(m -&gt; Objects.equals(m.getId(), id.get())) .flatMap(m -&gt; m.getEmployees().values().parallelStream()) .count(); break; } long averageAgeDays = 0; if (totalEmployeesInScope &gt; 0) averageAgeDays = (long)Math.floor(totalDaysAgeOfEmployeesInScope / totalEmployeesInScope); // NOTE - Some rounding down here to nearest day over all employees in scope Period averageAge = Period.between(LocalDate.now(), LocalDate.now().plusDays(averageAgeDays)); return averageAge; } } </code></pre> <p>Task1.java</p> <pre><code>package org.challenge; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Period; import java.util.Objects; import java.util.Optional; import org.challenge.analysis.AgeCalculator; import org.challenge.analysis.AgeCalculator.AgeCalculatorException; import org.challenge.analysis.SurveyAnalyzer; import org.challenge.csv.CSVData; import org.challenge.csv.CSVParser; import org.challenge.csv.Parser; import org.challenge.csv.survey.SurveyCSVParser; import org.challenge.json.JSONWriter; /** * Main class with entry point * */ class Task1 { /** * Main entry point * @param args */ public static void main(String[] args) { try { // Path to supplied CSV data file Path csvFilePath = Paths.get("data", "data.csv"); // Process command-line arguments for sort order and direction org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData.Employee.SortOrder employeeSortOrder = processSortOrder(args); org.challenge.csv.CSVData.SortDirection employeeSortDirection = processSortAscendingDescending(args); // Create the parser Parser csvParser = CSVParser.createSurveyParser(csvFilePath.toFile(), employeeSortOrder, employeeSortDirection); long timeBeforeWorkMs = System.nanoTime(); // Parse into object structure Optional&lt;CSVData&gt; csvDataObjectsOrNull = csvParser.parse(); if (true == csvDataObjectsOrNull.isPresent()) { CSVData csvDataObjects = csvDataObjectsOrNull.get(); Objects.requireNonNull(csvDataObjects, "FAILED to parse CSV"); // Create the writer JSONWriter writerofJson = new JSONWriter(csvDataObjects); // Write out objects as JSON String jsonStringRepresentation = writerofJson.write(); Objects.requireNonNull(jsonStringRepresentation, "FAILED to output JSON"); System.out.println("Processed in " + (System.nanoTime() - timeBeforeWorkMs) + "ms"); // Dump JSON to console System.out.println("JSON formatted survey data"); System.out.println(jsonStringRepresentation); // NOTE - Verify and pretty print JSON output at https://jsonlint.com/ // Check we have survey data if (true == csvDataObjects instanceof SurveyCSVParser.SurveyCSVData) { SurveyCSVParser.SurveyCSVData surveyData = (SurveyCSVParser.SurveyCSVData)csvDataObjects; // Dump some sample object data to console SurveyCSVParser.SurveyCSVData.Manager sampleManager = surveyData.getDivisions().get(1).getTeams().get(5).getManagers().get(1); System.out.println("Division 1, Team 5, Manager 1 has employees: " + sampleManager); try { // Create survey data analyzer AgeCalculator averageAgeCalculator = new SurveyAnalyzer(surveyData); Period averageAge; // Calculate some sample average ages and dump to console averageAge = averageAgeCalculator.getAverageAge(AgeCalculator.Scope.COMPANY, Optional.empty()); System.out.println("Average age of employees in company: " + formatPeriod(averageAge)); averageAge = averageAgeCalculator.getAverageAge(AgeCalculator.Scope.DIVISION, Optional.of(1)); // NOTE - Samples only, not added to command line arguments System.out.println("Average age of employees in division 1: " + formatPeriod(averageAge)); averageAge = averageAgeCalculator.getAverageAge(AgeCalculator.Scope.TEAM, Optional.of(12)); System.out.println("Average age of employees in team 12: " + formatPeriod(averageAge)); averageAge = averageAgeCalculator.getAverageAge(AgeCalculator.Scope.MANAGER, Optional.of(2)); System.out.println("Average age of employees under manager 2: " + formatPeriod(averageAge)); } catch (AgeCalculatorException e) { System.out.println("AGE EXCEPTION: " + e.toString()); } } else { System.out.println("UNEXPECTED CSV data type"); } } else { System.out.println("FAILED to parse CSV data"); } System.out.flush(); } catch (Exception e) { System.out.println("EXCEPTION: " + e.toString()); } } private static org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData.Employee.SortOrder processSortOrder(String[] args) { org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData.Employee.SortOrder sortOrder = org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL; if (args.length &gt; 0) { try { sortOrder = Enum.valueOf(org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData.Employee.SortOrder.class, args[0]); } catch (IllegalArgumentException e) { System.out.println("FAILED to process sort order, defaulting to ORIGINAL"); } } System.out.println("Sort order is " + sortOrder.name()); return sortOrder; } private static org.challenge.csv.CSVData.SortDirection processSortAscendingDescending(String[] args) { org.challenge.csv.CSVData.SortDirection sortDirection = org.challenge.csv.CSVData.SortDirection.ASCENDING; if (args.length &gt; 1) { if (true == "DESC".equalsIgnoreCase(args[1])) sortDirection = org.challenge.csv.CSVData.SortDirection.DESCENDING; } System.out.println("Sort direction is " + sortDirection.name()); return sortDirection; } private static String formatPeriod(Period period) { String formattedPeriod = String.format("%d years, %d months, %d days", period.getYears(), period.getMonths(), period.getDays()); return formattedPeriod; } } </code></pre> <p>Tests:</p> <p>CSVParserTests.java</p> <pre><code>package org.challenge.csv; import static org.junit.Assert.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import org.challenge.csv.survey.SurveyCSVParser.SurveyCSVData; import org.junit.Test; public class CSVParserTests { @Test public void testParse_givenCSV_success() { Path csvFilePath = Paths.get("data", "data.csv"); Parser csvParser = CSVParser.createSurveyParser(csvFilePath.toFile()); assertNotNull(csvParser); Optional&lt;CSVData&gt; csvData = csvParser.parse(); assertNotNull(csvData.orElse(null)); assertTrue(csvData.get() instanceof SurveyCSVData); SurveyCSVData surveyData = (SurveyCSVData)csvData.get(); assertNotNull(surveyData.getDivisions()); assertNotNull(surveyData.getDivisions().get(1)); } @Test public void testParse_emptyCSV_success() { Path csvFilePath = Paths.get("data", "empty.csv"); Parser csvParser = CSVParser.createSurveyParser(csvFilePath.toFile()); assertNotNull(csvParser); Optional&lt;CSVData&gt; csvData = csvParser.parse(); assertNotNull(csvData.orElse(null)); assertTrue(csvData.get() instanceof SurveyCSVData); SurveyCSVData surveyData = (SurveyCSVData)csvData.get(); assertNotNull(surveyData.getDivisions()); assertEquals(0, surveyData.getDivisions().size()); } @Test public void testParse_extraCSV_success() { Path csvFilePath = Paths.get("data", "extra.csv"); Parser csvParser = CSVParser.createSurveyParser(csvFilePath.toFile()); assertNotNull(csvParser); Optional&lt;CSVData&gt; csvData = csvParser.parse(); assertNotNull(csvData.orElse(null)); assertTrue(csvData.get() instanceof SurveyCSVData); SurveyCSVData surveyData = (SurveyCSVData)csvData.get(); assertNotNull(surveyData.getDivisions()); assertNotNull(surveyData.getDivisions().get(1)); } @Test public void testParse_badCSV_failure() { Path csvFilePath = Paths.get("data", "badformat.csv"); Parser csvParser = CSVParser.createSurveyParser(csvFilePath.toFile()); assertNotNull(csvParser); Optional&lt;CSVData&gt; csvData = csvParser.parse(); assertNull(csvData.orElse(null)); } @Test public void testParse_nonExistantCSV_failure() { Path csvFilePath = Paths.get("data", "missing.csv"); Parser csvParser = CSVParser.createSurveyParser(csvFilePath.toFile()); assertNotNull(csvParser); Optional&lt;CSVData&gt; csvData = csvParser.parse(); assertNull(csvData.orElse(null)); } } </code></pre> <p>JSONWriterTests.java</p> <pre><code>package org.challenge.json; import static org.junit.Assert.*; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import org.challenge.csv.CSVData; import org.challenge.csv.survey.SurveyCSVParser; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; public class JSONWriterTests { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-M-d"); @Test public void testWrite_success() { SurveyCSVParser.SurveyCSVData surveyData = buildSampleData(); JSONWriter writerOfJson = new JSONWriter(surveyData); try { String jsonString = writerOfJson.write(); assertNotNull(jsonString); assertTrue(jsonString.length() &gt; 0); } catch (JsonProcessingException e) { fail("JSON processing failed"); } } private SurveyCSVParser.SurveyCSVData buildSampleData() { SurveyCSVParser.SurveyCSVData surveyData = new SurveyCSVParser.SurveyCSVData(SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL); SurveyCSVParser.SurveyCSVData.Division division = new SurveyCSVParser.SurveyCSVData.Division(1, SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL); SurveyCSVParser.SurveyCSVData.Team team = division.createTeam(1); SurveyCSVParser.SurveyCSVData.Manager manager = team.createManager(1, CSVData.SortDirection.ASCENDING); SurveyCSVParser.SurveyCSVData.Employee employee = manager.createEmployee(1, "Stuart", "Mackintosh", LocalDate.now().minusDays(1).format(FORMATTER)); manager.addEmployee(1, employee); team.addManager(1, manager); division.addTeam(1, team); surveyData.addDivision(1, division); return surveyData; } } </code></pre> <p>SurveyAnalyzerTests.java</p> <pre><code>package org.challenge.analysis; import static org.junit.Assert.*; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; import java.util.Optional; import org.challenge.csv.CSVData; import org.challenge.csv.survey.SurveyCSVParser; import org.junit.Test; public class SurveyAnalyzerTests { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-M-d"); @Test public void test_CompanyScope_success() throws AgeCalculator.AgeCalculatorException { SurveyCSVParser.SurveyCSVData surveyData = buildSampleData(); SurveyAnalyzer analysis = new SurveyAnalyzer(surveyData); Period period = analysis.getAverageAge(AgeCalculator.Scope.COMPANY, Optional.empty()); assertNotNull(period); assertEquals(1, period.getDays()); } @Test public void test_NoEmployees_success() throws AgeCalculator.AgeCalculatorException { SurveyCSVParser.SurveyCSVData surveyData = buildEmptySampleData(); SurveyAnalyzer analysis = new SurveyAnalyzer(surveyData); Period period = analysis.getAverageAge(AgeCalculator.Scope.COMPANY, Optional.empty()); assertNotNull(period); assertTrue(period.equals(Period.ZERO)); } @Test public void test_DivisionScope_success() throws AgeCalculator.AgeCalculatorException { SurveyCSVParser.SurveyCSVData surveyData = buildSampleData(); SurveyAnalyzer analysis = new SurveyAnalyzer(surveyData); Period period = analysis.getAverageAge(AgeCalculator.Scope.DIVISION, Optional.of(1)); assertNotNull(period); assertEquals(1, period.getDays()); } @Test(expected=AgeCalculator.AgeCalculatorException.class) public void test_DivisionScope_failure() throws AgeCalculator.AgeCalculatorException { SurveyCSVParser.SurveyCSVData surveyData = buildEmptySampleData(); SurveyAnalyzer analysis = new SurveyAnalyzer(surveyData); analysis.getAverageAge(AgeCalculator.Scope.DIVISION, null); } private SurveyCSVParser.SurveyCSVData buildSampleData() { SurveyCSVParser.SurveyCSVData surveyData = new SurveyCSVParser.SurveyCSVData(SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL); SurveyCSVParser.SurveyCSVData.Division division = new SurveyCSVParser.SurveyCSVData.Division(1, SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL); SurveyCSVParser.SurveyCSVData.Team team = division.createTeam(1); SurveyCSVParser.SurveyCSVData.Manager manager = team.createManager(1, CSVData.SortDirection.ASCENDING); SurveyCSVParser.SurveyCSVData.Employee employee1 = manager.createEmployee(1, "Stuart", "Mackintosh", LocalDate.now().minusDays(1).format(FORMATTER)); SurveyCSVParser.SurveyCSVData.Employee employee2 = manager.createEmployee(2, "Stuart L", "Mackintosh", LocalDate.now().minusDays(2).format(FORMATTER)); manager.addEmployee(1, employee1); manager.addEmployee(2, employee2); team.addManager(1, manager); division.addTeam(1, team); surveyData.addDivision(1, division); return surveyData; } private SurveyCSVParser.SurveyCSVData buildEmptySampleData() { SurveyCSVParser.SurveyCSVData surveyData = new SurveyCSVParser.SurveyCSVData(SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL); SurveyCSVParser.SurveyCSVData.Division division = new SurveyCSVParser.SurveyCSVData.Division(1, SurveyCSVParser.SurveyCSVData.Employee.SortOrder.ORIGINAL); SurveyCSVParser.SurveyCSVData.Team team = division.createTeam(1); SurveyCSVParser.SurveyCSVData.Manager manager = team.createManager(1, CSVData.SortDirection.ASCENDING); team.addManager(1, manager); division.addTeam(1, team); surveyData.addDivision(1, division); return surveyData; } } </code></pre> <p>Data.csv (excerpt):</p> <pre><code>divisionId,teamId,managerId,employeeId,firstName,lastName,birthdate 7,6,2,597,Terrill,Lindgren,1956-7-21 7,10,2,632,Cecile,Mante,1955-3-11 6,2,1,489,Audreanne,Labadie,1964-4-5 9,9,1,859,Vinnie,Mann,1974-11-20 7,7,1,607,Cecilia,Kunde,1997-7-18 2,9,2,134,Taryn,Bednar,1970-5-8 9,9,2,865,Helmer,Littel,1964-2-19 11,4,1,1071,Declan,Bailey,1972-8-7 5,8,1,476,Gladyce,Mills,1988-12-15 12,3,1,1157,Cyrus,Tillman,1980-2-19 7,12,2,651,Camryn,Ernser,1965-11-17 6,4,1,515,Kadin,Wehner,1989-11-5 7,4,1,570,Kirk,Rowe,1966-1-26 10,6,1,993,Ashlee,Wuckert,1956-1-9 13,2,2,1183,Anibal,Botsford,1972-7-25 7,6,2,598,Roscoe,Corkery,1954-5-16 10,7,1,1008,Branson,Hammes,1983-5-2 14,9,1,1308,Favian,Skiles,1981-9-13 14,10,1,1331,Kaelyn,Rosenbaum,1956-8-22 8,9,1,765,Shea,Osinski,1964-3-5 7,6,2,594,Helena,Lesch,1957-10-26 9,9,2,864,Orrin,Stiedemann,1951-10-19 5,8,1,475,Vivien,Kemmer,1981-7-20 5,3,1,432,Genoveva,Kassulke,1987-5-27 8,5,2,745,Verdie,Gerhold,1988-6-25 1,5,2,15,Stefan,Stokes,1978-11-24 8,4,1,731,Tyrel,McDermott,1992-12-9 2,10,1,139,Rickey,Hodkiewicz,1968-1-24 10,8,1,1017,Gianni,Morissette,1992-8-23 14,11,2,1342,Uriel,Halvorson,1965-9-9 7,10,2,630,Robert,Johnston,1955-10-27 14,12,2,1366,Rene,Carter,1988-9-23 2,1,1,51,Maggie,O'Kon,1998-5-22 2,11,1,156,Jerod,Walker,1971-8-3 13,2,1,1174,Margarette,Jacobi,1955-8-10 3,12,1,301,Cleo,Hudson,1989-1-28 2,13,1,183,Jaquan,Skiles,1957-9-10 9,13,1,904,Elfrieda,Langworth,1953-10-18 5,7,1,461,Torrey,Gislason,1998-1-23 2,7,1,102,Demond,Herman,1950-7-3 11,3,1,1057,Gracie,Rau,1957-6-9 14,7,1,1290,Ollie,Bogan,1951-10-4 7,8,1,610,Rahul,Spencer,1981-10-3 8,5,2,742,Bell,Orn,1963-8-19 8,6,1,752,Alisa,Corwin,1969-11-4 3,2,1,198,Angelina,Corwin,1969-2-2 3,5,2,243,Rigoberto,Runolfsson,1971-1-21 9,16,1,934,Elise,Hegmann,1964-2-5 9,17,1,935,Richmond,Cormier,1980-1-6 14,5,2,1273,Eino,O'Conner,1969-8-24 13,7,1,1214,Kathryn,Kub,1966-1-6 5,7,2,470,Golden,Reichert,1952-9-10 2,1,1,57,Dejah,Schaefer,1975-2-5 2,7,1,101,Ronny,McCullough,1994-6-2 10,6,2,1001,Nikki,Runolfsson,1961-10-5 8,4,1,730,Wayne,Ward,1997-4-9 7,3,1,569,Vivian,Muller,1969-7-31 5,6,1,450,Juvenal,Schmidt,1973-8-5 14,5,2,1274,Orrin,O'Keefe,1981-12-13 14,9,1,1313,Jazlyn,Walter,1992-4-13 1,4,1,7,Darwin,Collins,1975-4-11 9,13,1,901,Margarita,Spinka,1972-5-4 10,2,1,954,Stephen,Schmitt,1980-2-5 2,7,1,104,Westley,Swift,1989-10-19 3,14,1,321,Emelie,Simonis,1951-5-29 11,11,2,1126,Clement,Lemke,1990-10-20 7,14,2,680,Millie,Haag,1979-8-23 2,1,1,56,Marcelino,Will,1987-10-29 14,7,1,1288,Cheyanne,Labadie,1954-7-20 4,3,2,386,Owen,Turner,1986-2-7 3,1,1,193,Lynn,Huel,1963-8-17 14,11,2,1345,Evangeline,Becker,1995-10-9 6,6,1,535,Bridget,Rath,1959-9-12 3,10,1,277,Rodolfo,O'Kon,1951-3-30 12,2,1,1153,Vincent,Collins,1991-8-17 12,1,2,1145,Coralie,Olson,1956-9-14 9,16,1,933,Annabell,Wehner,1965-5-25 7,12,2,649,Davonte,Kohler,1970-6-30 2,12,1,170,Laury,Muller,1968-12-16 7,9,2,622,Norval,Gusikowski,1967-5-18 2,12,1,173,Jena,Conn,1999-5-23 11,3,1,1056,Kamren,Koch,1960-3-24 14,1,1,1242,Mckenna,Graham,1958-6-20 12,3,1,1155,Raegan,Doyle,1996-12-9 9,17,1,939,Lazaro,Swaniawski,1981-8-16 10,4,2,974,Astrid,Rath,1998-9-19 3,4,1,215,Scarlett,Watsica,1987-5-27 5,1,1,400,Jenifer,Stokes,1969-5-16 12,3,2,1164,Kobe,Wisozk,1958-3-24 8,11,1,788,Margret,Zemlak,1993-8-20 9,15,1,920,Sister,Braun,1960-11-9 5,1,1,402,Daniela,Pollich,1968-11-11 9,4,2,820,Cornell,Robel,1952-4-9 3,4,2,227,Marion,Flatley,1997-11-13 1,4,1,3,Arvel,Runolfsdottir,1954-9-5 6,3,1,498,Jazmyn,Hartmann,1986-9-4 5,3,1,433,Cloyd,Botsford,1995-12-23 9,16,1,932,Jerrell,Moore,1972-12-3 11,4,1,1072,Jefferey,Goldner,1984-5-3 14,5,1,1267,Nicolas,Davis,1988-2-5 14,7,1,1291,Demarco,Rolfson,1980-1-3 6,1,1,483,Katelin,Hintz,1955-3-2 14,11,1,1339,Jennings,Schowalter,1985-8-6 12,3,2,1159,Kamryn,Wyman,1998-8-17 3,1,1,187,Tremayne,Cummings,1998-1-14 3,13,1,316,D'angelo,Morar,1990-10-20 3,16,1,346,Marian,Mante,1955-2-27 7,13,1,664,Audreanne,Schoen,1987-9-16 14,2,1,1245,Rylan,Conroy,1951-6-8 5,3,1,429,Leola,Hansen,1997-5-6 10,6,1,991,Ahmad,Schinner,1966-2-11 6,6,1,536,Irma,Osinski,1988-11-29 13,2,1,1173,Sister,Heller,1984-9-13 10,8,1,1019,Margaret,Stokes,1960-8-8 14,11,2,1347,Noah,Brakus,1983-4-21 9,5,1,827,Christina,Feeney,1972-5-31 2,12,1,172,Elwyn,Upton,1971-11-9 2,10,1,143,Reva,Hand,1955-3-17 7,7,1,605,Evangeline,Schuster,1995-7-20 6,5,2,529,Albina,Koss,1981-2-12 7,16,1,698,Ronaldo,Rutherford,1983-11-22 9,12,2,899,Odessa,McClure,1958-6-5 3,4,2,219,Braulio,Gibson,1960-6-12 13,8,2,1232,Josiah,Reynolds,1963-7-30 3,5,1,229,Vidal,Schuppe,1963-2-12 2,1,1,50,Friedrich,Ortiz,1951-1-30 13,4,2,1199,Orin,Vandervort,1981-4-17 3,2,1,196,Chelsey,Boyer,1995-9-5 14,5,2,1276,Tracy,Leffler,1983-3-31 12,3,2,1161,Edythe,Sauer,1972-2-1 13,3,1,1186,Otilia,O'Reilly,1986-2-20 4,4,2,394,Taylor,Quitzon,1975-8-16 11,10,2,1112,Kayli,Mohr,1961-10-10 10,2,1,950,Tillman,Abshire,1972-11-11 13,3,2,1190,Nya,Klocko,1971-6-10 9,14,1,913,Pedro,D'Amore,1957-10-19 12,3,2,1165,Gunner,Hamill,1986-9-15 7,3,1,566,Bailey,Bayer,1965-2-7 3,15,1,339,Broderick,Hettinger,1998-6-18 14,10,1,1326,Carlos,Von,1978-10-21 3,16,2,349,Webster,Rodriguez,1987-7-2 3,16,1,348,Vallie,Wyman,1995-3-16 14,9,2,1318,Clifford,Leuschke,1959-8-30 7,8,1,612,Otto,Mante,1951-3-26 3,8,1,267,Kaleb,Rice,1963-12-25 9,17,1,942,Dave,Erdman,1968-5-23 14,4,1,1263,Lemuel,Osinski,1966-4-20 14,7,2,1292,Winnifred,Mraz,1964-11-29 11,9,1,1093,Ottilie,Gutmann,1990-11-2 9,3,1,797,Rocio,Fisher,1960-2-21 2,10,1,147,Tobin,Larkin,1987-12-27 11,3,1,1058,Brenden,Bechtelar,1981-8-2 13,8,1,1228,Irma,Bruen,1972-8-21 11,1,1,1043,Francisco,Hartmann,1967-6-4 4,3,1,377,Donato,Hyatt,1955-4-21 5,3,1,428,Alexanne,Parker,1965-1-9 11,1,1,1041,Eleanora,Littel,1985-4-19 7,14,1,674,Curt,Kshlerin,1996-12-2 11,10,2,1107,Yazmin,Williamson,1971-5-25 3,12,1,305,Bailee,Rodriguez,1965-5-14 11,2,1,1052,Mathew,McClure,1960-10-18 14,9,2,1317,Macie,Rath,1971-11-6 9,3,2,805,Joany,Sanford,1972-1-24 1,6,1,20,Manley,Bednar,1973-5-31 4,1,2,369,Twila,Stoltenberg,1981-8-8 1,3,2,1,Maeve,Corwin,1963-4-7 11,5,1,1075,Effie,Dooley,1997-6-28 14,4,1,1261,Whitney,Gibson,1982-8-16 2,8,1,117,Chris,Mann,1992-3-2 10,8,1,1014,Hans,Hauck,1953-10-29 10,5,1,979,Wilfredo,Kub,1993-1-9 5,6,1,446,Gabe,Walter,1954-9-23 3,2,1,197,Maxine,Oberbrunner,1996-8-8 9,12,1,888,Cecile,Adams,1963-7-23 2,11,1,153,Tyree,Lemke,1983-8-7 2,11,1,149,Mathew,Lehner,1967-12-3 1,5,1,11,Hipolito,Collins,1961-12-17 7,1,1,548,Assunta,Murazik,1993-5-27 1,7,1,31,Maye,Torphy,1956-12-11 8,9,1,767,Kamille,Kessler,1995-11-27 4,3,1,380,Derrick,Bergnaum,1996-4-20 11,9,2,1096,Hal,Price,1970-11-29 8,1,1,705,Jailyn,Predovic,1993-6-7 10,2,1,958,Jamaal,Buckridge,1997-4-12 14,1,1,1240,Dovie,Yundt,1995-8-17 8,8,1,760,Marisol,Beahan,1975-6-25 3,6,2,248,Jade,Haag,1950-10-21 13,8,1,1223,Gerry,Ziemann,1976-4-3 14,1,1,1237,Logan,Schneider,1977-5-31 7,16,1,700,Nikki,Daniel,1978-4-28 10,5,2,989,Art,Bernhard,1969-9-28 14,1,1,1234,Cassie,Aufderhar,1990-8-31 9,12,2,898,Kayden,Spinka,1986-1-9 11,3,2,1063,Faustino,Schamberger,1994-11-14 6,3,2,509,April,Williamson,1984-4-21 10,4,1,971,Cristina,DuBuque,1968-9-19 9,14,1,911,Roel,Flatley,1958-10-17 7,5,1,578,Magdalena,Cole,1986-2-23 8,3,1,718,Pat,Dach,1956-2-29 9,15,2,923,Kiana,Jenkins,1994-7-28 11,1,1,1042,Gene,West,1953-5-21 13,1,1,1170,Adelbert,Lockman,1991-10-11 1,4,1,4,Anthony,Armstrong,1957-4-9 1,7,2,35,Ramiro,Kohler,1973-9-6 14,5,2,1275,Reyes,Funk,1960-6-10 14,11,1,1334,Ellis,Roob,1951-9-18 2,9,2,138,Linnea,Blanda,1968-2-29 2,4,2,85,Elinor,Jakubowski,1999-4-29 9,13,2,909,Kristy,Orn,1963-12-9 9,12,1,893,Mandy,Howell,1985-11-9 14,6,1,1281,Marisa,Terry,1991-2-12 12,1,1,1133,Taryn,Predovic,1990-9-19 11,7,2,1083,Otto,Bergstrom,1955-6-8 14,11,2,1343,Howell,Moore,1956-9-27 11,3,2,1061,Sabina,Senger,1968-4-1 1,8,2,45,Gaston,Graham,1963-9-2 9,17,1,941,Brant,Halvorson,1970-12-28 3,11,2,292,Hallie,Schaefer,1974-8-6 9,6,1,832,Kara,Block,1974-2-5 4,4,1,390,Terrence,Effertz,1986-11-29 4,1,1,356,Maye,Bauch,1980-9-16 2,6,2,96,Brock,Rowe,1971-1-17 7,4,1,575,Jessie,Larkin,1977-6-24 14,4,1,1260,Carlie,Gerlach,1995-5-11 1,7,2,33,Kirsten,Reichel,1988-11-6 3,9,1,271,Roselyn,Jakubowski,1970-11-19 14,12,1,1360,Alene,Jacobi,1999-5-26 10,5,2,986,Newton,Volkman,1969-12-13 7,13,1,656,Soledad,Spencer,1993-12-31 3,5,1,230,Lucas,Emmerich,1977-9-29 14,8,2,1307,Lyla,Vandervort,1979-6-16 10,3,1,969,Vena,Conn,1985-3-6 9,11,1,877,Sally,Runolfsdottir,1960-10-6 11,11,1,1121,Caroline,Smitham,1979-8-4 9,1,1,792,Litzy,Tromp,1972-8-22 7,10,2,631,Reynold,Dare,1991-4-14 10,7,2,1011,Beverly,McLaughlin,1999-8-20 1,6,1,18,Jaylen,Cole,1975-10-6 2,13,1,182,Delia,Strosin,1968-11-29 8,9,1,764,Lavina,Koch,1993-9-16 2,4,2,87,Marvin,Lehner,1956-11-1 10,2,1,956,Prince,Schroeder,1979-5-9 2,9,1,129,Emmie,Auer,1969-6-19 8,5,2,743,Antoinette,Legros,1986-5-17 9,7,1,847,Murphy,Jenkins,1955-12-2 11,11,2,1124,Quinton,Romaguera,1973-12-28 12,3,2,1166,Martine,Stanton,1977-3-1 8,4,2,737,Nova,Sporer,1993-4-5 3,13,1,314,Gilberto,Kuhic,1970-4-17 10,1,2,948,Faye,Wisoky,1958-12-11 7,12,2,650,Aleen,O'Connell,1987-9-21 10,5,1,975,Sandrine,Hegmann,1980-6-27 4,3,1,379,Shanna,Mann,1977-7-4 1,5,2,14,Eugenia,Nicolas,1976-5-5 13,2,1,1175,Heaven,Lang,1962-12-29 7,6,1,593,Hans,Fahey,1964-3-30 3,14,2,330,Alexa,Muller,1964-12-20 7,9,2,616,Elwyn,Russel,1966-5-21 10,2,1,953,Adolphus,Koch,1975-7-25 9,10,1,870,Rose,Walker,1950-6-15 3,3,2,212,Jairo,Smith,1980-11-5 8,11,1,781,Haylee,Stiedemann,1980-12-8 2,8,1,118,Alysson,Wisoky,1982-10-2 13,7,1,1217,Jace,Monahan,1995-12-10 14,5,2,1278,Danny,Kautzer,1967-12-30 1,6,2,26,Madyson,Bednar,1972-5-27 11,1,2,1047,Annalise,Lind,1982-7-23 1,5,2,13,Orlo,Wuckert,1991-2-14 9,15,2,924,Nicole,Balistreri,1950-10-5 7,6,2,596,Abigayle,Bogisich,1977-7-4 8,2,1,713,Malcolm,Spencer,1982-11-24 10,1,2,949,Eugene,Barrows,1983-7-30 6,6,2,546,Edward,Crist,1996-4-30 9,8,1,856,Percival,Bogan,1968-2-16 2,7,2,109,Gaetano,Rosenbaum,1979-1-30 14,11,2,1349,Eulalia,Nader,1958-4-18 1,8,1,37,Remington,Ratke,1988-11-15 7,15,1,687,Vada,Hansen,1960-10-13 4,3,2,387,Rogers,Larkin,1988-7-20 5,2,1,419,Arne,Ernser,1971-1-24 4,2,1,372,Orin,Quitzon,1995-1-26 11,9,2,1099,Roscoe,Collier,1990-6-1 13,7,1,1218,Chet,Wyman,1953-7-13 2,3,2,67,Aubree,Marvin,1979-6-6 3,15,1,337,Clare,Runolfsson,1969-9-9 14,11,2,1348,Urban,Hamill,1963-2-12 9,7,2,848,Hulda,Kautzer,1971-7-29 5,2,2,424,Neha,Jenkins,1961-8-22 3,4,1,214,Shawna,Boyle,1991-12-11 10,7,2,1012,Ivory,Davis,1987-5-16 11,8,1,1085,Esteban,Powlowski,1954-12-25 8,9,2,773,Dannie,Bogisich,1949-11-2 8,9,1,768,Aylin,Sporer,1990-12-30 2,2,1,59,Tianna,Kilback,1995-11-19 13,8,1,1226,Verla,Lehner,1969-4-14 2,12,1,169,Tina,Becker,1966-8-5 12,1,2,1142,Cassie,Littel,1956-10-4 5,3,1,430,Naomi,Stiedemann,1953-11-24 10,5,2,987,Deonte,Larson,1980-3-5 2,6,2,95,Odie,Halvorson,1992-11-5 2,13,1,181,Yolanda,Leannon,1996-3-2 10,5,1,980,Rachel,West,1978-3-24 8,10,2,777,Gladys,Lakin,1978-8-23 12,3,1,1156,Eugene,Farrell,1975-2-22 7,13,2,668,Ryley,Berge,1989-11-3 14,10,1,1324,Martine,Becker,1961-4-15 6,1,1,484,Greyson,Welch,1956-3-7 3,3,1,205,Cade,Hessel,1990-2-5 13,3,1,1188,Federico,Bins,1976-6-29 1,4,1,2,Lauren,Keeling,1969-12-27 2,10,1,144,Brandt,Torp,1960-8-1 10,2,1,951,Joey,Abernathy,1973-3-20 3,3,2,209,Alayna,Orn,1988-7-28 4,1,1,359,Jensen,Beier,1956-12-9 3,5,2,238,Victor,Murray,1983-6-3 2,11,2,167,Lauriane,Hodkiewicz,1952-2-25 9,13,1,906,Mayra,Heidenreich,1969-9-8 14,4,1,1257,Ova,Torp,1955-12-26 11,10,2,1111,Verla,Oberbrunner,1959-7-9 3,14,2,327,Brianne,Schoen,1975-7-29 7,1,2,559,Agustin,Pouros,1997-3-25 10,6,2,999,Earline,Becker,1964-1-22 13,2,1,1177,Genevieve,Kutch,1984-3-23 3,7,1,261,Gussie,Emmerich,1971-2-12 9,4,1,818,Louisa,Strosin,1953-8-16 10,5,2,985,Okey,Fisher,1960-12-2 2,13,1,179,Aylin,Kshlerin,1967-10-21 10,3,1,966,Sonya,Hagenes,1977-5-13 14,11,1,1338,Murl,Boehm,1986-2-4 7,5,2,581,Jamie,Aufderhar,1990-12-28 2,12,1,168,Keegan,Collins,1978-8-24 7,13,1,657,Connor,Kessler,1981-7-1 11,8,2,1091,Lauren,Hoeger,1958-1-1 10,4,1,970,Martina,Greenholt,1978-10-20 5,8,1,472,Clinton,Maggio,1968-5-31 9,14,1,917,Esther,Nitzsche,1989-7-24 2,10,1,142,Rashad,Ortiz,1950-3-5 4,3,2,385,Jacky,Crona,1989-6-18 12,2,1,1149,Neoma,Schamberger,1981-3-23 2,7,1,105,Giovanni,Wuckert,1989-4-28 14,4,1,1256,Zackary,Jaskolski,1961-11-14 13,4,1,1197,Sally,Stokes,1975-3-29 5,1,1,404,Terrence,Purdy,1969-6-15 7,14,1,672,Margret,Bradtke,1984-1-24 7,6,2,602,Maureen,Stark,1994-12-16 9,16,1,931,Heather,Goyette,1951-7-10 9,11,1,881,Rosario,Kohler,1969-3-24 2,6,2,98,Gerry,Daugherty,1986-6-22 2,7,2,111,Destany,Jacobs,1981-7-31 9,15,1,922,Caitlyn,Nikolaus,1949-12-16 14,5,1,1265,Fanny,Sawayn,1956-6-30 7,10,1,624,Vincenzo,Kozey,1975-10-20 7,4,1,574,Ciara,Prosacco,1958-11-14 5,7,1,465,Chandler,Borer,1957-3-12 10,6,2,998,Kraig,Ortiz,1953-8-6 5,1,1,405,Waldo,Swaniawski,1951-7-30 7,10,2,635,Jeramy,Kiehn,1981-4-10 2,8,1,119,Dedrick,Yundt,1973-2-26 2,2,1,63,Eugene,Kuhlman,1960-8-11 9,9,2,863,Dedrick,Conn,1965-5-11 14,5,1,1270,Susie,Labadie,1957-10-27 9,3,1,802,Ora,Mohr,1956-1-17 10,5,1,981,Delphine,Lindgren,1980-11-22 3,17,1,352,Chanel,Dare,1980-5-19 2,4,1,78,Shany,Kessler,1983-10-12 2,11,2,162,Loyal,Mertz,1964-11-21 8,10,1,775,Hettie,Kris,1969-1-21 14,1,1,1238,Jon,Pagac,1973-1-16 8,4,1,728,Katrina,Kovacek,1962-5-29 3,12,1,304,Jaime,Barrows,1968-2-25 14,11,1,1337,Casey,Gibson,1988-10-15 12,1,2,1140,Melany,Blanda,1978-1-11 5,2,1,415,Nelda,Hartmann,1973-8-30 10,6,1,990,Nelle,Gislason,1988-2-15 3,12,1,306,Gunnar,Hartmann,1977-7-6 11,6,1,1080,Hoyt,Nikolaus,1987-4-21 ... </code></pre> <p>My instructions/answers:</p> <h2>Eclipse Photon project for Challenge</h2> <p>Requirements:</p> <ul> <li>Java 8</li> <li>Gradle 4.3</li> <li>Jackson 2.4</li> <li>JUnit 4.12</li> </ul> <p>Build with Gradle:</p> <pre class="lang-none prettyprint-override"><code>Gradlew.bat build </code></pre> <p>Execute main in /src/main/java/org/challenge/Task1.java, possible arguments to control the data sort order and employee sort order are:</p> <pre class="lang-none prettyprint-override"><code>[ORIGINAL/ID/LASTNAME/FIRSTNAME/BIRTHDATE] [ASC/DESC] </code></pre> <p>e.g.</p> <pre class="lang-none prettyprint-override"><code>java ... org.challenge.Test1 LASTNAME DESC java ... org.challenge.Test1 ID java ... org.challenge.Test1 </code></pre> <p>Run unit tests under /src/test/java/*:</p> <pre class="lang-none prettyprint-override"><code>Gradlew.bat test </code></pre> <p>For Javadoc:</p> <pre class="lang-none prettyprint-override"><code>Gradlew.bat javadoc </code></pre> <h2>Questions</h2> <ol> <li>Time complexity is linear or O(n) without sorting, i.e. ORIGINAL, each line of the CSV file is processed once, map insertions and gets are O(1) for unsorted hash maps or O(log n) for sorted maps. Space complexity is O(n).</li> <li>Use ID command-line argument to obtain all data sorted by ID, the argument ORIGINAL (default) will use CSV data order.</li> <li>Use ID, LASTNAME, FIRSTNAME or BIRTHDATE arguments to set sort order of employees, optionally with ASC or DESC to set sort direction, the default is ascending.</li> <li>The program will output some calculated average ages for the company and one sample division, team and manager at the end. I didn't add command-line arguments for this.</li> </ol> <h2>Assumptions</h2> <p>Employee birthdate is always in yyyy-M-D format. The CSV file can be read entirely into available heap. A badly formatted CSV row will end the parsing operation. File reading will not be retried. Integer data type can contain all IDs. Long data type can contain the total age in days of all employees during the scope of the average age calculation. Average age of all employees in scope is rounded down to the nearest day.</p>
[]
[ { "body": "<p>There are indeed a few weird/bad practices in your code.</p>\n\n<ul>\n<li><p><strong>Error handling:</strong> Broadly speaking, there are two categories of things that can go wrong when running this program: I/O errors and malformed input. You handle both of those poorly.</p>\n\n<ul>\n<li><p><co...
{ "AcceptedAnswerId": "205852", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T12:15:31.050", "Id": "205813", "Score": "1", "Tags": [ "java", "interview-questions", "json", "csv" ], "Title": "Converting employee survey data from CSV to JSON" }
205813
<p>I have made a simple To-Do Application just to get started with HTML/CSS/JavaScript and here is what I came up with. I have done what I can do at my best but still, I need some suggestions on my code, because I am new to Web-Development.</p> <p>Well, here is what my code is doing:</p> <p>This application helps others remember the works they have to do in nearby time.</p> <p>So, the application has <kbd>Add work</kbd> a button, if the user clicks on that button then application prompts the user to add any work then it shows that work on screen and stores that work in <code>localStorage</code> and when the work is done then user can hover over the work and can click on the <kbd>done</kbd> button then the work gets removed from screen and from <code>localStorage</code> as well.</p> <p>In addition to that, my JS code also searches for any work in <code>localStorage</code> at startup.</p> <p>So if there is something wrong, or there is something which is not a recommended practice, or there is something which can be done in a better way, then please share that.</p> <p>Here is the link to <a href="https://github.com/HarshitSeksaria/ToDo/tree/fda9b1e351867e97e2b051557a41a879fe00a854" rel="nofollow noreferrer">Github repo</a></p> <p>Here is the whole source code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Instance of a div to add a work let addButton = document.getElementById("addbutton"); // Instance of work list let list = document.getElementById('workslist'); // Instance of title div let title = document.getElementById('text'); // Number of works let works = 0; // Record of current works let workTitles = []; // function to add Typewrite effect let type = function() { setTimeout(() =&gt; { title.innerHTML += 'T'; }, 250); setTimeout(() =&gt; { title.innerHTML += 'o'; }, 500); setTimeout(() =&gt; { title.innerHTML += '-'; }, 750); setTimeout(() =&gt; { title.innerHTML += 'd'; }, 1000); setTimeout(() =&gt; { title.innerHTML += 'o'; }, 1250); setTimeout(() =&gt; { title.innerHTML += ' '; }, 1500); setTimeout(() =&gt; { title.innerHTML += 'A'; }, 1750); setTimeout(() =&gt; { title.innerHTML += 'p'; }, 2000); setTimeout(() =&gt; { title.innerHTML += 'p'; }, 2250); setTimeout(() =&gt; { title.innerHTML += 'l'; }, 2500); setTimeout(() =&gt; { title.innerHTML += 'i'; }, 2750); setTimeout(() =&gt; { title.innerHTML += 'c'; }, 3000); setTimeout(() =&gt; { title.innerHTML += 'a'; }, 3250); setTimeout(() =&gt; { title.innerHTML += 't'; }, 3500); setTimeout(() =&gt; { title.innerHTML += 'i'; }, 3750); setTimeout(() =&gt; { title.innerHTML += 'o'; }, 4000); setTimeout(() =&gt; { title.innerHTML += 'n'; }, 4250); } // Calling type() to start TypeWriter effect. type(); // Fetch works form localStorage if (localStorage.getItem('works')) { workTitles = localStorage.getItem('works').split(','); workTitles.forEach(element =&gt; { let currentTitle = element; let entry = document.createElement('li'); let div = document.createElement('div'); div.className = 'works'; div.id = 'works' + works; div.appendChild(document.createTextNode(currentTitle[0].toUpperCase() + currentTitle.slice(1))); div.title = 'Click to remove'; entry.appendChild(div); let span = document.createElement('span'); span.className = 'works remove' span.id = 'remove' + works; span.onclick = function() { let toBeDeleted = document.getElementById('item' + this.id.split('remove')[1]); if (workTitles.length != 1) workTitles.splice(this.id.split('remove')[1], 1); else workTitles.pop(); toBeDeleted.style.transform = 'scale(0)'; localStorage.setItem('works', workTitles); setTimeout(function () { list.removeChild(toBeDeleted); }, 1000); if (workTitles.length == 0) { document.getElementsByTagName('h4')[0].innerHTML = 'No Works to do.'; } } span.appendChild(document.createTextNode('Done')); entry.appendChild(span); entry.id = 'item' + works; let listitem = list.appendChild(entry); listitem.onclick = function() { if (workTitles.length != 1) workTitles.splice(this.id.split('remove')[1], 1); else workTitles.pop(); listitem.style.transform = 'scale(0)' localStorage.setItem('works', workTitles); setTimeout(() =&gt; { list.remove(listitem); }, 1000); if (workTitles.length == 0) { document.getElementsByTagName('h4')[0].innerHTML = 'No Works to do.'; } } // Show animation when new work get added let newWork = document.getElementById('item' + works); setTimeout(function () { newWork.style.transform = 'scale(1)'; }, 1); works++; }) } else { document.getElementsByTagName('h4')[0].innerHTML = 'No Works to do.' } // ClickListener for addButton addButton.addEventListener('click', function() { let currentTitle = prompt('Add your work here'); // Check if value is not null if (currentTitle) { let entry = document.createElement('li'); let div = document.createElement('div'); div.className = 'works'; div.id = 'works' + works; div.appendChild(document.createTextNode(currentTitle[0].toUpperCase() + currentTitle.slice(1))); entry.appendChild(div); let span = document.createElement('span'); span.className = 'works remove' span.id = 'remove' + works; span.onclick = function() { let toBeDeleted = document.getElementById('item' + this.id.split('remove')[1]); if (workTitles.length != 1) workTitles.splice(this.id.split('remove')[1], 1); else workTitles.pop(); toBeDeleted.style.transform = 'scale(0)'; localStorage.setItem('works', workTitles); setTimeout(function () { list.removeChild(toBeDeleted); }, 1000); if (workTitles.length == 0) document.getElementsByTagName('h4')[0].innerHTML = 'No Works to do.'; } span.appendChild(document.createTextNode('Done')); entry.appendChild(span); entry.id = 'item' + works; let listitem = list.appendChild(entry); listitem.onclick = function() { if (workTitles.length != 1) workTitles.splice(this.id.split('remove')[1], 1); else workTitles.pop(); listitem.style.transform = 'scale(0)' localStorage.setItem('works', workTitles); setTimeout(() =&gt; { list.remove(listitem); }, 1000); if (workTitles.length == 0) { document.getElementsByTagName('h4')[0].innerHTML = 'No Works to do.'; } } // Show animation when work get added let newWork = document.getElementById('item' + works); setTimeout(function () { newWork.style.transform = 'scale(1)'; }, 1); works++; workTitles.push(currentTitle); document.getElementsByTagName('h4')[0].innerHTML = 'Works to do:' localStorage.setItem('works', workTitles); } })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-image: url(https://i.stack.imgur.com/usyUd.png); font-family: 'Roboto', cursive, Arial, Helvetica, sans-serif; } li { list-style: none; transition: 1s; transform: scale(0); } span { margin: 0%; padding: 0%; } h4 { text-align: center; margin-top: 100px; font-family: Montserrat, 'Consolas'; font-size: 3ch; color: #2B2B52; } #title { margin-left: 30px; margin-right: 30px; margin-top: 30px; padding-top: 10px; padding-bottom: 10px; border-radius: 30px; text-align: center; font-family: 'Roboto Mono', cursive; font-size: 4vh; background-color: #8B78E6; color: #F5F5F5; } #cursor { color: #f5f5f5; animation: blink-cursor 1s step-end infinite; } #subtitle { font-family: Comfortaa, cursive; text-align: center; font-size: 1.2em; color: #26F9D8; font: bold; } .works { margin: 10px; transition: 0.3s; color: #FFF; padding: 10px; display: inline-block; background-color: #FB6F6F; border-radius: 16px; } .works:hover { transform: scale(1.1); box-shadow: 0px 5px 15px 2px rgba(0, 0, 0, 0.2); } .works:hover~.remove { transform: scale(1); } .remove { transition: 0.5s; transform: scale(0); cursor: pointer; } .remove:hover { transform: scale(1.1); } #addbutton { display: inline-block; padding-right: 30px; padding-left: 30px; transition: 0.5s; color: #212121; border-radius: 16px; cursor: pointer; } #addbutton:hover { background-color: #212121; color: #F5F5F5; } @keyframes blink-cursor { from, to {opacity: 1;} 50% {opacity: 0;} }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;link rel="stylesheet" type="text/css" href="main.css"&gt; &lt;title&gt;To-Do&lt;/title&gt; &lt;!-- Fonts --&gt; &lt;link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Montserrat:700" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="title"&gt; &lt;b&gt;&lt;span id="text"&gt;&lt;/span&gt;&lt;span id="cursor"&gt;|&lt;/span&gt;&lt;/b&gt; &lt;/div&gt; &lt;h4&gt;Works to do:&lt;/h4&gt; &lt;ul id="workslist"&gt;&lt;/ul&gt; &lt;div style="text-align:center; transition: 1s;"&gt; &lt;div id="addbutton"&gt;&lt;p&gt;&lt;b&gt;Add Work&lt;/b&gt;&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- JS Script --&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T14:36:56.627", "Id": "396997", "Score": "3", "body": "I've linked to a snapshot of your repository (the latest commit), so that if you commit changes later, the question still makes sense." } ]
[ { "body": "<p>As you've asked if there's anything that can be done in a better way, here's my suggestion for your <code>type()</code> function:</p>\n\n<pre><code>let type = (target, delay, text) =&gt; {\n if (text.length === 0) {\n return;\n }\n\n target.innerHTML += text[0];\n return setTime...
{ "AcceptedAnswerId": "205827", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T12:52:16.930", "Id": "205816", "Score": "4", "Tags": [ "javascript", "beginner", "html", "css", "to-do-list" ], "Title": "Simple to-do application by an HTML beginner" }
205816
<p>I've written code that performs a merge of two streams of sorted time series data. The first stream is taken to be the primary and any successive streams are merged into it, using the nearest timestamp match to align data. It can be assumed that there will only ever be one match per primary timestamp.</p> <pre><code>const primary = [[1,0], [2, 5], [3, 10], [4, 0]]; const aux = [[1.3, 10], [3.4, 20], [6.9, 30]]; let j = 0; const halfPeriod = (primary[1][0] - primary[0][0]) / 2; aux.map(val =&gt; { tsAux = val[0]; while(j &lt; primary.length) { if (tsAux &lt; primary[j][0] + halfPeriod) { primary[j].push(val[1]); return j++; } else { primary[j].push(null); j++; } } }); console.log(primary); </code></pre> <p>I can't quite put my finger on it but something about writing it felt sub-optimal (maybe just because I haven't used any ES6/2017/2018 syntax!), so my question is: is my gut feel correct and is there a neater and more robust way to do this? As a bonus, can it be neatly extended to accommodate:</p> <ol> <li>any number of auxiliary data streams rather than just one</li> <li>a primary data stream that doesn't have consistent time increments?</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T13:32:12.320", "Id": "205819", "Score": "1", "Tags": [ "javascript", "algorithm", "datetime", "ecmascript-6" ], "Title": "JavaScript time series data combination" }
205819
<p>I've written a function to update the contents of an HTML element to display a counter. On pageload the counter will recieve an initial value, every five minutes the new value will be requested from the server. Over the next five minutes, the initial value will loop to the new value.</p> <pre><code>const increment = function(counter, newValue, timespan = 300000) { const currentValue = Number(counter.textContent); const diff = newValue - currentValue; const interval = timespan / diff; const intervalFn = setInterval(function() { counter.textContent++; if (counter.textContent == newValue) clearInterval(intervalFn); }, interval); }; </code></pre> <p>For simplicity I've left the server calls out:</p> <pre><code>&lt;h1&gt;0&lt;/h1&gt; //html const counter = document.querySelector("h1"); counter.textContent = 50; increment(counter, 100); </code></pre>
[]
[ { "body": "<p>This looks a bit strange:</p>\n\n<blockquote>\n<pre><code>counter.textContent++;\n</code></pre>\n</blockquote>\n\n<p>Incrementing <em>text</em>... waaat? If you check the type of the <code>.textContent</code> property using <code>typeof</code>, it will tell you that it's a <code>string</code>.\nFo...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T13:40:44.907", "Id": "205820", "Score": "0", "Tags": [ "javascript", "performance", "dom" ], "Title": "JS counter in DOM" }
205820
<p>I needed to stitch together a large number of badly formatted log files. I [painfully] developed a script for it in R, one that successfully dealt with the various flaws in the dataset. However, this script is rather slow. Considering I'm a neophyte to the field (and don't know what I do not know), I was hoping I could get some suggestions on how to speed this code up - using either R, or any other Windows-based/CLI tools.</p> <pre><code>#Getting path for all files within a particular directory. files = list.files(path = dirs[j], full.names = T) #The files are in csv format and in the ideal case have exactly 5 columns. However, the 5th column can contain an arbitary number of commas. If I try to fread with sep = ",", certain rows can be of arbitarily high length. If I use select = 1:5 to subset each row, I lose data. #My solution was to read each line into a single column and then seperate into columns within the script based on the location of the first 4 commas. data &lt;- rbindlist(lapply(files,fread,sep = "\n",fill = T,header = F)) #Removing empty rows. retain &lt;- unlist(lapply(data, function(x) { str_detect(x,".") })) data[retain,] -&gt; data #Removing rows where there is no data in the 5th column. retain &lt;- unlist(lapply(data, function(x) { str_detect(trimws(x,which ='both') ,".+,.+,.*,.*,.+") })) data[retain,] -&gt; data #This replaces the first 4 commas with a tab-delimiter. for(i in 1:4){ data &lt;- data.frame(lapply(data, function(x) { str_replace(x,",","\t") }),stringsAsFactors = F) } #This splits the row into 5 seperate columns, always. data &lt;- unlist(lapply(data, function(x) { unlist(strsplit(x,"\t",fixed = T)) })) #Changes the format from a character vector to a data table. data = data.frame(matrix(data,ncol=5,byrow = T),stringsAsFactors = F) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T15:39:06.717", "Id": "397014", "Score": "2", "body": "Welcome to Code Review. The focus of this site is to review *working* code. From your question, it looks like the code does work, but it's slow, and you're not sure why. That's f...
[ { "body": "<p>Without knowing exactly your data structure, I have to guess that it looks like this:</p>\n\n<pre><code>data &lt;- data.table(a = c('1,1,1,4,6',\n '1,2,3,4,',\n '',\n '1,2,3,4,',\n '1,2,3,4,5'))\n</code...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T15:14:45.460", "Id": "205828", "Score": "2", "Tags": [ "performance", "beginner", "csv", "r" ], "Title": "Stitching together badly formatted log files" }
205828
<p>When processing large files (say for parsing or performing computations based on the contents), we want to be able to use multiple processes to perform the job faster.</p> <p>In my case I wanted to count the frequency of appearance of features in a LibSVM formated file, similar to a word-count which is a typical parallel processing example.</p> <p>Example input:</p> <pre><code>1 4:22 6:22 7:44 8:12312 1 4:44 7:44 0 1:33 9:0.44 -1 1:55 4:0 8:12132 </code></pre> <p>We want to count how many times each feature index, i.e. the value before the ':', appears. Here feature 4 appears 3 times, feature 7 appears 2 times etc.</p> <p>Expected output:</p> <pre><code>[(4, 3), (7, 2), (8, 2), (1, 2), (6, 1), (9, 1)] </code></pre> <p>Here's my solution for Python 3:</p> <pre><code>import argparse import multiprocessing as mp import os from operator import itemgetter from collections import Counter import functools import json def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", action='store_true', default=False) parser.add_argument("--no-stdout", action='store_true', default=False) parser.add_argument("--cores", type=int, default=None) return parser.parse_args() def parse_libsvm_line(line: str) -&gt; list: """ Parses a line in a LibSVM file to return the indexes of non-zero features :param line: A line in LibSVM format: "1 5:22 7:44 99:0.88" :return: A list of ints, one for each index appearing in the line """ features = line.split()[1:] # Get rid of the class value indexes = [int(pair.split(":")[0]) for pair in features] return indexes def process_wrapper(arg_tuple): """ Applies the process function to every line in a chunk of a file, to determine the frequency of features in the chunk. :param arg_tuple: A tuple that contains: line_process_fun, filename, chunk_start, chunk_size :return: A counter object that counts the frequency of each feature in the chunk """ line_process_fun, filename, chunk_start, chunk_size = arg_tuple counter = Counter() with open(filename) as f: f.seek(chunk_start) lines = f.read(chunk_size).splitlines() for line in lines: indexes = line_process_fun(line) for index in indexes: counter[index] += 1 return counter def chunkify(fname, size=1024*1024): """ Creates a generator that indicates how to chunk a file into parts. :param fname: The name of the file to be chunked :param size: The size of each chunk, in bytes. :return: A generator of (chunk_start, chunk_size) tuples for the file. """ file_end = os.path.getsize(fname) with open(fname, 'r') as f: chunk_end = f.tell() while True: chunk_start = chunk_end f.seek(f.tell() + size, os.SEEK_SET) f.readline() chunk_end = f.tell() yield chunk_start, chunk_end - chunk_start if chunk_end &gt; file_end: break if __name__ == '__main__': args = parse_args() pool = mp.Pool(args.cores) jobs = [] # Create one job argument tuple for each chunk of the file for chunk_start, chunk_size in chunkify(args.input): jobs.append((parse_libsvm_line, args.input, chunk_start, chunk_size)) # Process chunks in parallel. The result is a list of Counter objects res_list = pool.map(process_wrapper, jobs) # Aggregate the chunk dictionaries and sort by decreasing value aggregated_count = sorted(functools.reduce(lambda a, b: a + b, res_list).items(), key=itemgetter(1), reverse=True) # Print the result if not args.no_stdout: print(aggregated_count) # Write the result to a file as json (sorted list of [index, count] lists) if args.output: with open(args.input + "_frequencies.json", 'w') as out: json.dump(aggregated_count, out) # Close the pool workers pool.close() </code></pre> <p>My questions are: </p> <ul> <li>Is it possible to do this in a single pass in parallel? Now I'm using one pass to determine the chunks, then one more for the processing.</li> <li>Is there a more efficient way to chunk text files? Now I'm using chunks of constant byte size.</li> </ul>
[]
[ { "body": "<p>A few comments, unfortunately not on the multiprocessing part.</p>\n\n<ul>\n<li><p><code>parser.add_argument(\"--output\", action='store_true', default=False)</code> is exactly the same as <code>parser.add_argument(\"--output\", action='store_true')</code>, the <code>'store_true'</code> action mak...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T16:44:16.820", "Id": "205830", "Score": "2", "Tags": [ "python", "parsing", "file", "multiprocessing" ], "Title": "Count features in a file, using parallel code" }
205830
<p>I'm going through the K&amp;R book (2nd edition, ANSI C ver.) and want to get the most from it. How does the following solution look to you? Note that, for the sake of exercise, I don't want to use techniques not introduced yet in the book. Also, I'm trying to reuse whatever code/philosophy already presented in the book.</p> <p>Related: <a href="https://codereview.stackexchange.com/questions/205674/kr-exercise-1-13-printing-histogram-of-word-lengths-horizontal-variant">K&amp;R Exercise 1-13. Printing histogram of word lengths (horizontal variant)</a></p> <h2>Program code</h2> <pre><code>/* Exercise 1-13. Write a program to print a histogram of the lengths of * words in its input. It is easy to draw the histogram with the bars * horizontal; a vertical orientation is more challenging. * */ /* Solution 2: Vertical Bars * */ #include &lt;stdio.h&gt; #define MAXLEN 20 /* Any word longer than this will get counted in * the &gt;MAXLEN histogram. */ #define MAXHEIGHT 20 /* Height for chart printout. * The whole chart will be scaled to fit. */ int main() { int c; int readEOF; int alnumCount; int i, j, k, n, s; int wordCount[MAXLEN+1]; /* Last element will count the * over-length words. */ int wordCountD[MAXLEN+1]; int maxWordCount; int maxWordCountD; int labelD[MAXLEN+1]; float scale; int npow; for (i = 0; i &lt;= MAXLEN; ++i) wordCount[i] = 0; /* Perform the counting */ alnumCount = 0; readEOF = 0; /* State to avoid having to repeat code just for the * last word, should it be terminated with EOF. */ c = getchar(); while (readEOF == 0) { if ((c &gt;= '0' &amp;&amp; c &lt;= '9') || (c &gt;= 'a' &amp;&amp; c &lt;= 'z') || (c &gt;= 'A' &amp;&amp; c &lt;= 'Z')) ++alnumCount; else { if (alnumCount &gt; 0) { if (alnumCount &lt;= MAXLEN) ++wordCount[alnumCount-1]; else ++wordCount[MAXLEN]; alnumCount = 0; } } if ((readEOF = (c == EOF)) == 0) /* ! operator not introduced * yet */ c = getchar(); } /* Chart Printing Section * */ /* The chart will look like: * N * 1 1 * 1 1 * * * * * * 0 * - - - - - - * 1 2 3 4 M &gt; * M * showing both the label and the histogram value, so we can display * accurate information in addition to scaled graphical * representation. * */ /* Calculate number of digits for each histogram count, * and find the maximums for both the count &amp; number of digits */ maxWordCount = 0; maxWordCountD = 0; for (i = 0; i &lt;= MAXLEN; ++i) { wordCountD[i] = 1; for (j = wordCount[i]; j &gt;= 10; j = j/10) ++wordCountD[i]; if (maxWordCount &lt; wordCount[i]) maxWordCount = wordCount[i]; if (maxWordCountD &lt; wordCountD[i]) maxWordCountD = wordCountD[i]; } /* Calculate number of digits for each label */ for (i = 0; i &lt; MAXLEN; ++i) { labelD[i] = 1; for (j = i + 1; j &gt;= 10; j = j/10) ++labelD[i]; } labelD[MAXLEN] = labelD[MAXLEN-1]; /* Calculate the scale factor */ scale = 1.0*(MAXHEIGHT - maxWordCountD - 1 - 1 - labelD[MAXLEN]) / maxWordCount; /* Fix a scale rounding bug resulting in chart being 1 line * shorter for some cases */ if (scale * maxWordCount &lt; MAXHEIGHT - maxWordCountD - 1 - 1 - labelD[MAXLEN]) scale = scale + 0.000001; /* Print the chart only if MAXHEIGHT is sufficient to print at least * the values */ if (maxWordCount * scale &gt;= 0) { /* Print vertical histogram. */ /* Row loop, plot count &amp; histograms */ for (i = MAXHEIGHT - 1 - 1 - labelD[MAXLEN]; i &gt; 0; --i) { /* Column loop */ for (j = 0; j &lt;= MAXLEN; ++j) { if (i &lt;= wordCount[j] * scale) printf("* "); else { /* What digit do we have to print? */ n = wordCountD[j] - (i - wordCount[j] * scale) + 1; if (n &gt; 0) { n = wordCountD[j] + 1 - n; npow = 1; for (k = n; k &gt; 1; --k) npow = npow * 10; /* Calculate &amp; print the required digit. * Note: % operator not yet introduced. */ printf("%d ", (wordCount[j]/npow) - (wordCount[j]/npow)/10*10); } else printf(" "); } } putchar('\n'); } /* Column loop, plot axis */ for (j = 0; j &lt;= MAXLEN; ++j) printf("--"); putchar('\n'); /* Row loop, plot labels */ for (i = 0; i &lt;= labelD[MAXLEN]; ++i) { /* Column loop */ for (j = 0; j &lt;= MAXLEN; ++j) { /* Tweak for the last label, print '&gt;' and "virtually" * shift the row further on. */ if ((s = (j == MAXLEN)) &amp;&amp; i == 0) printf("&gt; "); /* What digit do we have to print? */ n = labelD[j] - (i-s); if (n &gt; 0 &amp;&amp; n &lt;= labelD[j]) { npow = 1; for (k = n; k &gt; 1; --k) npow = npow * 10; /* Calculate &amp; print the required digit. * Note: % operator not yet introduced. */ printf("%d ", ((j+1-s) / npow) - ((j+1-s) / npow)/10*10); } else printf(" "); } putchar('\n'); } } else printf("Error: insufficient screen width for print-out.\n"); } </code></pre> <h2>Output when run on the program code</h2> <pre><code>$ ./ch1-ex-1-13-02 &lt; ch1-ex-1-13-02.c 1 6 8 * * * * * * * 7 * 5 3 6 5 6 * 9 * 4 5 3 * * * * * * 3 * * * * * * 2 1 0 2 * * * * * * 0 7 * 1 * * * * * * * * * * 3 8 6 1 0 0 0 0 0 0 0 ------------------------------------------ 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 2 &gt; 0 1 2 3 4 5 6 7 8 9 0 2 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:18:13.140", "Id": "397030", "Score": "0", "body": "I take it you haven't got to `isalnum()` yet? Comparing character values (apart from the digits, which are specified to be consecutive) is fragile!" }, { "ContentLicense...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:01:20.100", "Id": "205832", "Score": "3", "Tags": [ "beginner", "c", "io", "ascii-art", "data-visualization" ], "Title": "K&R Exercise 1-13. Printing histogram of word lengths (vertical variant)" }
205832
<p>In order to avoid having to make any real progress (at least for a short time), I wrote a script that measures how much progress I have made so far, instead. Specifically, this script sums up the file sizes of files in all commits of a git repository, filtering files either by their endings, a whitelist or not at all, and plots this size against the commit dates.</p> <p>This script needs <a href="https://pypi.org/project/GitPython/" rel="nofollow noreferrer"><code>gitpython</code></a> to work.</p> <pre><code>import argparse import git import matplotlib.pyplot as plt import numpy as np import os def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--dir", help="Directory of the git repository to analyze (default: '.')", default=os.curdir) parser.add_argument("--pattern", help="Count only files ending in pattern") parser.add_argument("--files", help="Only count these files", nargs='+') return parser.parse_args() def filter_pattern(pattern): """Returns a function that returns True if the file name ends with pattern""" return lambda file: file.name.endswith(pattern) def filter_whitelist(whitelist): """Returns a function that returns True if the file name is in whitelist""" whitelist = set(whitelist) return lambda file: file.name in whitelist def get_file_sizes(commit, filter_func=None): """Return the sum of the file sizes in the commit. Counts only files passing filter_func. """ return sum(file.size for file in filter(filter_func, commit.tree.traverse())) def get_file_sizes_per_commit(repo, filter_func=None): """Get the filesizes in all commits of repo. Counts only files passing filter_func. Ordered from oldest to newest commit. """ return np.array([get_file_sizes(commit, filter_func) for commit in repo.iter_commits()])[::-1] def get_commit_dates(repo): """Get the commit dates of all commits in repo. Ordered from oldest to newest. """ return np.array([commit.committed_datetime for commit in repo.iter_commits()])[::-1] def plot_repo_size(repo, filter_func): sizes = get_file_sizes_per_commit(repo, filter_func) dates = get_commit_dates(repo) plt.plot(dates, sizes) plt.ylabel("Repository size") plt.xlabel("Commit date") plt.yscale("log") plt.show() if __name__ == "__main__": args = parse_args() filter_func = filter_whitelist(args.files) if args.files else filter_pattern(args.pattern) if args.pattern else None repo = git.Repo(args.dir) plot_repo_size(repo, filter_func) </code></pre> <p>I am looking for general feedback as well as how to improve setting the filter function from the parsed arguments.</p> <p>I am aware that it is not strictly necessary for the data I'm plotting to be <code>numpy.array</code>s, but I wanted to be able to expand this script in the future and they are just easier to work with (I might even make it a <code>pandas.DataFrame</code> to be able to restrict the date range, interpolate to the future, etc).</p> <p>With the repository I am using this on, this produces the following image when run with <code>python plot_progress.py --pattern .tex</code>:</p> <p><a href="https://i.stack.imgur.com/03nJJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/03nJJ.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T19:41:32.203", "Id": "397062", "Score": "0", "body": "Say you have 2 files. One of them doubles in size and the other loses half it's size. What is your actual and expected output? As in, is it already counting absolute values or wi...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:06:30.363", "Id": "205833", "Score": "5", "Tags": [ "python", "git", "matplotlib" ], "Title": "Measure size of repository as a function of time" }
205833
<p>This is a C# console application that displays the n terms of even natural numbers between (1 and 100) and their sum</p> <p>Is this good? Or is it bug riddled ?</p> <pre><code>int numberOfEvenNumbers; int currentNumber; currentNumber = 0; int counter; counter = 1; int sum; sum = 0; Console.Write("How many even numbers :"); numberOfEvenNumbers = Convert.ToInt32(Console.ReadLine()); while (counter &lt;= 100) { if (counter % 2 == 0) { Console.WriteLine(counter); sum += counter; currentNumber++; } if (currentNumber == numberOfEvenNumbers) { break; } counter++; } Console.Write("Sum : "); Console.WriteLine(sum); Console.ReadLine(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:36:34.213", "Id": "397036", "Score": "0", "body": "This code looks incomplete. Could you copy/paste the entire method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T19:17:05.453", "Id": "3970...
[ { "body": "<pre><code>int numberOfEvenNumbers;\n\n// can be inlined in a for-loop\n// int currentNumber = 0;\n// int counter = 1;\n\n// int sum;\n// sum = 0;\nint sum = 0;\n\nConsole.Write(\"How many even numbers :\"); \nnumberOfEvenNumbers = Convert.ToInt32(Console.ReadLine());\n\n// while (counter &lt;= 10...
{ "AcceptedAnswerId": "205848", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:35:28.790", "Id": "205836", "Score": "3", "Tags": [ "c#", "console" ], "Title": "Display the n terms of even natural numbers(between 1 and 100) and their sum" }
205836
<p>What I want to do is build a <em>Slay-the-Spire</em>-like Map. As you can see in the following image, the map is splitted in <code>ISteps</code> and <code>IRooms</code>. Each <code>IStep</code> is connected to the next one by its <code>IRooms</code>. There is no dead-end, so each <code>IRooms</code> is connected with the previous and next <code>ISteps</code>.</p> <p><a href="https://i.stack.imgur.com/9ikyY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ikyY.png" alt="Slay the Spire - Generated map"></a></p> <p>Firstly, I have these two <code>C#</code> interfaces:</p> <pre><code>public interface IStep { IRoom this[int index] { get; } int Size { get; } void Connect(IStep nextStep, int[,] matrix); } public interface IRoom { IRoom[] NextRooms { get; } void Connect(IRoom nextRoom); } </code></pre> <p>Here is what I want to achieve: </p> <blockquote> <ul> <li>A <code>IStep</code> has a set of 3-to-5 <code>IRooms</code>.</li> <li>I can connect two <code>ISteps</code> together, which connects the <code>IRooms</code>.</li> <li>Each <code>IRoom</code> has at least one connection to the other <code>IStep</code> ...</li> <li>... and at most three</li> <li>Connections cannot cross, but can begin from / end to the same <code>IRoom</code></li> </ul> </blockquote> <p>Here is what is true:</p> <blockquote> <ul> <li>The minimum number of connections is equal to the larger <code>IStep.Size</code></li> <li>The maximum number is equal to both <code>IStep.Size</code> minus <code>1</code></li> <li>Each row and each column has to contains at least one <code>1</code></li> </ul> </blockquote> <p>I decided to represent these connections in a matrix-like display:<br> <span class="math-container">\begin{bmatrix} 1 &amp; 1 &amp; 0 &amp; 0 &amp; 0\\ 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1\\ 0 &amp; 0 &amp; 0 &amp; 0 &amp; 1 \end{bmatrix}</span> This matrix says:</p> <blockquote> <ul> <li><code>IStep from</code> is connected to <code>IStep to</code></li> <li><code>from.Size = 3</code> and <code>to.Size = 5</code></li> <li>There is a total of 6 connections</li> <li><code>from[0]</code> is connected to <code>to[0]</code></li> <li><code>from[0]</code> is also connected to <code>to[1]</code></li> <li>...</li> <li><code>from[2]</code> is connected to <code>to[4]</code></li> </ul> </blockquote> <hr> <p>To create this matrix, I use the following <code>F#</code> module:</p> <pre><code>type CellType = | Uncertain | Disconnected | Connected module Connector2D = let getAt array row col = Array2D.get array row col let setAt array row col value = Array2D.set array row col value let len1 array = Array2D.length1 array let len2 array = Array2D.length2 array let IsUncertain array row col = getAt array row col = Uncertain let IsDisconnected array row col = getAt array row col = Disconnected let IsConnected array row col = getAt array row col = Connected let filterBy predicate array = seq { for i in 0 .. len1 array - 1 do for j in 0 .. len2 array - 1 do if predicate array i j then yield (i, j) } let ListUncertain array = array |&gt; filterBy IsUncertain let ListDisconnected array = array |&gt; filterBy IsDisconnected let ListConnected array = array |&gt; filterBy IsConnected let CountUncertain array = ListUncertain array |&gt; Seq.length let CountDisconnection array = ListDisconnected array |&gt; Seq.length let CountConnection array = ListConnected array |&gt; Seq.length let Disconnect array row col = match getAt array row col with | Uncertain -&gt; setAt array row col Disconnected true | Connected -&gt; false | Disconnected -&gt; true // Check no-cross rule let Connect array row col = if IsUncertain array row col then setAt array row col Connected // Disconnect all 'top-right' connections for i in 0 .. row - 1 do for j in col + 1 .. len2 array - 1 do Disconnect array i j |&gt; ignore // Disconnect all 'bottom-left' connections for i in row + 1 .. len1 array - 1 do for j in 0 .. col - 1 do Disconnect array i j |&gt; ignore IsConnected array row col // Check no-more-than-three rule let Create rows cols = let matrix = Array2D.create rows cols Uncertain Connect matrix 0 0 |&gt; ignore Connect matrix (rows - 1) (cols - 1) |&gt; ignore for i in 3 .. rows - 1 do Disconnect matrix i 0 |&gt; ignore for i in 0 .. rows - 4 do Disconnect matrix i (cols - 1) |&gt; ignore for j in 3 .. cols - 1 do Disconnect matrix 0 j |&gt; ignore for j in 0 .. cols - 4 do Disconnect matrix (rows - 1) j |&gt; ignore matrix </code></pre> <p>And my matrix creation method is this one:</p> <pre><code>public void Connect(IStep from, IStep to) { Random rnd = new Random(); int min = Math.Max(from.Size, to.Size); int max = from.Size + to.Size; int count = rnd.Next(min, max); int[,] matrix = MapConnections.Create(from.Size, to.Size); List&lt;int&gt; emptyRows = Enumerable.Range(1, from.Size - 2).ToList(); List&lt;int&gt; emptyCols = Enumerable.Range(1, to.Size - 2).ToList(); while (MapConnections.CountConnection(matrix) &lt; count) { var possibleConnections = MapConnections.ListUncertain(matrix).ToList(); var tmp = possibleConnections.Where(pc =&gt; emptyRows.Contains(pc.Item1) &amp;&amp; emptyCols.Contains(pc.Item2)).ToList(); if (tmp.Count == 0) tmp = possibleConnections.Where(pc =&gt; emptyRows.Contains(pc.Item1) || emptyCols.Contains(pc.Item2)).ToList(); if (tmp.Count != 0) possibleConnections = tmp; var connection = possibleConnections[rnd.Next(possibleConnections.Count)]; MapConnections.Connect(matrix, connection.Item1, connection.Item2); emptyRows.Remove(connection.Item1); emptyCols.Remove(connection.Item2); } from.Connect(to, matrix); } </code></pre> <hr> <p>An example of what my algorithm should do is (for 5 connections goal):</p> <p><span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; - &amp; -\\ - &amp; - &amp; - &amp; -\\ 0 &amp; - &amp; - &amp; 1 \end{bmatrix}</span> <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; 1 &amp; -\\ 0 &amp; 0 &amp; - &amp; -\\ 0 &amp; 0 &amp; - &amp; 1 \end{bmatrix}</span> <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; 1 &amp; -\\ 0 &amp; 0 &amp; - &amp; 1\\ 0 &amp; 0 &amp; 0 &amp; 1 \end{bmatrix}</span> <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; 0 &amp; 0\\ - &amp; 1 &amp; 1 &amp; -\\ 0 &amp; 0 &amp; - &amp; 1\\ 0 &amp; 0 &amp; 0 &amp; 1 \end{bmatrix}</span></p> <hr> <p>My actual problem is that I can encounter this scenario (for 4 connections goal):</p> <p><span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; - &amp; -\\ - &amp; - &amp; - &amp; -\\ 0 &amp; - &amp; - &amp; 1 \end{bmatrix}</span> <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; 1 &amp; -\\ 0 &amp; 0 &amp; - &amp; -\\ 0 &amp; 0 &amp; - &amp; 1 \end{bmatrix}</span> <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; 1 &amp; -\\ 0 &amp; 0 &amp; - &amp; 1\\ 0 &amp; 0 &amp; 0 &amp; 1 \end{bmatrix}</span></p> <p>Finally, nothing is connected to my <code>to[1]</code>. For this very example, I could force the ones to be in the diagonal, but I want to achieve is a generic algorithm, not a <em>case-by-case</em> one.</p> <hr> <p>If you wonder, there are all the <em>bad selections</em> for a <em>first-connection</em>, in every case (apply symmetry):</p> <blockquote> <ul> <li><p>For 4 connections: <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; * &amp; -\\ - &amp; * &amp; - &amp; -\\ 0 &amp; - &amp; - &amp; 1 \end{bmatrix}</span></p></li> <li><p>For 5 connections: <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0\\ - &amp; - &amp; * &amp; 0\\ - &amp; - &amp; - &amp; -\\ 0 &amp; * &amp; - &amp; -\\ 0 &amp; - &amp; - &amp; 1 \end{bmatrix}</span> <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0 &amp; 0\\ - &amp; - &amp; * &amp; * &amp; 0\\ - &amp; * &amp; - &amp; * &amp; -\\ 0 &amp; * &amp; * &amp; - &amp; -\\ 0 &amp; 0 &amp; - &amp; - &amp; 1 \end{bmatrix}</span></p></li> <li><p>For 6 connections: <span class="math-container">\begin{bmatrix} 1 &amp; - &amp; - &amp; 0 &amp; 0\\ - &amp; - &amp; - &amp; * &amp; 0\\ - &amp; - &amp; - &amp; - &amp; -\\ 0 &amp; * &amp; - &amp; - &amp; -\\ 0 &amp; 0 &amp; - &amp; - &amp; 1 \end{bmatrix}</span></p></li> </ul> </blockquote> <hr> <p>As asked, here are my classes and tests:</p> <pre><code>public class Step : IStep { private IRoom[] Rooms { get; set; } public IRoom this[int index] { get { return Rooms[index]; } } public int Size { get { return Rooms.Length; } } public Step(IRoom first, IEnumerable&lt;IRoom&gt; rooms) : this(first, rooms.ToArray()) { } public Step(IRoom first, params IRoom[] rooms) { Rooms = new IRoom[] { first }.Concat(rooms).ToArray(); } public void Connect(IStep nextStep, int[,] matrix) { for (int i = 0; i &lt; Size; i++) for (int j = 0; j &lt; nextStep.Size; j++) if (MapConnections.IsConnected(matrix, i, j)) this[i].Connect(nextStep[j]); } } public /*abstract*/ class Room : IRoom { public IRoom[] NextRooms { get; private set; } public void Connect(IRoom nextRoom) { if (NextRooms == null) NextRooms = new[] { nextRoom }; else NextRooms = NextRooms.Concat(new[] { nextRoom }).ToArray(); } } public interface IStepConnector { void Connect(IStep from, IStep to); } public class StepConnector : IStepConnector { public void Connect(IStep from, IStep to) { Random rnd = new Random(); int min = Math.Max(from.Size, to.Size); int max = from.Size + to.Size; int count = rnd.Next(min, max); int[,] matrix = MapConnections.Create(from.Size, to.Size); List&lt;int&gt; emptyRows = Enumerable.Range(1, from.Size - 2).ToList(); List&lt;int&gt; emptyCols = Enumerable.Range(1, to.Size - 2).ToList(); while (MapConnections.CountConnection(matrix) &lt; count) { var possibleConnections = MapConnections.ListUncertain(matrix).ToList(); var tmp = possibleConnections.Where(pc =&gt; emptyRows.Contains(pc.Item1) &amp;&amp; emptyCols.Contains(pc.Item2)).ToList(); if (tmp.Count == 0) tmp = possibleConnections.Where(pc =&gt; emptyRows.Contains(pc.Item1) || emptyCols.Contains(pc.Item2)).ToList(); if (tmp.Count != 0) possibleConnections = tmp; var connection = possibleConnections[rnd.Next(possibleConnections.Count)]; MapConnections.Connect(matrix, connection.Item1, connection.Item2); emptyRows.Remove(connection.Item1); emptyCols.Remove(connection.Item2); } from.Connect(to, matrix); } } [TestMethod] public void CodeReviewTest() { IStep from = new Step(new FightRoom(), new FightRoom(), new FightRoom(), new FightRoom(), new FightRoom()); IStep to = new Step(new FightRoom(), new FightRoom(), new FightRoom(), new FightRoom(), new FightRoom()); IStepConnector connector = new StepConnector(); connector.Connect(from, to); List&lt;IRoom&gt; toRooms = new List&lt;IRoom&gt;(); for (int i = 0; i &lt; 5; i++) { Assert.IsTrue(from[i].NextRooms.Length &gt; 0); for (int j = 0; j &lt; from[i].NextRooms.Length; j++) { if (!toRooms.Contains(from[i].NextRooms[j])) toRooms.Add(from[i].NextRooms[j]); } } for (int j = 0; j &lt; 5; j++) { Assert.IsTrue(toRooms.Contains(to[j])); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T05:17:15.390", "Id": "397106", "Score": "2", "body": "Welcome to CodeReview. If you want a serious review of your code, I think you have to provide a little more background, context, a simple example and some full implementations of...
[]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:37:38.763", "Id": "205837", "Score": "5", "Tags": [ "c#", "matrix", "f#" ], "Title": "Creation of matrix with specific attempts at the end" }
205837
<p>I'm a beginner at coding who recently started learning Python, and I think I have grasped the basics. Now I'm working on my first "proper" project in Python.</p> <p>The problem is to have the program:</p> <ol> <li>Generate a standard Poker deck of 52 cards (no Jokers)</li> <li>Shuffle said deck</li> <li>Deal five (5) cards to three (3) hands/"players" (can be altered when calling the 'deal' function)</li> <li>Analyse the three hands individually for possible Poker hands in each <ul> <li>the analysis must be able to detect at least: <ul> <li>Two pairs</li> <li>Straight</li> <li>Flush</li> <li>Straight Flush</li> <li>(no harm in detecting any of the other Poker hands as well)</li> </ul></li> </ul></li> <li>Print all three hands and their respective results/analyses</li> </ol> <p>I've managed 1-3, but stalled at 4 and plan to continue with 4-5 later, but first I want to hear your thoughts on my code so far!</p> <p>I managed to find several somewhat similar programs all over the Internet, of which I extracted many parts to my own program. I had to make a few adjustments here and there, as none of the existing programs had the exact same approach as mine, but this was a good thing in terms of my learning curve. In case you find a part of your own code in mine, consider it admiration, for I'm truly grateful for all the help and examples I've received from more seasoned coders' work.</p> <p>My code:</p> <pre><code>import random class Card(object): def __init__(self, suit, val): self.suit = suit self.value = val # Implementing build in methods so that you can print a card object def __unicode__(self): return self.show() def __str__(self): return self.show() def __repr__(self): return self.show() def show(self): if self.value == 1: val = "Ace" elif self.value == 11: val = "Jack" elif self.value == 12: val = "Queen" elif self.value == 13: val = "King" else: val = self.value return "{} of {}".format(val, self.suit) class Deck(object): def __init__(self): self.cards = [] self.build() # Display all cards in the deck def show(self): for card in self.cards: print(card.show()) # Generate 52 cards def build(self): self.cards = [] for suit in ['Hearts', 'Clubs', 'Diamonds', 'Spades']: for val in range(1,14): self.cards.append(Card(suit, val)) # Shuffle the deck def shuffle(self, num=1): random.shuffle(self.cards) # Deal n cards to n players def deal(self, n_players, n_cards): self.hands = [self.cards[i:n_players*n_cards:n_players] for i in range(0, n_players)] # Test making a Card # card = Card('Spades', 6) # print card # Making a Deck myDeck = Deck() myDeck.shuffle() #myDeck.show() # Print the shuffled deck if needed, to show it is actually shuffled # and that the cards are dealt from top of the deck and not randomly myDeck.deal(3,5) #(No. of hands, no. of cards dealt per hand) print(*myDeck.hands, sep = '\n') </code></pre> <p>Please do let me know what you think of the code in general, and if you think there is a more efficient way to have the cards dealt so that they are also easier to analyse later. All help is much appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T18:25:13.117", "Id": "397046", "Score": "0", "body": "@TobySpeight Edited. I think it's more in line now - do you concur?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T19:53:37.950", "Id": "3970...
[ { "body": "<p>You've got a reasonable implementation for steps 1-3. I see no glaring issues with the code. Perhaps, we can over-engineer some parts of it.</p>\n\n<h2>General</h2>\n\n<p>Add docstrings.</p>\n\n<h2>class Card</h2>\n\n<p>It is mutable. I can be dealt the '6 of Spades' and by tweaking it <code>ca...
{ "AcceptedAnswerId": "205868", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T17:38:44.683", "Id": "205838", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "playing-cards" ], "Title": "Deal three Poker hands of five cards each in Python" }
205838
<p>I am wondering if someone can do a code re"vue" specifically for my star rating component ([complete code available <a href="https://github.com/Shreerang/Vue-Nuggets/blob/master/src/components/StarRating/StarRating.vue" rel="nofollow noreferrer">on github</a>).</p> <p>I am looking for feedback on best practices, any glaring code crimes I might have committed and bad code.</p> <p>The code is also deployed to #Heroku <a href="https://ecommerce-vue-nuggets.herokuapp.com/" rel="nofollow noreferrer">here</a></p> <p>Problems I saw with the code previous code are also included.</p> <ol> <li>The partial star sometimes just gets the default colors, even if the DOM has the colors assigned via props.</li> <li>Change in data (using Vue Dev Tools) does not re-render my star rating component. For the benefit for the code reviewers, I have hosted the component on Heroku, so if you have the Vue dev tools, you can test this too.</li> </ol> <p><strike>Edit - Inlined the code to follow the code-review standards.</strike></p> <p>Edit - 10/23 - I have updated the code since I first posted this and seem to have resolved all the issues with my previous code. The link to Github is <a href="https://github.com/Shreerang/Vue-Nuggets/blob/master/src/components/StarRating/StarRating.vue" rel="nofollow noreferrer">here</a>. Also the inlined code is now newer... I have added comments in the code, where I would love some feedback and comments.</p> <pre><code> &lt;template&gt; &lt;div&gt; &lt;!-- Is this use of dynamic component correct? --&gt; &lt;component v-for="n of this.totalStarsData" :key="n" :is="currentComponent(n)" :fillColor="ratingData - n &gt; -1 ? fillColorData : baseColorData" :baseColor="baseColorData" :rating="ratingData"&gt;&lt;/component&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; // Can Star and PartialStar components be dynamically imported? import Star from "./Star" import PartialStar from "./PartialStar" // Using a global variable like this - Good or bad? let isPartialRendered = false export default { name: 'star-rating', components: { Star, PartialStar }, props: { totalStars: { type: Number, default: 5 }, rating: { type: Number, required: true }, fillColor: { type: String, default: '#C00' }, baseColor: { type: String, default: '#666' }, }, data(){ return { // Any better way of converting props to data? // Also maybe naming convention best practices? totalStarsData: this.totalStars, ratingData: this.rating, fillColorData: this.fillColor, baseColorData: this.baseColor, } }, methods: { currentComponent: function (count) { const int_part = Math.trunc(this.ratingData); if(count &gt; int_part &amp;&amp; isPartialRendered === false) { isPartialRendered = true; // Re-setting the isPartialRendered flag here, for cases where the Partial SVG is the last SVG if(count === this.totalStarsData){ isPartialRendered = false; } return 'PartialStar' } else { if(count === this.totalStarsData){ isPartialRendered = false; } return 'Star' } } } } &lt;/script&gt; &lt;style scoped&gt; &lt;/style&gt; </code></pre>
[]
[ { "body": "<p>Converting props to data is a bad idea if it is not a copy of the <code>prop</code> because you might end up in a situation where your parent changes your <code>prop</code> and your component changes your <code>data</code> and then which is right? The component manipulating <code>props</code> is n...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T18:19:25.003", "Id": "205841", "Score": "1", "Tags": [ "javascript", "vue.js" ], "Title": "Vue Star Rating Component" }
205841
<p>I created a basic program that allows a user to continuously input values until he or she is satisfied; furthering, the program outputs the mean, median, and range. Then, the code gives you the option to run it again or exit.</p> <pre><code>#Mean, median, and range from clear import * def main(): clear() list_one = [] while True: q = input('Type a number or type stop at any time: ').lower() if q.isnumeric(): list_one.append(int(q)) print(''' Great choice! Choose again or type stop the sequence.''') elif q == 'stop': list_one.sort(key=int) print(''' And the values are...''') def mean(): return 'Mean: ' + str(sum(list_one)/len(list_one)) def median(): length = len(list_one) if length % 2 == 0: return 'Median: ' + str(sum(list_one[length//2-1:length//2+1])/2) else: return 'Median: ' + str(list_one[length//2]) def range_(): return 'Range: ' + str(list_one[-1] - list_one[0]) print(mean()) print(median()) print(range_()) break else: print(''' That\'s not a number or stop! Try again brudda man. ''') def end(): while True: q = input('Type anything and and press enter to repeat or press only \'Enter\' to exit. ') if len(q) &gt;= 1: main() break else: exit() main() while True: q = input(''' Type anything and and press enter to repeat or press only \'Enter\' to exit. ''') if len(q) &gt;= 1: main() else: clear() exit() </code></pre> <p>Additionally, the "clear" library that I imported is a custom library of my making which only prints out a ton of blank lines so the script "clears" and outputs are then at the bottom. If there is a better way of doing this please let me know.</p> <p>I want to get familiar with what is "right" or "wrong" in terms of programming with Python. I would like my work to look professional and practice more respected coding ethics, so please be as harsh as you wish.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T19:56:44.820", "Id": "397070", "Score": "3", "body": "**You need to include your external custom libraries if you have them**. We need ***COMPLETE CODE*** including any additional code libraries you wrote, including `clear`." } ]
[ { "body": "<blockquote>\n <p>Disclaimer: You asked me to be harsh, so I'm not holding back as much. I tried to though...</p>\n</blockquote>\n\n<p>Welcome to Code Review! Your python code has been put through my scrutiny and I have some concerns and suggestions for improvement. Any criticisms and scrutiny ar...
{ "AcceptedAnswerId": "205849", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T19:10:36.743", "Id": "205845", "Score": "9", "Tags": [ "python", "beginner", "python-3.x", "statistics" ], "Title": "Program to accept numbers, then calculate the mean, median, and range" }
205845
<p>Here is my second version of a bash program I'm writing, as per @hjpotter92 I've updated and cleaned it since last:</p> <p>This script is run directly after a fresh install of Debian, to do:</p> <ul> <li><p>sets up LS_COLORS====> colors in <code>/bin/ls</code> output</p></li> <li><p>sets up Portsentry (security for ssh and defence for ports)</p></li> <li><p>sets up syntax highlighting in nano,</p></li> <li><p>sets up iptables,</p></li> <li><p>sets up ssh,</p></li> <li><p>sets up custom bashrc files</p></li> <li><p>creates users on the system if needed,</p></li> <li><p>checks if user has a password set and sets it if not,</p></li> <li><p>installs non-free firmware and sets up apt with virtualbox deb file and multimedia deb.</p></li> </ul> <blockquote> <p>This is from my previous post↓↓↓</p> <p>You have a lot of stub code in the script. Clean it up; remove unused statements/declarations/tasks and post another question with the updated code.</p> </blockquote> <p><strong>QUESTIONS:</strong></p> <p>Can you give me pointers on what could be better or different?</p> <p>Do you have any ideas about new/other features for a <code>setup program</code> for a <code>developer</code> on <code>Debian Stretch(9)</code>?</p> <p><strong>Here is the code:</strong></p> <pre><code>#!/bin/bash -x # redirect all errors to a file exec 2&gt;debianConfigVersion3.1ERRORS.txt ##################################################################################################### exec 3&gt;cpSuccessCodes.txt ## SCRIPTNAME=$(basename "$0") if [ "$UID" != 0 ] then echo "This program should be run as root, exiting! now....." exit 1 fi if [ "$#" -eq 0 ] then echo "RUN AS ROOT...Usage if you want to create users:...$SCRIPTNAME USER_1 USER_2 USER_3 etc." echo "If you create users they will be set with a semi strong password which you need to change later as root with passwd" echo echo echo "#################### ↓↓↓↓↓↓↓↓↓↓↓ OR ↓↓↓↓↓↓↓↓↓↓ #############################" echo echo echo "RUN AS ROOT...Usage without creating users: $SCRIPTNAME" echo sleep 10 fi echo "Here starts the party!" echo "Setting up server..........please wait!!!!!" sleep 3 ### ↓↓↓↓ NEXT TIME USE "declare VARIABLE" ↓↓↓↓↓↓↓↓↓↓ ##### OAUTH_TOKEN=d6637f7ccf109a0171a2f55d21b6ca43ff053616 CURRENTDIR=/tmp/svaka BASHRC=.bashrc NANORC=.nanorc BASHRCROOT=.bashrcroot SOURCE=sources.list SSHD_CONFIG=sshd_config #-----------------------------------------------------------------------↓↓ export DEBIAN_FRONTEND=noninteractive #-----------------------------------------------------------------------↑↑ if grep "Port 22" /etc/ssh/sshd_config then echo -n "Please select/provide the port-number for ssh in iptables and sshd_config:" read port ### when using the "-p" option then the value is stored in $REPLY PORT=$port fi ############################### make all files writable, executable and readable in the working directory######### if /bin/chmod -R 777 "$CURRENTDIR" then continue else echo "chmod CURRENTDIR failed" sleep 3 exit 127 fi ################ Creating new users #####################1 checkIfUser() { for name in "$@" do if /usr/bin/id -u "$name" #&gt;/dev/null 2&gt;&amp;1 then echo "User: $name exists....setting up now!" else echo "User: $name does not exists....creating now!" /usr/sbin/useradd -m -s /bin/bash "$name" #&gt;/dev/null 2&gt;&amp;1 fi done } ###########################################################################3 ################# GET USERS ON THE SYSTEM ################################### prepare_USERS() { checkIfUser "$@" /usr/bin/awk -F: '$3 &gt;= 1000 { print $1 }' /etc/passwd &gt; "$CURRENTDIR"/USERS.txt /bin/chmod 777 "$CURRENTDIR"/USERS.txt if [[ ! -f "$CURRENTDIR"/USERS.txt &amp;&amp; ! -w "$CURRENTDIR"/USERS.txt ]] then echo "USERS.txt doesn't exist or is not writable..exiting!" exit 127 fi for user in "$@" do echo "$user" &gt;&gt; /tmp/svaka/USERS.txt || { echo "writing to USERS.txt failed"; exit 127; } done } ###########################################################################33 ################33 user passwords2 userPass() { if [[ ! -f "$CURRENTDIR"/USERS.txt &amp;&amp; ! -w "$CURRENTDIR"/USERS.txt ]] then echo "USERS.txt doesn't exist or is not writable..exiting!" exit 127 fi while read i do if [ "$i" = root ] then continue fi if [[ $(/usr/bin/passwd --status "$i" | /usr/bin/awk '{print $2}') = NP ]] || [[ $(/usr/bin/passwd --status "$i" | /usr/bin/awk '{print $2}') = L ]] then echo "$i doesn't have a password." echo "Changing password for $i:" echo $i:$i"YOURSTRONGPASSWORDHERE12345ÁÑ" | /usr/sbin/chpasswd if [ "$?" = 0 ] then echo "Password for user $i changed successfully" sleep 5 fi fi done &lt; "$CURRENTDIR"/USERS.txt } ################################################ setting up iptables ####################3 setUPiptables() { #if ! grep -e '-A INPUT -p tcp --dport 80 -j ACCEPT' /etc/iptables.test.rules if [[ `/sbin/iptables-save | grep '^\-' | wc -l` &gt; 0 ]] then echo "Iptables already set, skipping..........!" else if [ "$PORT" = "" ] then echo "Port not set for iptables exiting" echo -n "Setting port now, insert portnumber: " read port PORT=$port fi if [ ! -f /etc/iptables.test.rules ] then /usr/bin/touch /etc/iptables.test.rules else /bin/cat /dev/null &gt; /etc/iptables.test.rules fi /bin/cat &lt;&lt; EOT &gt;&gt; /etc/iptables.test.rules *filter # Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0 -A INPUT -i lo -j ACCEPT -A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT # Accepts all established inbound connections -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Allows all outbound traffic # You could modify this to only allow certain traffic -A OUTPUT -j ACCEPT # Allows HTTP and HTTPS connections from anywhere (the normal ports for websites) -A INPUT -p tcp --dport 80 -j ACCEPT -A INPUT -p tcp --dport 443 -j ACCEPT # Allows SSH connections # The --dport number is the same as in /etc/ssh/sshd_config -A INPUT -p tcp -m state --state NEW --dport $PORT -j ACCEPT # Now you should read up on iptables rules and consider whether ssh access # for everyone is really desired. Most likely you will only allow access from certain IPs. # Allow ping # note that blocking other types of icmp packets is considered a bad idea by some # remove -m icmp --icmp-type 8 from this line to allow all kinds of icmp: # https://security.stackexchange.com/questions/22711 -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT # log iptables denied calls (access via dmesg command) -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7 # Reject all other inbound - default deny unless explicitly allowed policy: -A INPUT -j REJECT -A FORWARD -j REJECT COMMIT EOT sed "s/^[ \t]*//" -i /etc/iptables.test.rules ## remove tabs and spaces /sbin/iptables-restore &lt; /etc/iptables.test.rules || { echo "iptables-restore failed"; exit 127; } /sbin/iptables-save &gt; /etc/iptables.up.rules || { echo "iptables-save failed"; exit 127; } /usr/bin/printf "#!/bin/bash\n/sbin/iptables-restore &lt; /etc/iptables.up.rules" &gt; /etc/network/if-pre-up.d/iptables ## create a script to run iptables on startup /bin/chmod +x /etc/network/if-pre-up.d/iptables || { echo "chmod +x failed"; exit 127; } fi } ###################################################33 sshd_config4 setUPsshd() { if grep "Port $PORT" /etc/ssh/sshd_config then echo "sshd already set, skipping!" else if [ "$PORT" = "" ] then echo "Port not set" exit 12 fi users="" /bin/cp -f "$CURRENTDIR"/sshd_config /etc/ssh/sshd_config sed -i "s/Port 34504/Port $PORT/" /etc/ssh/sshd_config for user in `awk -F: '$3 &gt;= 1000 { print $1 }' /etc/passwd` do users+="${user} " done if grep "AllowUsers" /etc/ssh/sshd_config then sed -i "/AllowUsers/c\AllowUsers $users" /etc/ssh/sshd_config else sed -i "6 a \ AllowUsers $users" /etc/ssh/sshd_config fi /bin/chmod 644 /etc/ssh/sshd_config /etc/init.d/ssh restart fi } #################################################3333 Remove or comment out DVD/cd line from sources.list5 editSources() { if grep '^# *deb cdrom:\[Debian' /etc/apt/sources.list then echo "cd already commented out, skipping!" else sed -i '/deb cdrom:\[Debian GNU\/Linux/s/^/#/' /etc/apt/sources.list fi } ####################################################33 update system6 updateSystem() { /usr/bin/apt update &amp;&amp; /usr/bin/apt upgrade -y } ###############################################################7 ############################# check if programs installed and/or install checkPrograms() { if [ ! -x /usr/bin/git ] || [ ! -x /usr/bin/wget ] || [ ! -x /usr/bin/curl ] || [ ! -x /usr/bin/gcc ] || [ ! -x /usr/bin/make ] then echo "Some tools with which to work with data not found installing now......................" /usr/bin/apt install -y git wget curl gcc make fi } #####################################################3 update sources.list8 updateSources() { if grep "deb http://www.deb-multimedia.org" /etc/apt/sources.list then echo "Sources are setup already, skipping!" else sudo /bin/cp -f "$CURRENTDIR"/"$SOURCE" /etc/apt/sources.list || { echo "sudo cp failed"; exit 127; } /bin/chmod 644 /etc/apt/sources.list /usr/bin/wget http://www.deb-multimedia.org/pool/main/d/deb-multimedia-keyring/deb-multimedia-keyring_2016.8.1_all.deb || { echo "wget failed"; exit 127; } /usr/bin/dpkg -i deb-multimedia-keyring_2016.8.1_all.deb /usr/bin/wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add - updateSystem || { echo "update system failed"; exit 127; } /usr/bin/apt install -y vlc vlc-data browser-plugin-vlc mplayer youtube-dl libdvdcss2 libdvdnav4 libdvdread4 smplayer mencoder build-essential sleep 3 updateSystem || { echo "update system failed"; exit 127; } sleep 3 fi } ###############################################33 SETUP PORTSENTRY ############################################################ ##############################################3 ############################################################33 setup_portsentry() { if ! grep -q '^TCP_PORTS="1,7,9,11,15,70,79' /etc/portsentry/portsentry.conf || [[ ! -f /etc/portsentry/portsentry.conf ]] then /usr/bin/apt install -y portsentry logcheck /bin/cp -f "$CURRENTDIR"/portsentry.conf /etc/portsentry/portsentry.conf || { echo "cp portsentry failed"; exit 127; } /usr/sbin/service portsentry restart || { echo "service portsentry restart failed"; exit 127; } fi } ###############################################################################################################################33 #####################################################3 run methods here↓ ###################################################3 ##################################################### ################################################### prepare_USERS "$@" userPass "$@" setUPiptables setUPsshd editSources updateSystem setup_portsentry checkPrograms updateSources ########################################################################################################### #####3## ##############################################################################################################3Methods ##########################################3 Disable login www ######### passwd -l www-data #################################### firmware apt install -y firmware-linux-nonfree firmware-linux sleep 5 ################ NANO SYNTAX-HIGHLIGHTING #####################3 if [ ! -d "$CURRENTDIR"/nanorc ] then if [ "$UID" != 0 ] then echo "This program should be run as root, goodbye!" exit 127 else echo "Doing user: $USER....please, wait\!" /usr/bin/git clone https://$OAUTH_TOKEN:x-auth-basic@github.com/gnihtemoSgnihtemos/nanorc || { echo "git failed"; exit 127; } cd "$CURRENTDIR"/nanorc || { echo "cd failed"; exit 127; } /usr/bin/make install-global || { echo "make failed"; exit 127; } /bin/cp -f "$CURRENTDIR/$NANORC" /etc/nanorc &gt;&amp;3 || { echo "cp failed"; exit 127; } /bin/chown root:root /etc/nanorc || { echo "chown failed"; exit 127; } /bin/chmod 644 /etc/nanorc || { echo "chmod failed"; exit 127; } if [ "$?" = 0 ] then echo "Implementing a custom nanorc file succeeded!" else echo "Nano setup DID NOT SUCCEED\!" exit 127 fi echo "Finished setting up nano!" fi fi ################ LS_COLORS SETTINGS ############################# if ! grep 'eval $(dircolors -b $HOME/.dircolors)' /root/.bashrc then echo "Setting root bashrc file....please wait!!!!" if /bin/cp -f "$CURRENTDIR/$BASHRCROOT" "$HOME"/.bashrc then echo "Root bashrc copy succeeded!" else echo "Root bashrc cp failed, exiting now!" exit 127 fi /bin/chown root:root "$HOME/.bashrc" || { echo "chown failed"; exit 127; } /bin/chmod 644 "$HOME/.bashrc" || { echo "failed to chmod"; exit 127; } /usr/bin/wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors || { echo "wget failed"; exit 127; } echo 'eval $(dircolors -b $HOME/.dircolors)' &gt;&gt; "$HOME"/.bashrc fi while read user do if [ "$user" = root ] then continue fi sudo -i -u "$user" user="$user" CURRENTDIR="$CURRENTDIR" BASHRC="$BASHRC" bash &lt;&lt;'EOF' if grep 'eval $(dircolors -b $HOME/.dircolors)' "$HOME"/.bashrc then : else echo "Setting users=Bashrc files!" if /bin/cp -f "$CURRENTDIR"/"$BASHRC" "$HOME/.bashrc" then echo "Copy for $user (bashrc) succeeded!" sleep 3 else echo "Couldn't cp .bashrc for user $user" exit 127 fi /bin/chown $user:$user "$HOME/.bashrc" || { echo "chown failed"; exit 127; } /bin/chmod 644 "$HOME/.bashrc" || { echo "chmod failed"; exit 127; } /usr/bin/wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors || { echo "wget failed"; exit 127; } echo 'eval $(dircolors -b $HOME/.dircolors)' &gt;&gt; "$HOME"/.bashrc fi EOF done &lt; "$CURRENTDIR"/USERS.txt echo "Finished setting up your system!" cd ~/ || { echo "cd ~/ failed"; exit 155; } rm -rf /tmp/svaka || { echo "Failed to remove the install directory!!!!!!!!"; exit 155; } </code></pre> <p>I've checked the program into <a href="https://www.shellcheck.net/" rel="nofollow noreferrer">https://www.shellcheck.net/</a></p>
[]
[ { "body": "<p>It's good you're taking advices and improving your script.\nThere's still much work to do, so keep it up!</p>\n\n<h3>Never do <code>chmod 777</code></h3>\n\n<p>I haven't seen a single valid use case of permission 777 in recent memory.\nAnd there's no valid use case of it in this script.\nDon't tak...
{ "AcceptedAnswerId": "205887", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T19:57:29.767", "Id": "205847", "Score": "3", "Tags": [ "beginner", "bash", "linux", "shell", "installer" ], "Title": "Bash program that sets up and configures the environment for new Debian installs" }
205847