body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a Word Search algorithm, the main function (<code>wsearch</code>) takes a grid of letters as an input and a 'word' to search for. The output is the number of occurence of the 'word' in the grid.</p> <p>First, I break down the problem into three functions (including <code>wsearch</code>).</p> <ol> <li><p>The <code>nword</code> is for looking the number of occurence of a 'word' in a string. For example: string <code>bananana</code> has 4 occurence of word <code>nana</code>. Note that occurence of <code>anan</code> is counted as <code>nana</code> (backward).</p></li> <li><p>The <code>fdiags</code> stands for 'find all diagonals' or the grid/matrix. It returns a list of all strings representing the diagonals.</p></li> <li><p>Finally, the <code>wsearch</code> uses the 2 functions above.</p></li> </ol> <p>Example:</p> <pre><code>grid = [list(input()) for j in range(5)] word = input() wsearch(grid, word) </code></pre> <p>input:</p> <pre><code>gogog ooooo godog ooooo gogog dog </code></pre> <p>The output will be <code>8</code> (horizontal, vertical, and diagonal form of <code>dog</code>).</p> <p>How to make it more <strong>readable</strong> and <strong>efficient</strong>?</p> <hr> <p><strong>The functions:</strong></p> <pre><code>def nword(string, word): normal = string listed = list(normal) listed.reverse() reverse = ''.join(listed) n = len(word); count = 0; idx = 0; start = 0; while idx &gt;= 0: idx = normal.find(word, start) if idx &gt;= 0: count+=1 start=idx+1 idx = 0; start = 0; while idx &gt;= 0: idx = reverse.find(word, start) if idx &gt;= 0: count+=1 start=idx+1 return count def fdiags(grid): n = len(grid[0]) m = len(grid) diags = [] Ll = [(1, n-1)] + [(0, i+1) for i in range(n-1)] Lr = [(1, 0)] + [(0, i) for i in range(n-1)] for l,r in zip(Ll, Lr): diags.append(''.join([ grid[l[0]+j][l[1]-k] for j, k in zip(range(m-l[0]), range(l[1]+1)) ])) diags.append(''.join([ grid[r[0]+j][r[1]+k] for j, k in zip(range(m-r[0]), range(n-r[1])) ])) return diags def wsearch(grid, word): n = len(grid[0]) m = len(grid) if n == 1: from_cols = sum([nword(''.join(i), word) for i in zip(*grid)]) return from_cols if m == 1: from_rows = sum([nword(''.join(i), word) for i in grid]) return from_rows from_diags = sum([nword(i, word) for i in fdiags(grid)]) from_cols = sum([nword(''.join(i), word) for i in zip(*grid)]) from_rows = sum([nword(''.join(i), word) for i in grid]) return from_diags+from_cols+from_rows </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-26T17:02:34.853", "Id": "204420", "Score": "3", "Tags": [ "python", "performance", "algorithm" ], "Title": "Word search algorithm" }
204420
<p>I'm currently coding a game of Pentominoes and I would like to hear suggestions on how to improve my code and make it more pythonic.</p> <h1>Rules and goal of the game</h1> <p>There is an 8x8 grid and you have 12 pentominos. The goal of the game is to lay all the pentominos on the grid without any overlapping, nor any pentomino partially being out of the grid.</p> <p>A pentomino is a geometric shape made up of 5 squares. 12 such shapes are possible (hence the goal). You are allowed to rotate a pentomino a quarter turn clockwise or counter-clockwise as many times as you want. You are also allowed to mirror a pentomino both vertically and horizontally (also as many times as desired).</p> <p>Each pentomino must be laid once and only once on the grid.</p> <h1>Actual code</h1> <p>Here's the conceptual part that can be (tediously) played in a python REPL; the visual part has not been taken care of yet:</p> <pre><code>GRID_DIM = 8 class Grid: """ The Grid is the place where all the pentominos have to be placed.. in order to win the game. This is an 8x8 grid. attributes: '_map' is a dict of {coords: case} with 'case' being what's sitting at said 'coords' '_game_over' is boolean that's False all game long and becomes True when.. all the pentominos have been put down on the grid '_laid_pentos' is a list containing all the letters symbolizing pentominos.. that are on the grid """ def __init__(self): self._game_over = False self._laid_pentos = [] self._map = dict() # '_map' initialisation for y in range(GRID_DIM): for x in range(GRID_DIM): self._map[(x, y)] = '.' # unoccupied case will be '.' # drops 'pento' at given coordinates def drop_pento_at(self, pento, x_drop, y_drop): letter = pento.letter if letter not in self._laid_pentos: self._laid_pentos.append(letter) try: for x in range(pento.width): for y in range(pento.height): # empty cases gets replaced if self._map[(x_drop + x, y_drop + y)] == '.': self._map[(x_drop + x, y_drop + y)] = pento[y][x] # if case is occupied and pento's corresponding case.. # is not '.' then, droping this pentomino here .. # would make two pentominos overlap elif pento[y][x] != '.': raise ValueError('pentomino {} cannot be dropped at\ coordinates ({},{})'.format(pento.letter, x_drop, y_drop)) # canceling changes except (ValueError, KeyError): self._laid_pentos.remove(letter) for coords in self._map: if self._map[coords] == letter: self._map[coords] = '.' # checking how many pentominos have already been laid if len(self._laid_pentos) == PENTO_COUNT: self._game_over = True print('You win, congrats old chap') # returns pentomino sitting at given coordinates def grab_pento_at(self, x_grab, y_grab): # determining what pentomino needs to be removed letter = self._map[(x_grab, y_grab)] if letter != '.': # removing 'letter' from '_laid_pentos' self._laid_pentos.remove(letter) # determining the area containing pentomino at '(x_grab, y_grab)' x_coords = [coords[0] for coords in self._map if self._map[coords] == letter] y_coords = [coords[1] for coords in self._map if self._map[coords] == letter] x_min, x_max = min(x_coords), max(x_coords) y_min, y_max = min(y_coords), max(y_coords) # constructing a pentomino's surface surface_pento = [] for y in range(y_min, y_max+1): new_row = [] for x in range(x_min, x_max+1): if self._map[(x, y)] == letter: self._map[(x, y)] = '.' new_row.append(letter) else: new_row.append('.') surface_pento.append(tuple(new_row)) return Pentomino(surface=surface_pento) # returns None if grab is done on empty case else: return None # for console representation def __str__(self): representation = str() for y in range(GRID_DIM): for x in range(GRID_DIM): representation += self._map[(x, y)] representation += '\n' return representation # All the Pentominos PENTO_COUNT = 12 PENTO_Y = [('.', '.', 'Y', '.'), ('Y', 'Y', 'Y', 'Y')] PENTO_T = [('T', '.', '.'), ('T', 'T', 'T'), ('T', '.', '.')] PENTO_V = [('V', 'V', 'V'), ('V', '.', '.'), ('V', '.', '.')] PENTO_N = [('N', 'N', 'N', '.'), ('.', '.', 'N', 'N')] PENTO_W = [('W', 'W', '.'), ('.', 'W', 'W'), ('.', '.', 'W')] PENTO_I = [('I', 'I', 'I', 'I', 'I')] PENTO_X = [('.', 'X', '.'), ('X', 'X', 'X'), ('.', 'X', '.')] PENTO_Z = [('Z', '.', '.'), ('Z', 'Z', 'Z'), ('.', '.', 'Z')] PENTO_U = [('U', 'U', 'U'), ('U', '.', 'U')] PENTO_P = [('P', 'P', 'P'), ('P', 'P', '.')] PENTO_L = [('L', 'L', 'L', 'L'), ('L', '.', '.', '.')] PENTO_F = [('.', 'F', 'F'), ('F', 'F', '.'), ('.', 'F', '.')] PENTO_DICT = {'Y': PENTO_Y, 'T': PENTO_T, 'V': PENTO_V, 'N': PENTO_N, 'W': PENTO_W, 'I': PENTO_I, 'X': PENTO_X, 'Z': PENTO_Z, 'U': PENTO_U, 'P': PENTO_P, 'L': PENTO_L, 'F': PENTO_F} class Pentomino: """ A Pentomino is a figure taking up 5 squares. There are twelve pentominos in the game. attributes: '_letter' is a single char informing the shape of the pentomino '_surface' is a list of tuples representing the pentomino in space """ def __init__(self, **kwargs): """ Initialising is done with keyword: either a 'letter' or a 'surface' is given. If a 'letter' is given the pentomino will be have a predefined '_surface' attribute, from 'PENTA_DICT' Otherwise a 'surface' must be given, that will be the '_surface' attribute. This way is not meant to be used by anything else than Grid's method 'grab_penta_at' """ for key, item in kwargs.items(): # initialising pentaminoe with basic surface from 'PENTA_DICT' if key == 'letter': self._letter = item.upper() try: self._surface = PENTO_DICT[self._letter] except KeyError: raise ValueError('Pentomino {} does not exist'.format(item)) break # initialising pentomino with given 'surface' elif key == 'surface': self._surface = item for a_char in self._surface[0]: if a_char != '.': self._letter = a_char break break @property def letter(self): return self._letter @property def width(self): return len(self._surface[0]) @property def height(self): return len(self._surface) # rotates the pentomino clockwise def right_rot(self): temp_figure = reversed(self._surface) self._surface = list(zip(*temp_figure)) # rotates the pentomino counter-clockwise def left_rot(self): temp_figure = [reversed(a_line) for a_line in self._surface] self._surface = list(zip(*temp_figure)) # mirrors the pentomino along the vertical axis def x_mirror(self): self._surface = [tuple(reversed(a_line)) for a_line in self._surface] # mirrors the pentomino along the horizontal axis def y_mirror(self): self._surface = list(reversed(self._surface)) # returns items from 'surface' def __getitem__(self, position): return self._surface[position] # for console representation def __str__(self): representation = str() for y in range(self.height): for x in range(self.width): representation += self._surface[y][x] representation += '\n' return representation </code></pre> <h1>How to play</h1> <p>copy-paste the whole thing in your favourite text editor and save as <code>pentos.py</code>. Launch your python3 from the directory it's in and type:</p> <pre><code>from pentos import * grd = Grid() </code></pre> <p>Then you instantiate the Pentomino class with:</p> <pre><code># a_letter must be 'f', 'i', 'l', 'n', 'p', 't', 'u', 'v', 'w', 'x', 'y' or 'z' p = Pentomino(letter=a_letter) </code></pre> <p>From there:</p> <ul> <li>rotation is done with <code>p.right_rot()</code> and <code>p.left_rot()</code> </li> <li>you can mirror <code>p</code> with <code>p.x_mirror()</code> and <code>p.y_mirror()</code></li> <li>you can have a look at your pentomino with <code>print(p)</code> </li> <li>to lay your pentomino on the grid type <code>grd.drop_pento_at(p, x, y)</code> and pentomino will be laid in such a way that top left corner of <code>p</code> (actually top left corner of what's displayed when you call <code>print(p)</code>) will be at coordinates <code>(x, y)</code>. </li> <li>to withdraw a pentomino from the grid, grab it with <code>p2 = grd.grab_pento_at(x, y)</code>, <code>(x, y)</code> being any coordinates that pentomino occupies. </li> </ul> <p>Lastly, coordinates are like this: <code>(0, 0)</code> is top left corner of <code>grd</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T00:11:43.527", "Id": "426230", "Score": "0", "body": "I think you should ask the user for a move inside the code, rather then having to do it after you run the program." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-26T18:43:09.630", "Id": "204422", "Score": "4", "Tags": [ "python", "python-3.x", "game" ], "Title": "Pentominoes in Python" }
204422
<p>Trying to group elements in a list by the their last element. I think this is a good problem to use groupby() from itertools. Here is my solution:</p> <pre><code>from itertools import groupby def match_ends(list1): """Returns a dictionary of groups of elements whose end elements match Returns empty dic if given list was empty Ex: list1 = ["abc", "dbc","aba","baa"] matched_ends(list1) = { 'c' : ['abc', 'dbc'], 'a' : ['aba', 'baa'] } """ matched_ends = {} list1 = sorted(list1, key = lambda x: x[-1]) for key, group in groupby(list1, lambda x: x[-1]): matched_ends[key] = list(group) return matched_ends </code></pre> <p>Was this a good approach? Am I missing any key points, or any errors I did not forsee that may yield garbage values instead of the program throwing an Error? Is there a quicker way to group elements based on certain criteria that I have yet to see?</p>
[]
[ { "body": "<h1>docstring</h1>\n\n<p>Your original method is adequately docmented, but you can format your docstring also according to a general style. <a href=\"https://stackoverflow.com/a/24385103/1562285\">This SO answer</a> covers some of the templates.</p>\n\n<h1>doctest</h1>\n\n<p>If you format your exampl...
{ "AcceptedAnswerId": "204444", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-26T21:03:32.767", "Id": "204428", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Grouping a list by their last element" }
204428
<p>I've implemented a simple program to print out 4 right triangles oriented in different ways to learn Haskell. I'm sure there are more efficient ways of doing what I have done, and I just want some feedback.</p> <p>All feedback related to the efficiency or quality of my code is welcome.</p> <h2>The four different triangle orientations are listed below</h2> <p>A <strong>Top Left Triangle</strong> of size 4 would look like:</p> <pre><code>**** *** ** * </code></pre> <p>A <strong>Bottom Left Triangle</strong> of size 4 would look like:</p> <pre><code>* ** *** **** </code></pre> <p>A <strong>Top Right Triangle</strong> of size 4 would look like:</p> <pre><code>**** *** ** * </code></pre> <p>A <strong>Bottom Right Triangle</strong> of size 4 would look like:</p> <pre><code> * ** *** **** </code></pre> <p>Here is my implemented solution to the problem:</p> <pre><code>module Main (main) where import Prelude -- MARK: Pure section -- makeTopLeftTriangle :: Char -&gt; Int -&gt; [String] makeTopLeftTriangle c n | n &lt; 1 = [] | otherwise = makeTriangleRow c n : makeTopLeftTriangle c (n-1) where makeTriangleRow :: Char -&gt; Int -&gt; String makeTriangleRow c n | n &lt; 1 = [] | otherwise = c : makeTriangleRow c (n-1) makeBottomLeftTriangle :: Char -&gt; Int -&gt; [String] makeBottomLeftTriangle c n = makeBottomLeftTriangleHelper c 1 n where makeBottomLeftTriangleHelper :: Char -&gt; Int -&gt; Int -&gt; [String] makeBottomLeftTriangleHelper c x n | x &gt; n = [] | otherwise = makeTriangleRow c x : makeBottomLeftTriangleHelper c (x+1) n where makeTriangleRow :: Char -&gt; Int -&gt; String makeTriangleRow c x | x &lt;= 0 = [] | otherwise = c : makeTriangleRow c (x-1) makeTopRightTriangle :: Char -&gt; Int -&gt; [String] makeTopRightTriangle c n = [(replicate n c)] ++ zipWith (++) (makeBottomLeftTriangle ' ' (n-1)) (makeTopLeftTriangle c (n-1)) makeBottomRightTriangle :: Char -&gt; Int -&gt; [String] makeBottomRightTriangle c n = zipWith (++) (makeTopLeftTriangle ' ' (n-1)) (makeBottomLeftTriangle c (n-1)) ++ [(replicate n c)] makeTriangle :: Char -&gt; Int -&gt; Int -&gt; [String] makeTriangle c triangleType = case triangleType of 1 -&gt; makeTopLeftTriangle c 2 -&gt; makeBottomLeftTriangle c 3 -&gt; makeTopRightTriangle c 4 -&gt; makeBottomRightTriangle c -- MARK: Non-pure section -- printTriangle :: [String] -&gt; IO () printTriangle [] = return () printTriangle (x:xs) = do putStrLn x printTriangle xs getTriangleType :: IO String getTriangleType = do putStrLn "What type of triangle do you want to print? (1, 2, 3, or 4)" putStrLn "1) Top Left" putStrLn "2) Bottom Left" putStrLn "3) Top Right" putStrLn "4) Bottom Right" getLine main :: IO () main = do i_triangleType &lt;- getTriangleType i_n &lt;- getLine let triangleType = read i_triangleType :: Int let n = read i_n :: Int printTriangle $ makeTriangle '*' triangleType n </code></pre>
[]
[ { "body": "<p>The recursion you used is very cumbersome, and should be avoided in favour of more expressive solutions in Haskell. You figured out how to write <code>replicate n c</code> — why didn't you just run with that? Add some list comprehensions, and you're done!</p>\n\n<p>Instead of using recursion in ...
{ "AcceptedAnswerId": "204441", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-26T21:25:10.883", "Id": "204429", "Score": "3", "Tags": [ "haskell", "ascii-art" ], "Title": "Printing right triangles recursively in Haskell" }
204429
<p>After seeing <a href="https://www.youtube.com/watch?v=AaGK-fj-BAM" rel="nofollow noreferrer">Snake coded in 10 minutes</a>, I decided to try a similar challenge, albeit easier. The following is Tic Tac Toe that I coded in 10 minutes. Given the short time frame, I'm sure there are style and convention errors abound, and would appreciate any suggestions :) </p> <p>I will also specifically ask about one thing - checking if there is a winner(done in the only ActionPerformed method). It feels long and convoluted, but it was the best I could think of at the time. Looking back, I still can't really think of any ways to write it better, actually... </p> <pre><code>import javax.swing.*; import java.awt.event.*; import java.awt.*; public class TicTacToe { private JFrame main; private TicButton[][] buttons; private JPanel[] rows; private boolean p1turn = true; private final Color bg1 = new Color(255,0,0); private final Color bg2 = new Color(0,255,0); public static void main(String[] args) { new TicTacToe().go(); } public void go() { main = new JFrame("Tic Tac Toe!"); buttons = new TicButton[3][3]; rows = new JPanel[3]; int r = 0; main.getContentPane().setLayout(new BoxLayout(main.getContentPane(),BoxLayout.Y_AXIS)); for (int i = 0; i &lt; 3; i++) { rows[r] = new JPanel(); for (int j = 0; j &lt; 3; j++) { buttons[i][j] = new TicButton(); rows[r].add(buttons[i][j]); } main.getContentPane().add(rows[r]); r++; } main.pack(); main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); main.setVisible(true); } private class TicButton extends JButton{ int value; private boolean clicked; public TicButton() { super("-"); this.value = -1; clicked = false; setFocusable(false); this.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if (!clicked) { clicked = true; setText(p1turn ? "X" : "O"); value = p1turn ? 1 : 2; setBackground(p1turn ? bg1 : bg2); p1turn = !p1turn; setEnabled(false); } boolean winner = false; String win = ""; for (TicButton[] tt : buttons) { if (tt[0].value == tt[1].value &amp;&amp; tt[0].value == tt[2].value &amp;&amp; tt[0].value != -1) { winner = true; win = tt[0].value == 1 ? "X" : "O"; break; } } for (int j = 0; j &lt; 3; j++) { if (buttons[0][j].value == buttons[1][j].value &amp;&amp; buttons[0][j].value == buttons[2][j].value &amp;&amp; buttons[0][j].value != -1) { winner = true; win = buttons[0][j].value == 1 ? "X" : "O"; break; } } if (buttons[0][0].value == buttons[1][1].value &amp;&amp; buttons[0][0].value == buttons[2][2].value &amp;&amp; buttons[0][0].value != -1) { winner = true; win = buttons[0][0].value == 1 ? "X" : "O"; } if (buttons[0][2].value == buttons[1][1].value &amp;&amp; buttons[0][2].value == buttons[2][0].value &amp;&amp; buttons[0][2].value != -1) { winner = true; win = buttons[0][2].value == 1 ? "X" : "O"; } if (winner) { JOptionPane.showMessageDialog(main, win + " wins!"); main.setVisible(false); System.exit(0); } } }); } } } </code></pre>
[]
[ { "body": "<p>When it is X’s turn, and they make a move, only player X can win. Similarly, only Y can win on Y’s turn. So why all these tests?</p>\n\n<pre><code>win = tt[0].value == 1 ? \"X\" : \"O\";\n</code></pre>\n\n<p>If there is a winner, just test <code>p1turn</code> in the <code>if (winner) {</code> co...
{ "AcceptedAnswerId": "204439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-26T22:39:56.417", "Id": "204432", "Score": "0", "Tags": [ "java", "tic-tac-toe", "swing" ], "Title": "10 minute Tic Tac Toe" }
204432
<p>I tried to solve the SPOJ prime number problem below. The code produced correct results, but Time limit exceeded and also memory need around 970M which is not efficient(?)</p> <p>How can I optimize this code under a time constraint of around few seconds?</p> <blockquote> <h2>Problem</h2> <p>Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!</p> <h2>Input</h2> <p>The input begins with the number t of test cases in a single line (t&lt;=10). In each of the next t lines there are two numbers m and n (1 &lt;= m &lt;= n &lt;= 1000000000, n-m&lt;=100000) separated by a space.</p> <h2>Output</h2> <p>For every test case print all prime numbers p such that m &lt;= p &lt;= n, one number per line, test cases separated by an empty line.</p> </blockquote> <pre><code>#include&lt;string.h&gt; #include&lt;stdlib.h&gt; #include&lt;stdio.h&gt; #include &lt;cmath&gt; #include &lt;vector&gt; #include&lt;iostream&gt; using namespace std; void simplesieve(int limit, vector&lt;int&gt;&amp;prime); void segmentedsieve() { int T, M, K; cin &gt;&gt; T; for (int t = 0; t &lt; T; t++) { cin &gt;&gt; M &gt;&gt; K; const int limit = floor(sqrt(K)) + 1; vector&lt;int&gt; prime; simplesieve(K, prime); bool *mark = new bool[K - M]; memset(mark, true, sizeof(bool)*(K-M)); vector&lt;int&gt;::iterator it; for (it = prime.begin(); *it&lt;limit; it++) { int lolim = floor(M / (*it))*(*it); if (lolim &lt; M) lolim = lolim + (*it); for (int j = lolim; j &lt; K; j += (*it)) { if(j!=*it) mark[j - M] = false; } } for (int i = M; i &lt; K; i++) { if (mark[i - M] == true) cout &lt;&lt; i &lt;&lt; "\n"; } delete[] mark; } } void simplesieve( int limit, vector&lt;int&gt;&amp;prime) { bool *mark=new bool[limit + 1]; memset(mark, true, sizeof(bool)*(limit+1)); for (int p = 2; p*p &lt; limit; p++) { if (mark[p] == true) { for (int i = p * 2; i &lt; limit; i += p) mark[i] = false; } } for (int p = 2; p &lt; limit; p++) { if (mark[p] == true) { prime.push_back(p); } } } int main() { int n = 100; segmentedsieve(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T11:39:17.230", "Id": "394261", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y...
[ { "body": "<ol>\n<li><p>You are computing your prime sieve multiple times, when you only need to compute it once. You are told you will have at most 10 test cases. You could easily store those in an array, compute the maximum upper limit, and run the sieve once. Then loop through the stored test cases, and g...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-26T22:53:52.593", "Id": "204433", "Score": "7", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded", "sieve-of-eratosthenes", "memory-optimization" ], "Title": "Prime number segmented sieve" }
204433
<p>I'm starting to learn Java (started with C++), and still getting to get used to the syntax and whatnot. For practice, I made a doubly-linked list program. Is there any way this could be improved at all, or is this okay code?</p> <pre><code>// Doubly Linked-List Practice package doublylinkedlist; public class DoublyLinkedList { node head, tail; class node // Creates node class { double num; node next; node prev; public node() { num = 0; next = null; prev = null; } public node (double p) { num = p; next = null; prev = null; } } public void append(double x) // Appends data to list { node p = new node(x); if (head == null) // Creates head node if empty list { head = p; tail = p; return; } p.prev = tail; // Skips to end of list and appends tail.next = p; tail = p; return; } public void showF() // Displays list forward { for (node q = head; q != null; q = q.next) System.out.print(q.num + " "); System.out.println(); } public void showR() // Displays list in reverse { for (node q = tail; q != null; q = q.prev) System.out.print(q.num + " "); System.out.println(); } public double findAvg() { double mean = 0, total = 0; int i = 0; for (node p = head; p != null; p=p.next) { total += p.num; ++i; } return(mean = total/i); } public void delete(double x) // Deletes a single node { node p = new node(x); node temp = head; node pre, nex; if (head.num == p.num) // If head node needs to be removed { head = head.next; return; } while (temp != null) // If a node in between is to be deleted { if (p.num == temp.num) { System.out.println("Node found! Deleting " + x + "..."); temp.prev.next = temp.next; temp.next.prev = temp.prev; return; } else temp = temp.next; } if (tail.num == p.num) // If tail is to be deleted { tail = tail.prev; return; } } public void deleteMore(double x) // Removes all nodes of certain key { node temp = head; if(head == null) // If list is empty { System.out.println("Empty list!"); return; } while (head != null &amp;&amp; head.num &gt; x) // If head node needs to be deleted { head = head.next; head.prev = null; temp = head; } while(temp !=null) // Every remaining occurrence to be removed { if(temp.num &gt; x) { if (temp.num == tail.num) // If tail node needs to be removed { tail = tail.prev; tail.next = null; temp = tail; } else { temp.prev.next = temp.next; temp.next.prev = temp.prev; } } temp = temp.next; } } public static void main(String[] args) { DoublyLinkedList myList = new DoublyLinkedList(); double[] arr = {600.0, 100.0, 10.0, 15.0, 20.0, 200.0, 30.0, 40.0, 300.0, 350.0, 400.0, 500.0}; for (int i = 0; i &lt; arr.length; ++i) myList.append(arr[i]); System.out.println("Here's your list foreward..."); myList.showF(); System.out.println("Average = " + myList.findAvg()); System.out.println("Removing all excess averages..."); myList.deleteMore(myList.findAvg()); System.out.println("Here's your revised list"); myList.showF(); System.out.println("And here's your list in reverse"); myList.showR(); System.out.println("Removing 30, just because I can"); myList.delete(30.0); myList.showF(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T05:22:57.603", "Id": "394207", "Score": "1", "body": "You have bugs in `delete(x)`. If you delete the `head` node, the next node’s `prev` still points to it. If there was only 1 node, `tail` will still point to it. If you delete ...
[ { "body": "<p>Comments in mostly top-down order.</p>\n\n<hr>\n\n<pre><code>class node // Creates node class\n</code></pre>\n\n<p>Classes in Java should begin with an uppercase letter. Ie) <code>class Node</code>.</p>\n\n<p>As it stands, this class can only be used inside <code>DoublyLinkedList</code>, so it sh...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T02:10:48.320", "Id": "204435", "Score": "1", "Tags": [ "java", "linked-list" ], "Title": "Doubly-linked list program with delete functions" }
204435
<p>This is not my solution but that of an existing application I am enhancing.</p> <p>Basically what they are doing is annotating a <code>Form.java</code> with a custom validator that does all trivial <strong>AND</strong> business logic validation</p> <pre><code>@MyCreateFormValidator // which contains business logic validation // validator uses Services / Repositories that actually queries the DB for checking public class MyCreateForm { @NotEmpty private String name; // and more trivial validations } </code></pre> <p><strong>Question</strong>: I myself don't like the idea of this and would want to move the business logic validation on the Service layer instead of doing <code>@Valid</code> on the Controller level but maybe I am missing something.</p> <p>Is my solution of moving to Service layer better than this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T09:55:10.370", "Id": "394246", "Score": "1", "body": "The existing solution is nearer to the frontend and would it not be nice to have the name field on the screen signalling \"required\" and red outlined when empty? Though validati...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T09:26:52.693", "Id": "204452", "Score": "1", "Tags": [ "java", "validation", "spring", "spring-mvc" ], "Title": "Business logic validation as custom Bean Validation annotations?" }
204452
<p>I have a dict that may be 'infinitely' nested and contain several pandas DataFrame's (all the DataFrame's have the same amount of rows).</p> <p>I want to create a new dict for each row in the DataFrame's, with the row being transformed to a dict (the key's are the column names) and the rest of the dictionary staying the same.</p> <p>Note: I am not making a cartesian product between the rows of the different DataFrame's.</p> <p>I have an example in my SO <a href="https://stackoverflow.com/questions/52513662/turn-a-dict-that-may-contain-a-pandas-dataframe-to-several-dicts">question</a></p> <p>here is what i came up with:</p> <pre><code>import pandas as pd from copy import deepcopy from functools import partial def map_keys_by_type(d, typ, path=None): for k,v in d.items(): p = path.copy() if path else [] p.append(k) if isinstance(v, typ): yield p if isinstance(v, dict): yield from map_keys_by_type(v, typ, p) def nested_get(nested_key, input_dict): internal_dict_value = input_dict for k in nested_key: internal_dict_value = internal_dict_value.get(k, None) if internal_dict_value is None: return None return internal_dict_value def nested_set(dic, keys, value): for key in keys[:-1]: dic = dic.setdefault(key, {}) dic[keys[-1]] = value def dup_dicts(keys, iter_of_values, init_dict): for values in iter_of_values: init_dict = deepcopy(init_dict) [nested_set(init_dict, key, value) for key, value in zip(keys, values)] yield init_dict if __name__ == '__main__': keys = list(map_keys_by_type(d, pd.DataFrame)) dfs = map(partial(nested_get, input_dict=d), keys) dfs_as_dicts = map(partial(pd.DataFrame.to_dict, orient='records'), dfs) iter_of_dicts = dup_dicts(keys,zip(*dfs_as_dicts), d) </code></pre> <p>any improvements?</p>
[]
[ { "body": "<p>I'm assuming that the code works as intended.</p>\n\n<p>Firstly, let me tell you that your code looks very pythonic - this is a huge plus.</p>\n\n<h1>My comments:</h1>\n\n<p><strong>Introduction</strong></p>\n\n<p>You state that</p>\n\n<blockquote>\n <p>I have a dict that may be 'infinitely' nest...
{ "AcceptedAnswerId": "204459", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T09:42:36.630", "Id": "204453", "Score": "3", "Tags": [ "python", "hash-map", "pandas" ], "Title": "turn a dict that may contain a pandas dataframe to several dicts" }
204453
<p>I am trying to come up with a good File System Design using C++ / OOP. This is being done to gain an understanding of System Design and Design Patterns.</p> <p>I have some basic functionality, like reading and writing files, adding and deleting files and folders, calculating the size of files and folders. The design pattern I am trying to use is <a href="https://www.geeksforgeeks.org/composite-design-pattern/" rel="nofollow noreferrer">Composite Design pattern</a>.</p> <p>My design uses a base class called <code>BaseComponent</code> which contains facilities common to both files and folders. The class <code>Folder</code> deals with adding and deleting of files and folders while class <code>File</code> deals with reading and writing of files. Both <code>File</code> and <code>Folder</code> are derived from <code>BaseComponent</code>.</p> <p>Here is the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;set&gt; class BaseComponent { std::string name_v; BaseComponent* parent_v; bool is_folder; public: BaseComponent(std::string name, BaseComponent* parent = nullptr, bool f = true) : name_v{name}, parent_v{parent}, is_folder{f} { } virtual ~BaseComponent() { } void change_name(std::string&amp; name) { name_v = name; } std::string name() const { return name_v; } BaseComponent* parent() const { return parent_v; } void del() { if(parent_v == nullptr) { return; } parent_v -&gt; delete_component(this); } virtual int size() const { return 0; } virtual void add_component(BaseComponent*) { } virtual void delete_component(BaseComponent*) { } }; class Folder : public BaseComponent { std::set&lt;BaseComponent*&gt; children; public: Folder(std::string name, Folder* parent = nullptr, bool is_folder = true) : BaseComponent{name, parent, is_folder} { } ~Folder() { } int size() const { int size_v = 0; for(auto child : children) { size_v += child -&gt; size(); } return size_v; } int num_ff() { return children.size(); } void add_component(BaseComponent* b) { children.insert(b); } void delete_component(BaseComponent* b) { children.erase(b); } }; class File : public BaseComponent { std::string contents_v; public: File(std::string contents, std::string name, Folder* parent, bool is_folder = false) : BaseComponent{name, parent, is_folder}, contents_v{contents} { } ~File() { } int size() const { return sizeof(this); } void write(std::string content) { contents_v = content; } std::string read() const { return contents_v; } }; /*class FileSystem { };*/ int main() { Folder root{"/"}; Folder home{"home", &amp;root}; root.add_component(&amp;home); Folder lib{"lib", &amp;root}; root.add_component(&amp;lib); Folder dev{"dev", &amp;root}; root.add_component(&amp;dev); std::cout &lt;&lt; "No. of components in root: " &lt;&lt; root.num_ff() &lt;&lt; "\n"; std::cout &lt;&lt; "No. of components in home: " &lt;&lt; home.num_ff() &lt;&lt; "\n"; File test{"x = 0, y = 0", "Configuration.txt", &amp;root}; root.add_component(&amp;test); Folder ws{"ws", &amp;home}; home.add_component(&amp;ws); File fs{"fs file", "fs.cpp", &amp;ws}; ws.add_component(&amp;fs); File git{"user: dummy", "git_config", &amp;home}; home.add_component(&amp;git); std::cout &lt;&lt; "Contents of git: " &lt;&lt; git.read() &lt;&lt; "\n"; git.write("user: new\n email:new@new.com"); std::cout &lt;&lt; "Contents of git: " &lt;&lt; git.read() &lt;&lt; "\n"; std::cout &lt;&lt; "No. of components in root: " &lt;&lt; root.num_ff() &lt;&lt; "\n"; std::cout &lt;&lt; "No. of components in home: " &lt;&lt; home.num_ff() &lt;&lt; "\n"; std::cout &lt;&lt; "No. of components in ws: " &lt;&lt; ws.num_ff() &lt;&lt; "\n"; dev.del(); std::cout &lt;&lt; "No. of components in root: " &lt;&lt; root.num_ff() &lt;&lt; "\n"; std::cout &lt;&lt; "Size of git: " &lt;&lt; git.size() &lt;&lt; "\n"; std::cout &lt;&lt; "Size of root: " &lt;&lt; root.size() &lt;&lt; "\n"; return 0; } </code></pre> <ol> <li><p>The <code>add_component</code> is being called from <code>main</code>. How can I change that? I don't mind calling it inside a new class called <code>FileSystem</code> by creating functions such as <code>mkdir</code> or <code>mkfile</code> to handle folder and file creation. But I am not able to come up with a good design. </p></li> <li><p>If <code>FileSystem</code> is being implemented, I would like to avoid having to take the pointer to parent inside the <code>main</code>, while creating files and folders. This is again something that is stopping me from coming up with a better design. </p></li> <li><p>How to improve the functionalities implemented? Are there any significant issues in this part?</p></li> <li><p>Is a better design possible without changing classes and their interface?</p></li> <li><p>Kindly provide an overall review.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T10:48:01.167", "Id": "394249", "Score": "1", "body": "Have you looked at how (proposed) `std::filesystem` represents these, or is this a completely independent approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationD...
[ { "body": "<p>Something that jumps out immediately is the <code>is_folder</code> member. It's a bad sign if a base class needs to know what subclass it is. Even more concerning, the subclass constructors allow one to create a <code>File</code> with <code>is_folder</code> set, or a <code>Folder</code> with <co...
{ "AcceptedAnswerId": "204462", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T09:57:42.713", "Id": "204455", "Score": "2", "Tags": [ "c++", "object-oriented", "design-patterns", "file-system" ], "Title": "C++ - Object Oriented File System Design using Composite Design Pattern" }
204455
<p>I need to make the following function time constant - I have already removed if statements and have written it down to one line in the loop.</p> <pre><code> /******************/ uint8_t dseed[54]; // only 0 and 1 like {0,1,0,1,1,1,0,0,1,0,...} uint8_t fecb[256]; const unsigned char g[55] = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0,...}; /******************/ memset(fecb,0,54*sizeof(uint8_t)); for (int i = 255; i &gt;= 0; i--) { int feedback = dseed[i] ^ fecb[53]; for (int j = 53; j &gt; 0; j--){ fecb[j] = fecb[j - 1] ^ (feedback &amp;&amp; g[j]); } fecb[0] = g[0] &amp;&amp; feedback; } </code></pre> <p>The code in my eyes looks constant time but when I measure it, it is not. Cycles vary between 165k and 185k.</p> <p>The assembly code contains a conditional jump.</p> <pre><code> for (int i = PARAM_K - 1; i &gt;= 0; i--) { //PARAM_K = 256 0xC0000556: C5 04 3F 30 LEA a4,0xFF 0xC000055A: 7B 00 00 4C MOVH d4,0xC000 &gt; 0xC000059A: B0 F4 ADD.A a4,-0x1 &gt; 0xC000059E: FD 70 47 00 LOOP a7,0xC000062C &gt; 0xC0000622: B0 F4 ADD.A a4,-0x1 &gt; 0xC0000626: FD 70 03 00 LOOP a7,0xC000062C &gt; 0xC000062A: 3C BC J 0xC00005A2 &gt; 0xC000062C: 39 AF 37 00 LD.BU d15,[a10]0x37 &gt; 0xC0000630: 3C A1 J 0xC0000572 &gt; 0xC0000632: 00 A0 DEBUG &gt; 0xC0000634: 3C D0 J 0xC00005D4 feedback = dseed[i] ^ fecb[LENGTH - PARAM_K - 1]; //LENGTH = 310 0xC0000572: D9 AF 38 00 LEA a15,[a10]0x38 0xC0000576: 30 4F ADD.A a15,a4 0xC0000578: 08 05 LD.BU d5,[a15]0x0 0xC000057A: C5 0F 34 00 LEA a15,0x34 0xC000057E: C6 F5 XOR d5,d15 0xC0000580: DA 35 MOV d15,0x35 0xC0000582: DF 05 40 80 JNE d5,0x0,0xC0000602 &lt;----- JNE &gt; 0xC00005D4: 82 7F MOV d15,0x7 | &gt; 0xC00005D6: C5 0F 35 00 LEA a15,0x35 | | for (int j = LENGTH - PARAM_K - 1; j &gt; 0; j--) | fecb[j] = fecb[j - 1] ^ (feedback &amp;&amp; g[j]); | 0xC0000586: 92 F2 ADD d2,d15,-0x1 | 0xC0000588: 01 22 00 36 ADDSC.A a3,a2,d2,0x0 | 0xC000058C: 14 33 LD.BU d3,[a3] | 0xC000058E: 10 23 ADDSC.A a3,a2,d15,0x0 | 0xC0000590: 02 2F MOV d15,d2 | 0xC0000592: 34 33 ST.B [a3],d3 | 0xC0000594: FC F9 LOOP a15,0xC0000586 | &gt; 0xC0000602: 60 4E MOV.A a14,d4 &lt;---------| &gt; 0xC0000604: 92 F3 ADD d3,d15,-0x1 &gt; 0xC0000606: 10 E6 ADDSC.A a6,a14,d15,0x0 &gt; 0xC0000608: 01 23 00 56 ADDSC.A a5,a2,d3,0x0 &gt; 0xC000060C: 10 23 ADDSC.A a3,a2,d15,0x0 &gt; 0xC000060E: 0C 60 LD.BU d15,[a6]0x0 &gt; 0xC0000610: 14 52 LD.BU d2,[a5] &gt; 0xC0000612: 8B 0F 20 F2 NE d15,d15,0x0 &gt; 0xC0000616: C6 2F XOR d15,d2 &gt; 0xC0000618: 2C 30 ST.B [a3]0x0,d15 &gt; 0xC000061A: 02 3F MOV d15,d3 &gt; 0xC000061C: FC F3 LOOP a15,0xC0000602 fecb[0] = g[0] &amp;&amp; feedback; 0xC0000596: 8B 05 20 F2 NE d15,d5,0x0 &gt; 0xC000059C: 2C A2 ST.B [a10]0x2,d15 &gt; 0xC000061E: 8B 05 20 F2 NE d15,d5,0x0 &gt; 0xC0000624: 2C A2 ST.B [a10]0x2,d15 } </code></pre> <p>Is this conditional jump responsible for the varying #cycles? ´</p> <p>I already tried to compile this code snipped using <code>__attribute__((optimize("O0")))</code>, and I also tried <code>volatile int feedback</code>. Using the volatile keyword, this JNE disappears, but the code still isn't executed in constant time (because of stalls when writing/reading memory maybe?). Cycles vary between 215k and 235k using the volatile keyword.</p> <p>Can this code efficiently made constant time? Is there some conditional branch I am missing?</p> <p>Thank you for any help</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T10:49:10.723", "Id": "394250", "Score": "0", "body": "I'm not sure whether it will help, but have you tried unrolling the loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T10:59:44.207", "Id":...
[ { "body": "<p><a href=\"https://en.cppreference.com/w/cpp/language/operator_logical\" rel=\"nofollow noreferrer\">Operator &amp;&amp;</a> is <a href=\"https://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"nofollow noreferrer\">short-circuit</a> which means, that it can give the result based only on the...
{ "AcceptedAnswerId": "204458", "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T10:13:24.330", "Id": "204457", "Score": "0", "Tags": [ "c", "assembly", "gcc" ], "Title": "gcc constant time implemenation" }
204457
<p>In the Elm examples I have seen for form handling, they attach each input element with an update handler that sends out a very specific message to update the model according to the new input state.</p> <p>So you end up with a lot of message definition in your <code>Msg</code> union type.</p> <p>Alternatives I have seen for "dynamic" or complex forms use generic handlers that can work with <code>Dict</code> of data, keyed by form input id, at the expense of some type-safety.</p> <p>I was thinking I can have (at least for simple handlers that only update the model in straightforward ways and do not need to send Commands to the runtime engine) a middle-ground with a generic <code>SimpleModelUpdate</code> message that takes a mutator function as its payload to describe what it is actually supposed to do.</p> <p>Something like</p> <pre><code> type Msg = .... | SimpleModelUpdate (Model -&gt; Model) update model msg = ... case SimpleModelUpdate mutation -&gt; (mutation model, Cmd.none) Html.button [onClick = SimpleModelUpdate (\m -&gt; {m | counter = counter + 1})] [text "Increase"] </code></pre> <p>That seems to work. And I like it because I do not have to spread the code for trivial updates all over the place (I can reserve dedicated message types for the really "important" stuff).</p> <p>Is this bad design? Are there other issues that I am not seeing?</p>
[]
[ { "body": "<p>I think the general consensus is to avoid functions in <code>Msg</code> constructors when possible.</p>\n\n<p>The one certain thing that will break is the <code>Msg</code> history import/export of the Elm debugger, since functions cannot be serialized.</p>\n\n<p>Evan included this comment in his <...
{ "AcceptedAnswerId": "205135", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T13:52:04.887", "Id": "204460", "Score": "2", "Tags": [ "elm" ], "Title": "Generic message in Elm for simple model updates" }
204460
<p>I want to traverse a xml tree until I find the first element whose position matches the path. So if I'm looking for <code>Foo/Bar/FooBar</code> I want to get this:</p> <pre><code>&lt;Root&gt; &lt;Foo&gt; &lt;Bar&gt; &lt;FooBar /&gt; &lt;!-- This one --&gt; &lt;/Bar&gt; &lt;/Foo&gt; &lt;/Root&gt; </code></pre> <p>However there could be any number of <code>&lt;FooBar /&gt;'s</code> in my way and I only want the one at this path. I wrote 2 methods to get this:</p> <pre><code>private static XElement ElementByName(XElement parent, string name) { return parent.Elements().Where(element =&gt; element.Name.LocalName == name).First(); } private static XElement ElementAtPath(XElement root, string path) { XElement target = root; string[] pathArr = path.Split('/'); for (int i = 0; i &lt; pathArr.Length; i ++) { target = ElementByName(target, pathArr[i]); } return target; } </code></pre> <p>Is there a faster / more efficient way I could achieve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T14:59:39.777", "Id": "394289", "Score": "1", "body": "There is, look [here](https://stackoverflow.com/questions/3642829/how-to-use-xpath-with-xelement-or-linq) - you need to use `XPath` ;-)" }, { "ContentLicense": "CC BY-SA ...
[ { "body": "<p>What about:</p>\n\n<pre><code>private static XElement ElementByName(XElement parent, string name)\n{\n // Use FirstOrDefault() or another selector to find the relevant element\n return parent.Descendants(name).FirstOrDefault();\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>XDocument document ...
{ "AcceptedAnswerId": "204508", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T14:57:45.460", "Id": "204464", "Score": "3", "Tags": [ "c#", "xml" ], "Title": "Get a XElement at a given path" }
204464
<p>I've written a solution to the following leetcode problem:</p> <blockquote> <p>Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.</p> <p>Example 1: <code>Input: nums = [1,1,1], k = 2 Output: 2</code></p> <p>Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].</p> </blockquote> <p>Solution:</p> <pre><code>class Solution: def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ T = ['inf' for _ in range(len(nums))] count = 0 for i in range(len(nums)): for j in range(i,len(nums)): if j == i: T[i] = nums[i] if T[i] == k: count +=1 else: currSum = T[j-1] + nums[j] T[j] = currSum if currSum == k: count +=1 return count </code></pre> <p>The solution passes 58/80 test cases, but for some reason, the solution is returning a Time Limit Exceeded exception on an input array with hundreds of elements. I implemented a dynamic programming solution using a 1d array to memoize previous sums so the algorithm should be efficient. <strong><em>Is there any way to optimize this?</em></strong></p>
[]
[ { "body": "<p>Optimization for code:</p>\n\n<ol>\n<li>calculate <code>len(nums)</code> once outside <code>for</code> loops</li>\n<li>if you use Python2 - use <code>xrange</code> instead of <code>range</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDat...
{ "AcceptedAnswerId": "204484", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T15:20:22.943", "Id": "204466", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge", "dynamic-programming" ], "Title": "Subarray Sum Equals K" }
204466
<p>I have the following javascript function validateEmail(value). The goal of the function is to validate the users inputted email <em>as they are typing</em>. So if someone puts nfg@*gmail.com the email will be displayed with the * char crossed out. Anytime there is an invalid character the display will show it striked out. This must be updated on every key push. Here's a JSFiddle: <a href="https://jsfiddle.net/d4kgejym/1/" rel="nofollow noreferrer">https://jsfiddle.net/d4kgejym/1/</a></p> <p>This is one of my first code reviews so please comment below if anymore information is needed.</p> <p><strong>Assumptions about email addresses:</strong> (not true in real world)</p> <p>A valid email is defined as follows: <code>^[a-z0-9]*[@][a-z]*[.][a-z]{1,3}$</code></p> <pre><code>function validateEmail() { var value = $('#emailInput').val(); // TODO unsupported case: nfgallim$@ :( // case 5 where has @ and . with chars after . // nfgallimore@gmail.com if (value.includes('@') &amp;&amp; value.substr(value.indexOf('@')).length &gt; 1 &amp;&amp; value.includes('.') &amp;&amp; value.substr(value.indexOf('.')).length &gt; 1) { $('#emailDisplay').html(validateCase5Regex(value)); } // case 4 where has @ with chars after and . with no chars after . // nfgallimore@gmail. else if (value.includes('@') &amp;&amp; value.substr(value.indexOf('@')).length &gt; 1 &amp;&amp; value.includes('.') &amp;&amp; value[value.length - 1] === '.') { $('#emailDisplay').html(validateCase4Regex(value)); } // case 3 where has @ with chars after @ // nfgallimore@gmail else if (value.includes('@') &amp;&amp; value.substr(value.indexOf('@')).length &gt; 1) { $('#emailDisplay').html(validateCase3Regex(value)); } // case 2 where has only @ with no chars after @ // nfgallimore@ else if (value.includes('@') &amp;&amp; value[value.length - 1] === '@') { $('#emailDisplay').html(validateCase2Regex(value)); } // case 1 with just ^[a-z0-9]*$ // nfgallimore else { $('#emailDisplay').html(validateCase1Regex(value)); } } // nfgallimore@gmail.com function validateCase5Regex(value) { var domainTypeRegex = new RegExp('^[a-z]$'); var stringRegex = new RegExp('^[a-z0-9]*[@][a-z]*[.][a-z]{1,3}$'); var periodIndex = value.indexOf('.'); // first period var firstStr = value.slice(0, periodIndex + 1); var substr = value.substr(periodIndex + 1); return !value.match(stringRegex) ? validateCase4Regex(firstStr) + GetHtmlErrorWithMaxLength(substr, domainTypeRegex, 3) : value; } // nfgallimore@gmail. function validateCase4Regex(value) { var stringRegex = new RegExp('^[a-z0-9]*[@][a-z]*[.]$'); // nfgallimore@gmail var strWithoutPeriodSymbol = value.slice(0, value.length - 1); return !value.match(stringRegex) ? validateCase3Regex(strWithoutPeriodSymbol) + '.' : value; } // nfgallimore@gmail function validateCase3Regex(value) { var domainRegex = new RegExp('^[a-z]*$'); var stringRegex = new RegExp('^[a-z0-9]*[@][a-z]*$'); var atIndex = value.indexOf('@'); // split on first occurrence of @ var firstStr = value.slice(0, atIndex); // nfgallimore@ var domainStr = value.substr(atIndex + 1) // gmail // apply secondStrRegex to second str return !value.match(stringRegex) ? validateCase2Regex(firstStr) + GetHtmlError(domainStr, domainRegex) : value; } // nfgallimore@ function validateCase2Regex(value) { var regex = new RegExp('^[a-z0-9]*[@]$'); var strWithoutAtSymbol = value.slice(0, value.length); // nfgallimore return !value.match(regex) ? validateCase1Regex(strWithoutAtSymbol) + '@' : value; } // nfgallimore function validateCase1Regex(value) { var regex = new RegExp('^[a-z0-9]*$'); return !value.match(regex) ? GetHtmlError(value, regex) : value; } // Helper function that returns html. // Chars that fail the regex get striken out function GetHtmlError(value, regex) { var letters = ''; for (var i = 0, len = value.length; i &lt; len; i++) { if (value[i].match(regex)) { letters += value[i]; } else { letters += '&lt;span class="strike"&gt;' + value[i] + '&lt;/span&gt;'; } } return letters; } // Helper function that returns html. // Chars that fail the regex or exceed length get striken out function GetHtmlErrorWithMaxLength(value, regex, length) { var letters = ''; for (var i = 0, len = value.length; i &lt; len; i++) { if (value[i].match(regex) &amp;&amp; i &lt; length) { letters += value[i]; } else { letters += '&lt;span class="strike"&gt;' + value[i] + '&lt;/span&gt;'; } } return letters; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T20:46:39.593", "Id": "394340", "Score": "0", "body": "I added the function. I think that should be all of them. I was extracting it from the entire web app to make it is simple as possible." }, { "ContentLicense": "CC BY-SA ...
[ { "body": "<h2>Initial Comments</h2>\n<p><a href=\"https://codereview.stackexchange.com/users/130137/marc-rohloff\">@MarkRohloff</a>'s <a href=\"https://codereview.stackexchange.com/questions/204467/validate-email-as-user-is-typing-javascript#comment394357_204467\">comment</a> is good:</p>\n<blockquote>\n<p>My ...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T15:23:26.903", "Id": "204467", "Score": "2", "Tags": [ "javascript", "jquery", "regex", "validation", "ecmascript-6" ], "Title": "Validate Email as User is typing (JavaScript)" }
204467
<p>I'm writing an Exploratory Data Analysis using R Markdown. First of all, I need to check the "sanity" of the input data set. Among the other check I perform, I need to check if at least one between the variables <code>var_in</code> and <code>var_out</code> are present in the dataset. If at least one is present, the other one can be computed from the first one. Thus, I want to check which of them is missing, and store its name in a character vector. If <em>both</em> are missing, the analysis is impossible and I need to exit, preferably throwing a meaningful error.</p> <p>I cannot include the actual dataset on which the check is performed, because it's <span class="math-container">\$10^6\$</span> rows with confidential data, so I need to use fake data. The code, however, is as similar to the real code as possible.</p> <pre><code># fake data n &lt;- 10^6 input_df &lt;- data.frame(wind_speed = 10*abs(rnorm(n)), wind_direction = runif(n, 0, 2*pi), var_in = NA, var_out = 3) # nearly real code missing_variables &lt;- character(0) var_in_is_missing &lt;- all(is.na(input_df$var_in)) var_out_is_missing &lt;- all(is.na(input_df$var_out)) if (var_in_is_missing &amp; var_out_is_missing) { stop("both var_in and var_out are completely missing, so I cannot continue the EDA") } if (var_in_is_missing) { missing_variables &lt;- c("var_in", missing_variables) } if (var_out_is_missing) { missing_variables &lt;- c("var_out", missing_variables) } </code></pre> <p>Note that according to the principle of early return, I put the stopping test before the other two. The code runs, but it doesn't seem that readable to me:</p> <ol> <li>I test both <code>var_in_is_missing</code> and <code>var_out_is_missing</code> twice: this is definitely not going to impact notably the performance of my code, but it still feels useless</li> <li>is it really necessary to use three separate <code>if</code> statements? Isn't there a way to do it in R in a more...compact way, without sacrificing readability?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T02:20:27.083", "Id": "395012", "Score": "2", "body": "An additional minor comment, in this situation you should use `&&` rather than `&`, cleaner as you're not comparing vector, and this way RHS won't be tested if LHS is FALSE." ...
[ { "body": "<p>I would do something like this:</p>\n\n<pre><code>tt &lt;- function() {\n naI &lt;- sapply(input_df[, c('var_in', 'var_out')], function(x) all(is.na(x)))\n if (sum(naI) == 2) {\n stop(\"both var_in and var_out are completely missing, so I cannot continue the EDA\")\n } else {\n missing_va...
{ "AcceptedAnswerId": "204510", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T16:14:59.287", "Id": "204469", "Score": "1", "Tags": [ "r" ], "Title": "Checking the presence of certain variables in a dataframe" }
204469
<p>I'm looking to improve my coding skills. I am new to programming, and after weeks of research and trial and error - I have successfully wrote this basic program to find a music scale by inputting a Root note and Scale.</p> <p>Since I am pretty much teaching my self - I am looking for criticism to improve my syntax/programming. I compressed the code listed below and localized variables into a 46 line version of this program but really like the layout of the original, so please be brutally honest. Pros and Cons with explanations please?</p> <p>Note: I was purely being lazy by using <code>#define</code> and plan to replace all strings and vectors with their correct <code>std::<em>typename</em></code>.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;map&gt; #define astring std::string #define cvector std::vector astring rootnote = ""; astring scale = ""; void notation(); int root; cvector&lt;astring&gt; notes; cvector&lt;astring&gt; order; void scaler(); int main() { while (rootnote != "null") { std::cout &lt;&lt; "Please enter your root note and scale: " &lt;&lt; std::endl; std::cin &gt;&gt; rootnote &gt;&gt; scale; std::cout &lt;&lt; "\nroot scale: " &lt;&lt; rootnote &lt;&lt; " " &lt;&lt; scale &lt;&lt; std::endl; std::cout &lt;&lt; std::endl; notation(); scaler(); } return 0; } void notation() { notes.clear(); cvector&lt;astring&gt; chromatic = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" }; root = std::distance(chromatic.begin(), std::find(chromatic.begin(), chromatic.end(), rootnote)); for (int i = root; i &lt; chromatic.size(); i++) { notes.push_back(chromatic[i]); } for (int j = 0; j &lt; root; j++) { notes.push_back(chromatic[j]); } return; } void scaler() { order.clear(); std::map&lt;astring, cvector&lt;int&gt;&gt; scales; scales["Major"] = { 0, 2, 4, 5, 7, 9, 11 }; scales["Minor"] = { 0, 2, 3, 5, 7, 8, 10 }; scales["Melodic"] = { 0, 2, 3, 5, 7, 9, 11 }; scales["Harmonic"] = { 0, 2, 3, 5, 7, 8, 11 }; for (auto i : scales[scale]) order.push_back(notes[i]); for (int j = 0; j &lt; order.size(); j++) std::cout &lt;&lt; order[j] &lt;&lt; " "; std::cout &lt;&lt; "\n\n" &lt;&lt; std::endl; return; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T17:15:32.410", "Id": "394316", "Score": "0", "body": "I haven't included the if statement for sharps yet. You have to use 'Gb Major'" } ]
[ { "body": "<ol>\n<li><p>You should avoid the global vector variable and instead pass it by reference into the functions. I would remove all global variables and pass them through functions instead.</p></li>\n<li><p>The input is a little weird. You could do it differently using getline. It should not be checking...
{ "AcceptedAnswerId": "204483", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T17:05:02.087", "Id": "204472", "Score": "10", "Tags": [ "c++", "beginner", "music" ], "Title": "Generating a musical scale from a root note" }
204472
<pre><code>&lt;?php require_once '../db.php'; session_start(); // Check if user is logged in using the session variable if( $_SESSION['logged_in'] != 1 ){ $_SESSION['message'] = ""; header("location: error.php"); } else { $username = $_SESSION['username']; } //here starts the code to insert data on DB, and to make a slug $slug = ''; if(isset($_POST["create"])){ $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($_POST["title"]))); $query = "SELECT slug_url FROM bn_publicacao WHERE slug_url LIKE '$slug%'"; $statement = $conn-&gt;prepare($query); if($statement-&gt;execute()){ $total_row = $statement-&gt;rowCount(); if($total_row &gt; 0){ $result = $statement-&gt;fetchAll(); foreach($result as $row){ $data[] = $row['slug_url']; } if(in_array($slug, $data)){ $count = 0; while( in_array( ($slug . '-' . ++$count ), $data) ); $slug = $slug . '-' . $count; } } } $insert_data = array( ':title' =&gt; $_POST['title'], ':data_hora' =&gt; $_POST['data_hora'], ':datePublished' =&gt; $_POST['datePublished'], ':dateModified' =&gt; $_POST['dateModified'], ':descricao' =&gt; $_POST['descricao'], ':capa' =&gt; $_POST['capa'], ':width' =&gt; $_POST['width'], ':height' =&gt; $_POST['height'], ':alt' =&gt; $_POST['alt'], ':keywords' =&gt; $_POST['keywords'], ':categoria' =&gt; $_POST['categoria'], ':slug_url' =&gt; $slug, ':slug_link' =&gt; $slug, ':entry_type' =&gt; $_POST['entry_type'], ); $query = "INSERT INTO bn_publicacao (title, data_hora, datePublished, dateModified, descricao, capa, width, height, alt, keywords, categoria, slug_url, slug_link, entry_type) VALUES (:title, :data_hora, :datePublished, :dateModified, :descricao, :capa, :width, :height, :alt, :keywords, :categoria, :slug_url, :slug_link, :entry_type)"; $statement = $conn-&gt;prepare($query); $statement-&gt;execute($insert_data); } $conn = NULL; ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="pt_BR"&gt; &lt;head&gt; &lt;title&gt;Gravar&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;input type="text" name="title" autocomplete="off" required&gt; &lt;span data-placeholder="Title"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="datePublished" class="input100" autocomplete="on" required&gt; &lt;span data-placeholder="datePublished"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="dateModified" autocomplete="on" required&gt; &lt;span data-placeholder="dateModified"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="keywords" class="input100" autocomplete="off" required&gt; &lt;span data-placeholder="Keywords"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="data_hora" class="input100" autocomplete="on" required&gt; &lt;span data-placeholder="Data e Hora"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="descricao" autocomplete="off" required&gt; &lt;span data-placeholder="Descrição"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="capa" autocomplete="off" required&gt; &lt;span data-placeholder="Capa Url - ratio 5:2 h/w"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="alt" autocomplete="off" required&gt; &lt;span class="focus-input100" data-placeholder="Alt"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="categoria" required&gt; &lt;span data-placeholder="Categoria"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="entry_type" required&gt; &lt;span data-placeholder="Entry_type"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="width" autocomplete="off" required&gt; &lt;span class="focus-input100" data-placeholder="Width"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="height" autocomplete="off" required&gt; &lt;span data-placeholder="Height"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;button type="submit" name="create"&gt; Enviar &lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;div&gt; &lt;a href="ir.php"&gt; &lt;button name="logout"&gt; Log Out &lt;/button&gt; &lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This file is accessible through my login system that i posted here on codereview earlier: <a href="https://codereview.stackexchange.com/questions/204394/">Login System using PHP and PDO Prepared Statement</a></p> <p>It's just a simple code that i made, using prepared statement, to insert data on my database.</p> <p>What you think about my code? Any suggestion?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T07:24:55.733", "Id": "394407", "Score": "0", "body": "In your first select query you don't bind the value of `$slug%` to a corresponding named placeholder in the SQL statement. I think you should, despite the filtering before. Just ...
[ { "body": "<ol>\n<li>Just as I suspected, the authorization code doesn't protect anything. A <code>header(\"Location: ...\")</code> is <em>advisory</em> for the browser, which may ignore it... and continue to load the page you consider protected. Always have a <code>die()</code> call after the redirect header, ...
{ "AcceptedAnswerId": "204515", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T17:15:56.870", "Id": "204473", "Score": "2", "Tags": [ "php", "sql", "database", "pdo" ], "Title": "Insert data on Data Base using PDO Prepared Statement" }
204473
<p>I'm trying to read two sufficiently large binary files, comparing them and printing the offset at which they differ. I'm using <code>fread</code> to read the binary files and <code>memcmp</code> to compare them.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;time.h&gt; clock_t start, end; int main(int argc, char *argv[]) { double cpu_time_taken; FILE *fp1, *fp2; printf("\nArgument count: %d", argc); printf("\nFile 1 is: %s", argv[1]); printf("\nFile 2 is: %s\n", argv[2]); if (argc &lt; 3) { printf("\nInsufficient Arguments: \n"); printf("\nHelp:./executable &lt;filename1&gt; &lt;filename2&gt;\n"); return 0; } else { fp1 = fopen(argv[1], "rb"); if (fp1 == NULL) { printf("\nError in opening file %s", argv[1]); return 0; } fp2 = fopen(argv[2], "rb"); if (fp2 == NULL) { printf("\nError in opening file %s", argv[2]); return 0; } if ((fp1 != NULL) &amp;&amp; (fp2 != NULL)) { start = clock(); compare_two_binary_files(fp1, fp2); end = clock(); cpu_time_taken = ((double) (end - start)) / CLOCKS_PER_SEC; printf("\nTime taken to compare: %f", cpu_time_taken*1000); } } } int compare_two_binary_files(FILE *fp1, FILE *fp2) { char tmp1[16], tmp2[16]; size_t bytes = 0, readsz = sizeof tmp1; int count = 0; while (!feof(fp1) || !feof(fp2)){ fread (tmp1, sizeof *tmp1, readsz, fp1); fread (tmp2, sizeof *tmp2, readsz, fp2); count += 16; if(memcmp(tmp1, tmp2, readsz)){ for(int i=0; i &lt; readsz; i++){ printf ("%d: 0x%02x ",i, tmp1[i]); } printf("\n%x", count); return 0; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T21:07:22.497", "Id": "394350", "Score": "2", "body": "Why don't you mmap them: https://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "...
[ { "body": "<blockquote>\n<pre><code>fread (tmp1, sizeof *tmp1, readsz, fp1);\nfread (tmp2, sizeof *tmp2, readsz, fp2);\ncount += 16;\nif(memcmp(tmp1, tmp2, readsz)){\n …\n}\n</code></pre>\n</blockquote>\n\n<p>You are discarding the return values of the <code>fread()</code> calls, blindly assuming that they b...
{ "AcceptedAnswerId": "204485", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T18:39:19.357", "Id": "204478", "Score": "10", "Tags": [ "performance", "c", "file" ], "Title": "Comparing two large binary files in C" }
204478
<p><em>This is not a "please do my homework" question.</em> I solved a problem two ways and would like to know which solution is better; better being defined by better readability, lower complexity and lower memory consumption. I'd also like to note that this is a not a homework assignment but an optional no-credit practice problem.</p> <p>My CS class offers practice problems through their site. One specific question is named <a href="https://practiceit.cs.washington.edu/problem/view/cs2/sections/arraylist/removeShorterStrings" rel="nofollow noreferrer">"removeShorterStrings."</a> The prompt being:</p> <blockquote> <p>Write a method removeShorterStrings that takes an ArrayList of Strings as a parameter and that removes from each successive pair of values the shorter string in the pair. For example, suppose that an ArrayList called list contains the following values: <code>{"four", "score", "and", "seven", "years", "ago"}</code> In the first pair, "four" and "score", the shorter string is "four". In the second pair, "and" and "seven", the shorter string is "and". In the third pair, "years" and "ago", the shorter string is "ago". Therefore, the call: removeShorterStrings(list); should remove these shorter strings, leaving the list as follows: "score", "seven", "years". If there is a tie (both strings have the same length), your method should remove the first string in the pair. If there is an odd number of strings in the list, the final value should be kept in the list.</p> </blockquote> <p>I have come up with the following solutions:</p> <p>The "ask for permission" solution:</p> <pre><code>void removeShorterStrings(ArrayList&lt;String&gt; list) { if (list.size() != 0) { int isOdd = (list.size() &gt;&gt; 0) &amp; 1; for (int i = 0; i &lt;= (list.size() &gt;&gt; 1) - isOdd; i++) { String first = list.get(i); String second = list.get(i + 1); if (first.length() &lt;= second.length()) { list.remove(i); } else { list.remove(i + 1); } } } } </code></pre> <p>and the "ask for forgiveness" solution:</p> <pre><code>void removeShorterStrings(ArrayList&lt;String&gt; list) { for (int i = 0; i &lt;= (list.size() &gt;&gt; 1); i++) { try { String first = list.get(i); String second = list.get(i + 1); if (first.length() &lt;= second.length()) { list.remove(i); } else { list.remove(i + 1); } } catch (IndexOutOfBoundsException e) { break; } } } </code></pre> <p>I come from a JavaScript/python background, so I'm unsure of what is considered "good practice" in java.</p> <p><strong>TL;DR: Which solution is better in terms of better readability, lower complexity and lower memory consumption?</strong></p>
[]
[ { "body": "<p>Asking for forgiveness would be the best policy for dealing with errors that may be beyond your control, such as when opening a file for reading. Checking beforehand is useless, because too many things could go wrong: the file might not exist, you might not have the right permissions, the disk co...
{ "AcceptedAnswerId": "204491", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T21:21:04.757", "Id": "204488", "Score": "3", "Tags": [ "java", "comparative-review", "error-handling", "homework" ], "Title": "Given a list of words, remove the shorter word of every pair" }
204488
<p>I'm programming a board game called Djambi, where most of its pieces can move like the queen from chess. I created a list to save all valid destinations of a piece, which can be in 8 different directions, so I used 8 <code>for</code> loops, but the code of each loop is almost identical:</p> <p>This is the loop for possible movements to the right:</p> <pre><code>count = 0 for j in range(y+1,9): if P == 3 and count == 2: break if re.search(r'[■]',board[x][j]): pos = str(x)+str(j) destinations.append(pos) elif re.search(r'\d', board[x][j]): if re.search(r'' + chip[0], board[x][j]) or P == 1 or P == 0: break else: pos = str(x)+str(j) destinations.append(pos) break elif re.search(r'[░]',board[x][j]): if P == 0: pos = str(x)+str(j) destinations.append(pos) break else: break else: if P == 2: pos = str(x)+str(j) destinations.append(pos) else: continue count += 1 </code></pre> <p>The loop for movements to the left can be simplified with the one above, but the problem is for the loops for movements up</p> <pre><code>count = 0 for i in range(x+1,9): if P == 3 and count == 2: break if re.search(r'[■]',board[i][y]): pos = str(i)+str(y) destinations.append(pos) elif re.search(r'[\d]',board[i][y]): if re.search(r'' + chip[0], board[i][y]) or P == 1 or P == 0: break else: pos = str(i)+str(y) destinations.append(pos) break elif re.search(r'[░]',board[i][y]): if P == 0: pos = str(i)+str(y) destinations.append(pos) break else: break else: if P == 2: pos = str(i)+str(y) destinations.append(pos) else: continue count += 1 </code></pre> <p>and down, because the order of variables that change is different, also for diagonal movements:</p> <pre><code>count = 0 for i,j in zip( range(x+1,9) , range(y+1,9) ): if P == 3 and count == 2: break if re.search(r'[■]',board[i][j]): pos = str(i)+str(j) destinations.append(pos) elif re.search(r'[\d]',board[i][j]): if re.search(r'' + chip[0], board[i][j]) or P == 1 or P == 0: break else: pos = str(i)+str(j) destinations.append(pos) break elif re.search(r'[░]',board[i][j]): if P == 0: pos = str(i)+str(j) destinations.append(pos) break else: break else: if P == 2: pos = str(i)+str(j) destinations.append(pos) else: continue count += 1 </code></pre> <ul> <li><code>x</code> and <code>y</code> are the fixed coordinates of the original position of the chip</li> <li><code>i</code> and <code>j</code> are the variable coordinates</li> <li><code>board</code> is a matrix of 9x9 dimensions</li> </ul> <p>I want to know if there is a way to implement a kind of function of method or whatever Python can provide to simplify the code above in one chunk, and call it depending of what is needed, in this case, calling it 8 times.</p> <p>The code works, I just want to know how to simplify it and make it more understandable.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T21:38:48.507", "Id": "394355", "Score": "0", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the titl...
[ { "body": "<p>Yes, you can simplify the implementation of your algorithm by introducing the notion of <em>direction</em>, like you find in mathematics…</p>\n\n<p>In Djanbi game, a token can move in <a href=\"https://upload.wikimedia.org/wikipedia/commons/thumb/9/91/Djambi_moves.svg/1280px-Djambi_moves.svg.png\"...
{ "AcceptedAnswerId": "204526", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T21:30:24.983", "Id": "204489", "Score": "0", "Tags": [ "python", "python-3.x", "game" ], "Title": "Validate destinations of a piece in a board game" }
204489
<p>I was just wondering if there was a better way to write this block of code in php. I have a string with values separated by commas. I need to prepare that string to pass it on to the query using IN clause. </p> <pre><code> $sql = "SELECT domain, items FROM rep_skills WHERE report_id = $id "; $data = $conn-&gt;query($sql)-&gt;fetch_object(); while($data){ // can this be done in one line? $array = explode(",",$data-&gt;items); // string here is 39,40,41 $items = implode("','",$array); // string here is 39','40','41 // end of block $result = $conn-&gt;query("SELECT description FROM ".$tables[$data-&gt;domain]." WHERE item_id IN ('".$items."')"); $description = ''; while($row = $result-&gt;fetch_object()){ $details .= '- '.$row-&gt;description; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T22:01:42.947", "Id": "394358", "Score": "1", "body": "Where does `$records` come from? How can you be certain that it contains only comma-separated numbers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-0...
[ { "body": "<p>It's a very weird database schema in the first place.</p>\n\n<p>There should be never a thing like <strong>comma-separated values in one cell</strong>. Learn the database normalization and then create a link table wghich can be used to get all your records in a single query with JOIN.</p>\n\n<p>Th...
{ "AcceptedAnswerId": "204608", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T21:55:25.390", "Id": "204490", "Score": "1", "Tags": [ "php", "sql", "mysqli" ], "Title": "Use a comma-separated field in another SQL query" }
204490
<p>In my project I have an <code>async</code> method <code>AnAsynWebServiceCallHere</code> for calling a web service. I want to call <code>AnAsynWebServiceCallHere</code> twice in parallel and at the end I want to return the combined result. Will at the end of this method</p> <pre><code>public async Task&lt;List&lt;DesiredResult&gt;&gt; GetMyDesiredData(MyParamDTO dto) { List&lt;DesiredResult&gt; list = new List&lt;DesiredResult&gt;(); await Task.WhenAll( Task.Run(()=&gt; {var result1 = AnAsynWebServiceCallHere(dto.A);list.Add(result1);}), Task.Run(()=&gt; {var result2 = AnAsynWebServiceCallHere(dto.A);list.Add(result2);}) ); return list; } </code></pre> <p>and body of the '' method is:</p> <pre><code>public async Task&lt;DesiredResult&gt; AnAsynWebServiceCallHere(string sqlQuery) { string json; using(HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://demoapi.MyHost.net/SQLRunner")) { request.Headers.Add("id", SECURITY_TOKEN); request.Headers.Add("sqlStatement", sqlQuery); HttpResponseMessage response = await client.SendAsync(request); json = await response.Content.ReadAsStringAsync(); } return JsonConvert.DeserializeObject&lt;DesiredResult&gt;(json); } </code></pre> <p>Is the written method an elegant approach?</p> <p><strong>Update:</strong> Context provided with the called method body.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T05:37:16.383", "Id": "394400", "Score": "0", "body": "We cannot tell you whether this is an elegant approach or not becase this code isn't real and we don't review pseudo/hypothetical code." }, { "ContentLicense": "CC BY-SA ...
[ { "body": "<p>If <code>AnAsynWebServiceCallHere</code> is already async then there is no need for the additional <code>Task.Run</code> in the <code>Task.WhenAll</code>. </p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=netframework-4.7.2#System_Threading_T...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T22:01:36.103", "Id": "204492", "Score": "-1", "Tags": [ "c#" ], "Title": "optimizing parallel webservice calls" }
204492
<p>This is a CLI utility for managing the allocation of investment. It's an exercise, don't take it too seriously. So the utility asks the user a series of questions about it's finances and suggests a balanced investment profile. This was supposed to be a marathon script, however due to a bug, marathon fails to update packages whenever one tries to use Vapor. It works first time, but not the second. But it is perfectly fine with Swift Package Manager.</p> <p>I want help on controlling the unwieldy use of force unwraps, how do I avoid these? Also, general code style improvement would be greatly appreciated.</p> <pre><code>import CSVImporter // marathon: /home/luis/Dropbox/Documentos/Coding/Swift/Libraries/CSVImporter import Console // marathon: https://github.com/vapor/console.git import Files // marathon: https://github.com/JohnSundell/Files.git import Docopt // marathon: https://github.com/lf-araujo/docopt.swift.git extension Date { static func - (lhs: Date, rhs: Date) -&gt; TimeInterval { return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate } } let doc: String = """ Allocator Passive allocation investment tool. It departs from three assumptions: 1. the age when one wants to stop investing (should take life expectancy in your country into consideration); 2. the user risk profile; 3. that assets are grouped in three pools. 3.1. the emergency fund, corresponds to expenses for six months (think six months of unemployment), 3.2. the second pool corresponds to low risk investments 3.3. the third pool are the high risk investments. Try to vary the types of investment within each pool, this tool will not handle investments within pool, only the total pool value. Decision on what is low and high risk, as well as decision on the risk profile is entirely on users discretion. Every year, the tool will help the user allocate the correct amount in each of the pools, based in a simple algorithm. Finally, since sometimes one needs to quickly record a deposit into one of the investments , there is a quick-add add command, in which one can add the latest low risk and high risk investment without going trough all the questions. Usage: allocator [(quick-add &lt;low&gt; &lt;high&gt;)] Options: -h --help Shows this screen --version """ // Managing arguments var args = CommandLine.arguments args.remove(at: 0) let argument = Docopt.parse(doc, argv: args, help: true, version: "0.0.1") // Setting today's date let date = Date() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let today = formatter.string(from: date) // Setting the terminal interface let terminal = Terminal() let importer: [String:String] let importedRecords: [[String:String]] var header: String = "" var content: String = "" // If this is not the first run if Folder.current.files.names.contains("finances.csv") { let importer = CSVImporter&lt;[String: String]&gt;(path: "finances.csv") let importedRecords = importer.importRecords(structure: { (headerValues) -&gt; Void in header = headerValues.compactMap { $0 }.joined(separator: ",") + "\n" }) { $0 } if argument["quick-add"] as? String == "true" { var count: Int = 0 for record in importedRecords { content += "\(record["date"]!),\(record["investpercent"]!),\(record["expenses"]!),\(record["savings"]!)," content += "\(record["low"]!),\(record["high"]!),\(record["objective"]!)\n" //second line count += 1 if count == importedRecords.endIndex { content += "\(today),\(record["investpercent"]!),\(record["expenses"]!),\(record["savings"]!)," content += "\(argument["&lt;low&gt;"]!),\(argument["&lt;high&gt;"]!),\(record["objective"]!)\n" } } try Folder.current.file(named: "finances.csv").append(string: content) } else { let reversedRecords = importedRecords.reversed() let zipped = zip(reversedRecords.dropFirst(), reversedRecords) var lastPercentUpdate: String = "" if let twoDictionaries = zipped.first(where: {$0["investpercent"] != $1["investpercent"]}), let date = twoDictionaries.1["date"] { lastPercentUpdate = date } let lastentry = Array(importedRecords.suffix(1)) var investpercent: Double = Double(lastentry[0]["investpercent"]!)! var expenses: Double = Double(lastentry[0]["expenses"]!)! if (formatter.date(from: today)! - formatter.date(from: lastPercentUpdate)!) &gt; 15778800 { //print(lastentry[0]["date"]) expenses = Double(terminal.ask(""" It's been more than 6 months since you updated the amount you should be saving on the emergency pool. Please inform how much are your cummulative expenses in 6 months: """))! investpercent = Double(lastentry[0]["investpercent"]!)! - 1.0 } let investedlow = Double(terminal.ask("Invested value in low risk since last time:")) ?? 0.0 let investedhigh = Double(terminal.ask("Invested value in high risk since last time:")) ?? 0.0 let lowtoday = Double(terminal.ask("Total low risk value today:")) ?? Double(lastentry[0]["low"]!)! let hightoday = Double(terminal.ask("Total high risk value today:")) ?? Double(lastentry[0]["high"]!)! let savings = Double(terminal.ask("Enter your current savings account status:")) ?? Double(lastentry[0]["savings"]!)! let invest = Double(terminal.ask("Finally, how much you have to save today:")) ?? 0.0 let aimhigh = ((lowtoday + hightoday) * investpercent) / 100 let aimlow = ((lowtoday + hightoday) * (100 - investpercent)) / 100 if expenses &gt; savings { terminal.print(""" It's time to update the savings account, deposit \(expenses - savings). """) } else { if investpercent &lt;= 0 { investpercent = 0 print(""" Congratulations! You've reached the year which you wanted to stop moving money around! Don't forget to consider converting all high risk investiment into types of high risk investiment that generates dividends. """) } } let investhigh = (aimhigh / (aimhigh + aimlow)) * invest let investlow = (aimlow / (aimhigh + aimlow)) * invest let objective = expenses - ( (lowtoday + hightoday) - (investedlow + investedhigh) - (Double(lastentry[0]["low"]!)! + Double(lastentry[0]["high"]!)!)) print("\nDeposit \(investhigh) into the high risk pool.\n") print("Deposit \(investlow) into the low risk pool.\n") // salvar o arquivo content += "\(today),\(investpercent),\(expenses),\(savings),\(lowtoday),\(hightoday),\(objective)\n" try Folder.current.file(named: "finances.csv").append(string: content) print("Your data has been saved to finances.csv in this directory. Goodbye!\n") } } else if !Folder.current.files.names.contains("finances.csv") { // This is the first run let age = Double(terminal.ask("What is your age?")) ?? 0.0 let end = Double(terminal.ask("In which age you want to stop managing finances (default: 80):")) ?? 80.0 let profile = Double(terminal.ask(""" What is your risk profile: low risk (type 40, this is the default), medium risk (type 20), high risk (type 0). Intermediary values are accepted: """)) ?? 40 let expenses = Double(terminal.ask("Enter your current cummulative 6 months expenses:")) ?? 0.0 let savings = Double(terminal.ask("Enter your current savings account volume:")) ?? 0.0 let low = Double(terminal.ask("Enter your low risk investiments total:")) ?? 0.0 let high = Double(terminal.ask("Enter your high risk investiments total:")) ?? 0.0 let invest = Double(terminal.ask("Finally, how much you have to save or invest today (default: 0):")) ?? 0.0 if expenses &gt; savings { terminal.print(""" You haven't reached the first step of creating the emergency pool. Deposit \(invest) now into your savings acount and keep doing it suntil it reaches \(expenses)\n Good luck! """) } else { let highobjective = ((end - profile - age) / 100) * invest let lowobjective = invest - highobjective terminal.print(""" Deposit \(lowobjective) into your low risk investiment pool. Deposit \(highobjective) into your high risk investiment pool. Your data has been saved to finances.csv in this directory. Goodbye! """) var content: String = "date,investpercent,expenses,savings,low,high,objective\n" content += "\(today),\(end - profile - age),\(expenses),\(savings),\(low),\(high),\(expenses / 6)\n" let outfile = try Folder.current.createFile(named: "finances.csv") try outfile.write(string: header + content) } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T22:18:09.347", "Id": "204494", "Score": "1", "Tags": [ "swift", "linux" ], "Title": "Reducing force unwraps in CLI utility" }
204494
<p>I'm new to the programming and I want to ask a question about my linkedlist stack implementation if it's correct and if it meets the requirements of the linkedlist stack implementation. If there is any suggestion I'm glad to hear... </p> <pre><code>public class DynamicStack { private class Node { private Object item; private Node next; Node(Object item){ this.item = item; this.next = null; } Node(Object item, Node nextNode){ this.item = item; this.next = nextNode; } } private int count; private Node top; public DynamicStack() { this.top = null; this.count = 0; } public void push(Object item) { if(top == null) { top = new Node(item); }else { Node newNode = new Node(item,top); top = newNode; } count++; } public Object peek() { if(top == null) { throw new NoSuchElementException("Underflow Exception"); }else { return top.item; } } public Object pop() { Node currentNode = top; if(top == null) { throw new NoSuchElementException("Underflow Exception"); }else { Node nextNode = top.next; top = null; top = nextNode; } count--; return currentNode.item; } </code></pre>
[]
[ { "body": "<p>This looks to me like it will work as intended. I have a few suggestions for improvement though:</p>\n\n<ul>\n<li>You keep the <code>count</code> variable up to date but never use it's value for anything. You can either remove it or provide a <code>size()</code> method.</li>\n<li>You might change ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-27T22:37:48.767", "Id": "204495", "Score": "2", "Tags": [ "java", "beginner", "linked-list", "stack" ], "Title": "LinkedList Stack Implementation" }
204495
<p>The Hungarian algorithm solves the assignment problem, and I'm looking for any suggestions regarding improvement on my implementation (also coding style). It is based on the wikipedia <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm" rel="nofollow noreferrer">entry</a> and references therein. I have to use it repeatedly in calculations having cost matrices with anywhere between 15 and 40 rows or columns, note the cost matrix is not generally square. </p> <p>I've got a working C version that will run in about 45 sec on my laptop with -O3 compiler options for a 15 x 15 cost matrix. The algorithm moves between steps 4 and 6 multiple times before convergence.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;float.h&gt; #include &lt;assert.h&gt; #include &lt;stdbool.h&gt; #include &lt;time.h&gt; #define TOL 0.000001 typedef struct idx_t { int row; int col; int nrows; // rows - n int ncols; // cols - m int path_ct; double min; double* dm; int* M; int** path; int* path_row; int* path_col; int* row_cover; int* col_cover; int path_count; int path_row_0; int path_col_0; } idx_t; double get_random() { return ((double)rand() / (double)RAND_MAX); } struct idx_t* initIdxs( double** C, int n, int m ) { size_t i, j; struct idx_t* idxs = malloc( sizeof( struct idx_t )); assert( idxs != NULL ); idxs-&gt;nrows = n; // rows idxs-&gt;ncols = m; // columns idxs-&gt;min = DBL_MAX; idxs-&gt;dm = ( double* )calloc(( m * n ), sizeof( double )); idxs-&gt;M = ( int* ) calloc( (n * m), sizeof( int )); idxs-&gt;path = ( int** ) calloc(( m + n ), sizeof( int* )); idxs-&gt;row_cover = ( int* ) calloc( n, sizeof( int )); idxs-&gt;col_cover = ( int* ) calloc( m, sizeof( int )); idxs-&gt;path_row = ( int* ) calloc( n, sizeof( int )); idxs-&gt;path_col = ( int* ) calloc( m, sizeof( int )); for ( i = 0; i &lt; m + n; i++ ) idxs-&gt;path[i] = ( int* ) calloc( 2, sizeof( int )); for ( i = 0; i &lt; n; i++ ){ for ( j = 0; j &lt; m; j++ ){ idxs-&gt;dm[i*n+j] = C[i][j]; } } return idxs; } // For each row of the cost matrix, find the smallest element and subtract // it from every element in its row. Go to Step 2. int step_one( struct idx_t* idxs ) { double min_in_row; size_t r, c; size_t n = idxs-&gt;nrows; for ( r = 0; r &lt; idxs-&gt;nrows; r++ ){ min_in_row = idxs-&gt;dm[r*n]; for ( c = 0; c &lt; idxs-&gt;ncols; c++ ){ if ( idxs-&gt;dm[r*n+c] &lt; min_in_row ) min_in_row = idxs-&gt;dm[r*n+c]; } for ( c = 0; c &lt; idxs-&gt;ncols; c++ ) idxs-&gt;dm[r*n+c] -= min_in_row; } return 2; // step two } //Find a zero (Z) in the resulting matrix. If there is no starred //zero in its row or column, star Z. Repeat for each element, then go to Step 3. int step_two( struct idx_t* idxs ){ size_t r, c; size_t n = idxs-&gt;nrows; size_t m = idxs-&gt;ncols; size_t L = n &lt; m ? n : m; int i; int* z; if ( L == m ) z = &amp;idxs-&gt;col_cover[L]; else z = &amp;idxs-&gt;row_cover[L]; for ( int i = 0; i &lt; L; i++ ){ if ( idxs-&gt;row_cover[r] == 0 &amp;&amp; idxs-&gt;col_cover[c] == 0 ){ if ( idxs-&gt;dm[r*n+c] &lt; TOL ){ idxs-&gt;M[r*n+c] = 1; idxs-&gt;dm[r*n+c] = 0.0; idxs-&gt;row_cover[r] = 1; idxs-&gt;col_cover[c] = 1; } } } for ( i = 0; i &lt; L; i++ ){ idxs-&gt;row_cover[i] = 0; idxs-&gt;col_cover[i] = 0; } for ( i = 0; i &lt; m-L; i++ ) z[i] = 0; return 3; } //Cover each column containing a starred zero. If all columns are covered, //these describe a complete set of unique assignments. In such //case, we're DONE. Otherwise, go to Step 4. int step_three( struct idx_t* idxs ){ size_t r, c; size_t n = idxs-&gt;nrows; int col_count = 0; int step = 0; for ( r = 0; r &lt; idxs-&gt;nrows; r++ ) { for ( c = 0; c &lt; idxs-&gt;ncols; c++ ) { if ( idxs-&gt;M[r*n+c] == 1 ) { idxs-&gt;col_cover[c] = 1; col_count += 1; } } } if ( col_count == idxs-&gt;ncols || col_count == idxs-&gt;nrows ) { step = 7; } else { step = 4; } return step; } void find_zero( struct idx_t* idxs ){ size_t r = 0; size_t c = 0; size_t n = idxs-&gt;nrows; bool done = false; idxs-&gt;row = -1; idxs-&gt;col = -1; while ( !done ){ c = 0; while ( true ){ if ( idxs-&gt;row_cover[r] == 0 &amp;&amp; idxs-&gt;col_cover[c] == 0 &amp;&amp; idxs-&gt;dm[r*n+c] &lt; TOL ){ idxs-&gt;row = r; idxs-&gt;col = c; idxs-&gt;dm[r*n+c] = 0; done = true; } c += 1; if ( c &gt;= idxs-&gt;ncols || done ) break; } r += 1; if ( r &gt;= idxs-&gt;nrows ) done = true; } } bool star_in_row( struct idx_t* idxs ){ bool tmp = false; size_t n = idxs-&gt;nrows; size_t c = 0; for ( c = 0; c &lt; idxs-&gt;ncols; c++ ){ if ( idxs-&gt;M[idxs-&gt;row*n+c] == 1 ){ tmp = true; idxs-&gt;col = c; } } return tmp; } void find_star_in_row( struct idx_t* idxs ){ size_t c = 0; idxs-&gt;col = -1; size_t n = idxs-&gt;nrows; for ( c = 0; c &lt; idxs-&gt;ncols; c++ ){ if ( idxs-&gt;M[idxs-&gt;row*n+c] == 1 ) idxs-&gt;col = c; } } //Find a noncovered zero and prime it. If there is no starred zero //in the row containing it, go to 5. Otherwise, //cover this row and uncover the column containing the starred zero. //Continue until there are no uncovered zeros left. //Save the smallest uncovered value and go to Step 6. int step_four( struct idx_t* idxs ){ int step = 0; size_t n = idxs-&gt;nrows; bool done = false; idxs-&gt;row = -1; idxs-&gt;col = -1; while ( !done ){ find_zero( idxs ); if ( idxs-&gt;row == -1 ){ done = true; step = 6; } else { idxs-&gt;M[idxs-&gt;row*n+idxs-&gt;col] = 2; if ( star_in_row( idxs )){ idxs-&gt;row_cover[idxs-&gt;row] = 1; idxs-&gt;col_cover[idxs-&gt;col] = 0; } else { done = true; step = 5; idxs-&gt;path_row_0 = idxs-&gt;row; idxs-&gt;path_col_0 = idxs-&gt;col; } } } return step; } void find_star_in_col( struct idx_t* idxs ){ size_t i; size_t col = idxs-&gt;path[idxs-&gt;path_ct][1]; idxs-&gt;row = -1; size_t n = idxs-&gt;nrows; for ( i = 0; i &lt; idxs-&gt;nrows; i++ ){ if ( idxs-&gt;M[i*n+col] == 1 ) idxs-&gt;row = i; } } void find_prime_in_row( struct idx_t* idxs ){ size_t j; size_t row = idxs-&gt;path[idxs-&gt;path_ct][0]; size_t n = idxs-&gt;nrows; for ( j = 0; j &lt; idxs-&gt;ncols; j++ ){ if ( idxs-&gt;M[row*n+j] == 2 ) idxs-&gt;col = j; } } void augment_path( struct idx_t* idxs ){ size_t n = idxs-&gt;nrows; for ( int p = 0; p &lt; idxs-&gt;path_ct + 1; p++ ) if ( idxs-&gt;M[idxs-&gt;path[p][0]*n+idxs-&gt;path[p][1]] == 1 ){ idxs-&gt;M[idxs-&gt;path[p][0]*n+idxs-&gt;path[p][1]] = 0; } else { idxs-&gt;M[idxs-&gt;path[p][0]*n+idxs-&gt;path[p][1]] = 1; } } void clear_covers( struct idx_t* idxs ){ size_t r, c; size_t n = idxs-&gt;nrows; size_t m = idxs-&gt;ncols; size_t L = n &lt; m ? n : m; int i; int* z; if ( L == m ) z = &amp;idxs-&gt;col_cover[L]; else z = &amp;idxs-&gt;row_cover[L]; for ( i = 0; i &lt; L; i++ ){ idxs-&gt;row_cover[i] = 0; idxs-&gt;col_cover[i] = 0; } for ( i = 0; i &lt; m-L; i++ ) z[i] = 0; } void erase_primes( struct idx_t* idxs ){ size_t r, c; size_t n = idxs-&gt;nrows; for ( r = 0; r &lt; idxs-&gt;nrows; r++ ){ for ( c = 0; c &lt; idxs-&gt;ncols; c++ ) if ( idxs-&gt;M[r*n+c] == 2 ) idxs-&gt;M[r*n+c] = 0; } } //Construct a series of alternating primed and starred zeros. //Z0 is the uncovered primed zero found in Step 4. Z1 is //the starred zero in the column of Z0 (if any). Z2 is the primed zero //in the row of Z1. Continue until the series //ends at a primed zero that has no starred zero in its column. //Clear each starred zero of the series, star each primed zero of the series. //Then erase all primes and uncover every line in the matrix. Return to Step 3. int step_five( struct idx_t* idxs ) { bool done = false; int tmp; idxs-&gt;path_ct = 0; idxs-&gt;row = -1; idxs-&gt;col = -1; idxs-&gt;path[0][0] = idxs-&gt;path_row_0; idxs-&gt;path[0][1] = idxs-&gt;path_col_0; while ( !done ){ find_star_in_col( idxs ); if ( idxs-&gt;row &gt; -1 ){ idxs-&gt;path_ct += 1; tmp = idxs-&gt;path_ct - 1; idxs-&gt;path[idxs-&gt;path_ct][0] = idxs-&gt;row; idxs-&gt;path[idxs-&gt;path_ct][1] = idxs-&gt;path[tmp][1]; } else { done = true; } if ( !done ){ find_prime_in_row( idxs ); idxs-&gt;path_ct += 1; tmp = idxs-&gt;path_ct - 1; idxs-&gt;path[idxs-&gt;path_ct][0] = idxs-&gt;path[tmp][0]; idxs-&gt;path[idxs-&gt;path_ct][1] = idxs-&gt;col; } } augment_path( idxs ); clear_covers( idxs ); erase_primes( idxs ); return 3; } void min_val( struct idx_t* idxs ) { size_t r, c; size_t n = idxs-&gt;nrows; for ( r = 0; r &lt; idxs-&gt;nrows; r++ ){ if ( idxs-&gt;row_cover[r] == 0 ) { for ( c = 0; c &lt; idxs-&gt;ncols; c++ ){ if ( idxs-&gt;col_cover[c] == 0 ){ if ( idxs-&gt;min &gt; idxs-&gt;dm[r*n+c] ) idxs-&gt;min = idxs-&gt;dm[r*n+c]; } } } } } //Add the value found in Step 4 to every element of each covered row, and subtract //it from every element of each uncovered column. Return to Step 4 int step_six( struct idx_t* idxs ) { size_t r, c; size_t n = idxs-&gt;nrows; min_val( idxs ); for ( r = 0; r &lt; idxs-&gt;nrows; r++ ){ for ( c = 0; c &lt; idxs-&gt;ncols; c++ ){ if ( idxs-&gt;row_cover[r] == 1 ) idxs-&gt;dm[r*n+c] += idxs-&gt;min; if( idxs-&gt;col_cover[c] == 0 ) idxs-&gt;dm[r*n+c] -= idxs-&gt;min; } } return 4; } double calc_cost( double** C, struct idx_t* idxs ){ size_t i, j; size_t n = idxs-&gt;nrows; double cost = 0; for ( i = 0; i &lt; idxs-&gt;nrows; i++ ){ for ( j = 0; j &lt; idxs-&gt;ncols; j++ ) if ( idxs-&gt;M[i*n+j] == 1 ) cost += C[i][j]; } return cost; } void deleteMem(struct idx_t* idxs ){ size_t i; for ( i = 0; i &lt; idxs-&gt;ncols + idxs-&gt;nrows; i++ ) free( idxs-&gt;path[i] ); free( idxs-&gt;path_row ); free( idxs-&gt;path_col ); free( idxs-&gt;row_cover ); free( idxs-&gt;col_cover ); free( idxs-&gt;path); free( idxs-&gt;dm ); free( idxs-&gt;M ); free( idxs ); return; } double assignment( double** C, int m, int n ){ bool done = false; unsigned int start; double diff; double msec; double sec; double cps = 1000000.0; struct idx_t* idxs; idxs = initIdxs( C, m, n ); int step = 1; double cost = 0; while ( !done ){ switch ( step ){ case 1: // start = clock(); step = step_one( idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 1: Time taken %f seconds %f milliseconds\n", sec, msec); break; case 2: // start = clock(); step = step_two( idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 2: Time taken %f seconds %f milliseconds\n", sec, msec); break; case 3: // start = clock(); step = step_three( idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 3: Time taken %f seconds %f milliseconds\n", sec, msec); break; case 4: // start = clock(); step = step_four( idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 4: Time taken %f seconds %f milliseconds\n", sec, msec); break; case 5: // start = clock(); step = step_five( idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 5: Time taken %f seconds %f milliseconds\n", sec, msec); break; case 6: // start = clock(); step = step_six( idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 6: Time taken %f seconds %f milliseconds\n", sec, msec); break; case 7: // start = clock(); done = true; cost = calc_cost( C, idxs ); // diff = clock() - start; // msec = diff * (1000.0 / cps); // sec = diff / cps; // printf("Step 7: Time taken %f seconds %f milliseconds\n", sec, msec); break; } } deleteMem( idxs ); return cost; } int main(){ size_t i, j; unsigned int start; double diff; double msec; double sec; double cps = 1000000.0; int n = 15; double c = 0; double** C = malloc( n * sizeof( double* )); double* tmp = malloc(sizeof( double ) * n * n ); for( i = 0; i &lt; n; i++ ) C[i] = &amp;(tmp[i * n]); for( i = 0; i &lt; n; i++ ){ for( j = 0; j &lt; n; j++ ) C[i][j] = (i + 1) * (j + 1) + get_random(); } start = clock(); c = assignment(C, n, n); printf("\nIn c, cost = %10.4lf\n", c); diff = clock() - start; msec = diff * (1000.0 / cps); sec = diff / cps; printf("Total time: %f seconds %f milliseconds\n", sec, msec); free( C ); free( tmp ); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T03:33:13.793", "Id": "394393", "Score": "0", "body": "What range of values do you expect with `get_random()`? should it include 1.0?" } ]
[ { "body": "<blockquote>\n <p>I'm looking for any suggestions regarding improvement on my implementation (also coding style).</p>\n</blockquote>\n\n<p>Just some basic things.</p>\n\n<p><strong>No need for casting.</strong></p>\n\n<p>See <a href=\"https://stackoverflow.com/q/605845/2410359\">Do I cast the result...
{ "AcceptedAnswerId": "204504", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T00:26:07.973", "Id": "204497", "Score": "4", "Tags": [ "performance", "algorithm", "c", "mathematics" ], "Title": "Hungarian algorithm to perform least-cost assignments" }
204497
<p>The following is a program for my school. It's supposed to use a hashtable to store values/keys. We use a marking system to mark for empty indexes and deleted indexes. -1 for empty and -2 for deleted. This hashtable is an outdated concept but the real goal is to learn how to manipulate hashtables. I want to ask if this is efficient or how it could be improved, please be specific. Lastly, just take a look at the header to see what each function/how the program/code works.</p> <p><strong>Main.cpp:</strong></p> <pre><code>using namespace std; #include "tests.h" #include "hashtable.h" int main() { testHashTable(); cout &lt;&lt; endl; system("Pause"); return 0; } </code></pre> <p><strong>Tests.h (used to test the code):</strong></p> <pre><code>#include "hashtable.h" void testHashTable() { cout &lt;&lt; "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" &lt;&lt; endl; cout &lt;&lt; "Testing hashtables: " &lt;&lt; endl; cout &lt;&lt; "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" &lt;&lt; endl; cout &lt;&lt; "Constructing a hashtable and printing: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; HashTable test(7); cout &lt;&lt; test &lt;&lt; endl; cout &lt;&lt; "Capacity: " &lt;&lt; test.getCap() &lt;&lt; endl; cout &lt;&lt; "Number of items: " &lt;&lt; test.getNumOfItems() &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Hashtable insertion and print data: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; test.insertKey(21); cout &lt;&lt; test &lt;&lt; endl; test.insertKey(21); cout &lt;&lt; test &lt;&lt; endl; test.insertKey(7); test.insertKey(1991); test.insertKey(1992); test.insertKey(1996); test.insertKey(69); test.insertKey(420); cout &lt;&lt; test &lt;&lt; endl; cout &lt;&lt; "Number of items: " &lt;&lt; test.getNumOfItems() &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Searching and print: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Find 14, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(14) &lt;&lt; endl; cout &lt;&lt; "Find 400, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(400) &lt;&lt; endl; cout &lt;&lt; "Find 21, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(21) &lt;&lt; endl; cout &lt;&lt; "Find 1337, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(1337) &lt;&lt; endl; cout &lt;&lt; "Find 69, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(69) &lt;&lt; endl; cout &lt;&lt; "Find 420, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(420) &lt;&lt; endl; cout &lt;&lt; "Find 7, does it exist? " &lt;&lt; boolalpha &lt;&lt; test.searchKey(7) &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Deleting values in hashtable: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; test.deleteKey(21); test.deleteKey(69); test.deleteKey(420); test.deleteKey(1991); test.deleteKey(1969); cout &lt;&lt; test &lt;&lt; endl; cout &lt;&lt; "Number of items: " &lt;&lt; test.getNumOfItems() &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Hashtable insertion and print data again: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; test.insertKey(21); test.insertKey(69); cout &lt;&lt; test &lt;&lt; endl; cout &lt;&lt; "Number of items: " &lt;&lt; test.getNumOfItems() &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Rehash hashtable and print data again: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; test.rehash(); cout &lt;&lt; test &lt;&lt; endl; cout &lt;&lt; "Capacity: " &lt;&lt; test.getCap() &lt;&lt; endl; cout &lt;&lt; "Number of items: " &lt;&lt; test.getNumOfItems() &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Reset hashtable: " &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------" &lt;&lt; endl; test.resetTable(); cout &lt;&lt; test &lt;&lt; endl; cout &lt;&lt; "Number of items: " &lt;&lt; test.getNumOfItems() &lt;&lt; endl; cout &lt;&lt; "Is this hashtable empty? True or false? " &lt;&lt; boolalpha &lt;&lt; test.isEmpty() &lt;&lt; endl; } </code></pre> <p><strong>Hashtables.h:</strong></p> <pre><code>#ifndef HASHTABLE_H #define HASHTABLE_H using namespace std; #include &lt;iostream&gt; const int DEFAULTCAPACITY = 23; class HashTable { friend ostream&amp; operator&lt;&lt;(ostream&amp; out, const HashTable&amp; theTable); // Print operator overloading. public: // Constructors: HashTable(); // Default constructor. HashTable(int newCapacity); // Overloaded constructor. HashTable(const HashTable&amp; otherTable); // Copy constructor. HashTable(HashTable&amp;&amp; otherTable); // Move constructor. // Accessors: int getNumOfItems() const; // Spits out the number of items stored within the hashtable. int getCap() const; // Spits out the capacity of the hashtable. bool isEmpty() const; // Spits out if the hashtable is empty or not. // Function(s): void insertKey(int value); // Inserts a value into the hashtable using the hashvalue function to get the correct index. void deleteKey(int value); // Deletes a value within the hashtable, setting it to -2. void resetTable(); // Empties out the hashtable, setting everything to -1. void rehash(); // Rehashes all non-deleted/non-empty values of the hashtable into a bigger hashtable that is double that of the current hashtable (next prime #). bool searchKey(int value) const; // Returns true if it finds the value within the hashtable. // Operator overloading(s): HashTable&amp; operator=(const HashTable&amp; otherTable); // Assignment operator overloading. HashTable&amp; operator=(HashTable&amp;&amp; otherTable); // Move assignment operator overloading. // Destructor: ~HashTable(); // Destroys the hashtable. private: int hashValue(int key, int j) const; // Calculates an expression to get the hashvalue so you can store the value in index. int* searchKey(int value, int j) const; // Spits out an index if there's one, if not spits out nullptr. int *ht; // Points to hashtable. int numOfItems; // Number of items in the hashtable. int capacity; // Maximum length of the hashtable. }; #endif </code></pre> <p><strong>Hashtables.cpp:</strong></p> <pre><code>#include "hashtable.h" ostream&amp; operator&lt;&lt;(ostream&amp; out, const HashTable&amp; theTable) { for (int i = 0; i &lt; theTable.capacity; ++i) { out &lt;&lt; theTable.ht[i] &lt;&lt; " "; } return (out); } HashTable::HashTable() { capacity = DEFAULTCAPACITY; ht = new int[capacity]; for (int i = 0; i &lt; capacity; ++i) { ht[i] = -1; } numOfItems = 0; } HashTable::HashTable(int newCapacity) { capacity = newCapacity; ht = new int[capacity]; for (int i = 0; i &lt; capacity; ++i) { ht[i] = -1; } numOfItems = 0; } HashTable::HashTable(const HashTable&amp; otherTable) { // Set all member variables of the calling object: capacity = otherTable.capacity; numOfItems = otherTable.numOfItems; // Create a new array: ht = new int[capacity]; // Copy all elements of the array parameter onto the calling object: for (int i = 0; i &lt; numOfItems; ++i) { ht[i] = otherTable.ht[i]; } } HashTable::HashTable(HashTable&amp;&amp; otherTable) { ht = move(otherTable.ht); capacity = move(otherTable.capacity); numOfItems = move(otherTable.numOfItems); otherTable.ht = nullptr; otherTable.capacity = move(0); otherTable.numOfItems = move(0); } int HashTable::getNumOfItems() const { return (numOfItems); } int HashTable::getCap() const { return (capacity); } bool HashTable::isEmpty() const { return (numOfItems == 0); } int HashTable::hashValue(int key, int j) const { const int stepSize = 3; return ( ((key)+(j*stepSize)) % capacity ); // Space for readability. } void HashTable::insertKey(int value) { if (numOfItems &lt; capacity) { bool foundSlot = false; int j = 0; int* indexValue; while (!foundSlot) { indexValue = &amp;ht[hashValue(value, j)]; if (*indexValue == -1 || *indexValue == -2 || *indexValue == value) { if (*indexValue != value) { *indexValue = value; ++numOfItems; } foundSlot = true; } ++j; // Just increase the j... } } else { cerr &lt;&lt; "Capacity in HashTable has been reached, cannot exceed the capacity." &lt;&lt; endl; } } void HashTable::deleteKey(int value) { if (numOfItems != 0) { int* indexPosition = searchKey(value, 0); if (indexPosition != nullptr) { *indexPosition = -2; --numOfItems; } } } void HashTable::resetTable() { for (int i = 0; i &lt; capacity; ++i) { ht[i] = -1; } numOfItems = 0; } void HashTable::rehash() { int *oldHt = ht; int oldCapacity = capacity; capacity = (capacity * 2) + 1; ht = new int[capacity]; numOfItems = 0; for (int i = 0; i &lt; capacity; ++i) { ht[i] = -1; } for (int i = 0; i &lt; oldCapacity; ++i) { if (oldHt[i] != -1 &amp;&amp; oldHt[i] != -2) { insertKey(oldHt[i]); } } delete[] oldHt; oldHt = nullptr; } bool HashTable::searchKey(int value) const { int j = 0; int *indexValue = &amp;ht[hashValue(value, j)]; int *firstIndexValue = indexValue; bool stillSearching = true; while (stillSearching) { if (*indexValue == value || *indexValue == -1 || (indexValue == firstIndexValue &amp;&amp; j != 0)) { // The third or condition is to make sure it has stillSearching = false; // wrapped around at least one time and } // if it did and landed on first index value again, just stop the search. else { ++j; indexValue = &amp;ht[hashValue(value, j)]; } } return (*indexValue == value); } int* HashTable::searchKey(int value, int j) const { int *indexValue = &amp;ht[hashValue(value, j)]; int *firstIndexValue = indexValue; bool stillSearching = true; while (stillSearching) { if (*indexValue == value || *indexValue == -1 || (indexValue == firstIndexValue &amp;&amp; j != 0)) { // The third or condition is to make sure it has stillSearching = false; // wrapped around at least one time and } // if it did and landed on first index value again, just stop the search. else { ++j; indexValue = &amp;ht[hashValue(value, j)]; } } if (*indexValue != value) { return nullptr; } return indexValue; } HashTable&amp; HashTable::operator=(const HashTable&amp; otherTable) { // Avoid self-assignment by checking that the // parameter passed is not the calling object: if (&amp;otherTable != this) { // If the array we are passing has a different // capacity from the calling object, // then we need to create a new array: if (capacity != otherTable.capacity) { // Deallocate the memory used by // the calling object and // re-create the object so that // it has the same capacity: delete[] ht; ht = new int[otherTable.capacity]; // Update capacity: capacity = otherTable.capacity; } // Update number of elements: numOfItems = otherTable.numOfItems; // Start copying: for (int i = 0; i &lt; numOfItems; ++i) ht[i] = otherTable.ht[i]; } else { cerr &lt;&lt; "Attempted assignment to itself."; } return (*this); } HashTable&amp; HashTable::operator=(HashTable&amp;&amp; otherTable) { if (this != &amp;otherTable) { delete[] ht; ht = move(otherTable.ht); capacity = move(otherTable.capacity); numOfItems = move(otherTable.numOfItems); otherTable.ht = nullptr; otherTable.capacity = move(0); otherTable.numOfItems = move(0); } return (*this); } HashTable::~HashTable() { delete[] ht; ht = nullptr; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T01:06:44.013", "Id": "394377", "Score": "0", "body": "Who told you that the hashtable was an outdated concept? It's one of the two most common approaches to implementing a mapping type and many think it has significant performance b...
[ { "body": "<h1>Don't use <code>using</code> in your headers</h1>\n<p>Everyone who uses the header will have <em>the entire contents of the <code>std</code> namespace</em> copied into the global namespace <em>whether they want them or not</em>. It's not what I expect when I write <code>#include &quot;hashtable....
{ "AcceptedAnswerId": "204520", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T00:38:40.950", "Id": "204498", "Score": "4", "Tags": [ "c++", "performance", "hash-map" ], "Title": "Hash table, using special values to mark empty and deleted indexes" }
204498
<p>I have this script that pulls text out of .docx, .doc and .pdf files and uploads that text to an Azure SQL Server. This is so users can search on the contents of those documents without using Windows Search / Azure Search.</p> <p>The filenames are all in the following format:</p> <p><strong>firstname surname - id.extension</strong></p> <p>The id is incorrect though, the ID is from an outdated database and the new database that I am updating holds both (newID and oldID).</p> <p><strong>COLUMNS:</strong></p> <ul> <li>ID - New ID of the candidate record</li> <li>OldID - Old ID of the candidate record (old database schema)</li> <li>OriginalResumeID - Document link ID for the candidate table to the document table</li> <li>CachedText - The field I am updating (holds the document text) at the moment this will mostly be NULL</li> </ul> <p>Here is the script:</p> <pre><code>## Get resume list $params = @{ 'Database' = $TRIS5DATABASENAME 'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName) 'Username' = $AdminLogin 'Password' = $InsecurePassword 'query' = "SELECT id, OldID, OriginalResumeID FROM Candidate WHERE OriginalResumeID IS NOT NULL" } $IDCheck = Invoke-Sqlcmd @params ## Word object $files = Get-ChildItem -force -recurse $documentFolder -include *.doc, *.pdf, *.docx $word = New-Object -ComObject word.application $word.Visible = $false $saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatText") foreach ($file in $files) { Write-Output "Processing: $($file.FullName)" $doc = $word.Documents.Open($file.FullName) $fileName = $file.BaseName + '.txt' $doc.SaveAs("$env:TEMP<span class="math-container">\$fileName", [ref]$saveFormat) Write-Output "File saved as $env:TEMP\$</span>fileName" $doc.Close() $4ID = $fileName.split('-')[1].replace(' ', '').replace(".txt", "") $text = Get-Content "$env:TEMP\$fileName" $text = $text.replace("'", "''") $resumeID = $IDCheck | where {$_.OldID -eq $4id} | Select-Object OriginalResumeID $resumeID = $resumeID.OriginalResumeID &lt;# Upload to azure #&gt; $params = @{ 'Database' = $TRIS5DATABASENAME 'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName) 'Username' = $AdminLogin 'Password' = $InsecurePassword 'query' = "Update Document SET CachedText = '$text' WHERE id = $ResumeID" } Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue" Remove-Item -Force "$env:TEMP\$fileName" } $word.Quit() </code></pre> <p>The problem is that running this on a large dataset, let's say 750000 documents takes far too long per document. I'm fairly certain that this is because it has to search through the entire $IDCheck object of 750000 records before it can get the originalResumeID of the record to upload to.</p> <p>Running this on a smaller database is quite quick (around 200000 per 24 hours). I was thinking I could check the documents table and only pull rows where the CachedText field is null and loop that to run every 50000 documents so it would get quicker as it goes. Problem is the documents table will be massive and will take a long time to search through every time this is called. </p> <p>Any help on speeding this up would be much appreciated.</p> <p><strong>EDIT:</strong></p> <p>Looks like it is the upload to azure causing the delay:</p> <pre><code>&lt;# Upload to azure #&gt; $params = @{ 'Database' = $TRIS5DATABASENAME 'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName) 'Username' = $AdminLogin 'Password' = $InsecurePassword 'query' = "Update Document SET CachedText = '$text' WHERE id = $ResumeID" } Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T07:02:40.570", "Id": "394548", "Score": "0", "body": "Your `Get-Content` is super slow too. Use `-raw` parameter to get the text as a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T01:21:17.6...
[ { "body": "<p>I would try to use bulkcopy to load all of the IDs and their CachedText at once into a staging table in Azure, and then do a single update on your <code>document</code> table. </p>\n\n<pre><code> CREATE TABLE document\n(docKey BIGINT IDENTITY(1, 1) PRIMARY KEY, \n CachedText NVARCHAR(MAX), \n ...
{ "AcceptedAnswerId": "212359", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T05:19:26.337", "Id": "204506", "Score": "1", "Tags": [ "time-limit-exceeded", "powershell", "pdf", "ms-word", "azure" ], "Title": "Text extraction of document files" }
204506
<p>I have implemented smallest job first algorithm using javascript. It was part of a coding challenge. I would like to ask for evaluation of my script. I would like to get suggestions to improve my code performance. Which parts of the code I can improve. Is there an alternative to for loops? </p> <p>Function takes jobs array with transaction time and index. Returns the clock cycles of the process/job at specific index. Function Call with sample input, <code>sjf([10, 3, 15, 8, 7], 3)</code>.</p> <p>Here is the code. </p> <pre><code>function sjf(jobs, index) { // declare waiting time array var waitingTime = []; // set waiting time for first task to zero waitingTime[0] = 0; // declare total time array var totalTimeArray = []; var processArray = []; // add job value and index as an object to process array for (i=0; i &lt; jobs.length; i++) { processArray.push({ id: i, value: jobs[i] }) } // sort the array in ascending order function sortArray(a, b) { return a.value - b.value; } // calculate waiting time for each process except first process // waiting time for first process is zero so we start to calculate from index 1 function calculateWaitingTime(sortedArray, waitingTime) { for (i=1; i &lt; sortedArray.length; i++) { waitingTime.push(sortedArray[i-1].value + waitingTime[i-1]); } } // total time taken to complete each task function calculateTimeForEachTask(sortedArray, totalTimeArray) { for (i=0; i &lt; sortedArray.length; i++) { totalTimeArray.push({ id: sortedArray[i].id, time: sortedArray[i].value + waitingTime[i] }); } } // find clock cycles function findClockCycles(totalTimeArray, index) { for (i = 0; i &lt; totalTimeArray.length; i++) { if (totalTimeArray[i].id === index) { return totalTimeArray[i].time; } } } // First of all sort the process array in ascending order of their value var sortedArray = processArray.sort(sortArray); // calculate waiting time for the rest of the processes calculateWaitingTime(sortedArray, waitingTime); // calculate total time for each task calculateTimeForEachTask(sortedArray, totalTimeArray); // return clock cycles for the task return findClockCycles(totalTimeArray, index); } </code></pre>
[]
[ { "body": "<p>I think this can be done with far less code. Like this:</p>\n\n<pre><code>function calculateTotalClockCycles(jobs, index) {\n jobs.sort((a, b) =&gt; a - b);\n return jobs.slice(0, index).reduce((a, b) =&gt; a + b, 0);\n}\n\nalert(calculateTotalClockCycles([10, 3, 15, 8, 7], 3));\n</code></pre>\n...
{ "AcceptedAnswerId": "204514", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T05:31:03.393", "Id": "204507", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge" ], "Title": "Smallest job first algorithm implementation" }
204507
<p>I'm using <code>log4net</code> in my application and have a static <code>Log</code> class which creates an instance of <code>ILog</code> with a default log type, e.g <code>CMS</code>. The <code>ILog</code> instance is then used by the class to call the <code>log4net</code> logging methods passing in a <code>LogItem</code> type as the log message to enforce a strict logging format.</p> <p>The user of the class can also change the logger targeted by the logger at runtime by setting a public static property <code>LogType</code> for example: <code>Log.LogType = Enums.LogType.Database</code>.</p> <p>Here is the class:</p> <pre><code>/// &lt;summary&gt; /// Log wrapper around ILog - enforces consistent log format. /// &lt;/summary&gt; public static class Log { private static ILog Logger = LogManager.GetLogger(LogType.CMS.ToString()); /// &lt;summary&gt; /// Sets the Logger to be used. /// &lt;/summary&gt; public static LogType LogType { set { Logger = LogManager.GetLogger(value.ToString()); } } /// &lt;summary&gt; /// Logs information to the system. /// &lt;/summary&gt; /// &lt;param name="source"&gt;Source of the info.&lt;/param&gt; /// &lt;param name="description"&gt;Info description.&lt;/param&gt; /// &lt;param name="exc"&gt;Associated Exception object.&lt;/param&gt; public static void Info(string source, string description, Exception exc = null) { Logger.Info(new LogItem() { Source = source, Description = description }, exc); } /// &lt;summary&gt; /// Logs a warning to the system. /// &lt;/summary&gt; /// &lt;param name="source"&gt;Source of the info.&lt;/param&gt; /// &lt;param name="description"&gt;Info description.&lt;/param&gt; /// &lt;param name="exc"&gt;Associated Exception object.&lt;/param&gt; public static void Warn(string source, string description, Exception exc = null) { Logger.Warn(new LogItem() { Source = source, Description = description }, exc); } /// &lt;summary&gt; /// Logs an error to the system. /// &lt;/summary&gt; /// &lt;param name="source"&gt;Source of the info.&lt;/param&gt; /// &lt;param name="description"&gt;Info description.&lt;/param&gt; /// &lt;param name="exc"&gt;Associated Exception object.&lt;/param&gt; public static void Error(string source, string description, Exception exc) { Logger.Error(new LogItem() { Source = source, Description = description }, exc); } } </code></pre> <p>I'm concerned on whether the <code>LogType</code> prop would be thread safe, what would happen if this is changed by another class before the logger does its job?</p> <p>I've read that <code>log4net</code> itself is thread safe and will block when calling the appenders - would having a single static class that everything logs through eventually cause a bottleneck?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T09:06:08.627", "Id": "394430", "Score": "0", "body": "_enforces consistent log format_ - not really, it just provides three APIs but it doesn't enforce actually anything because anyone could use `LogManager.GetLogger(...);` anywhere...
[ { "body": "<p>This is not thread safe, just because the <code>LogType</code> static property. The basic problem of such design is that any log operation while setting the log type requires <em>two calls</em> and changes in global state. Imagine how an hypothetical client code would look like:</p>\n\n<pre><code>...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T08:34:16.937", "Id": "204516", "Score": "1", "Tags": [ "c#", "thread-safety", "logging", "static", "log4net" ], "Title": "Static wrapper class for log4net Logging - thread safety" }
204516
<p>I have created this function for Delphi 10.1 Berlin to validate an email address entered by the user:</p> <pre><code>function IsValidEmailAddress(const AString: string): Boolean; begin Result := System.RegularExpressions.TRegEx.IsMatch(AString, '^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\Z$', [roIgnoreCase]); end; </code></pre> <p>Usage:</p> <pre><code>if not IsValidEmailAddress(Trim(edtEmail.Text)) then ... </code></pre> <p>Are there any valid email addresses which could be detected as invalid with this function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T09:24:25.377", "Id": "394438", "Score": "1", "body": "https://www.mailboxvalidator.com/resources/articles/acceptable-email-address-syntax-rfc/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T10:45:45....
[ { "body": "<p>I think there are some emails that will be invalid with your function.\nLike this:\n<code>thisissanPrivateMail@example.wolterskluwer</code>\n(when a domain name is more than 6 symbols). </p>\n\n<p>About email address length, according to <a href=\"https://www.lifewire.com/is-email-address-length-l...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T09:04:07.593", "Id": "204517", "Score": "0", "Tags": [ "regex", "delphi" ], "Title": "IsValidEmailAddress" }
204517
<p>I've written a script in python to parse different <code>names</code> ,<code>bubbles</code> and <code>reviews</code> of various restaurant names from tripadvisor and finally store them in a table named <code>webdata</code> in a database. There are two <code>functions</code> within my script: one for storing the scraped data in <code>MySQL</code> and the other for printing the same in the console. The scraper is doing its job just flawless. As this is my first ever try to store items in a database and print the already stored items in the console, I might not have been able to follow the rules of <code>DRY</code>.</p> <p>I will vastly appreciate any modification I should pursue to make the script robust.</p> <p>This is my attempt so far:</p> <pre><code>import mysql.connector from bs4 import BeautifulSoup import requests URL = "https://www.tripadvisor.com.au/Restaurants-g255068-c8-Brisbane_Brisbane_Region_Queensland.html" def store_info(link): mydb = mysql.connector.connect( host="localhost", user="root", passwd = "test123", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("DROP TABLE webdata") #kick out the table if it already exists mycursor.execute("CREATE TABLE webdata (name VARCHAR(255), bubble VARCHAR(255), review VARCHAR(255))") response = requests.get(link) soup = BeautifulSoup(response.text,"lxml") for items in soup.find_all(class_="shortSellDetails"): name = items.find(class_="property_title").get_text(strip=True) bubble = items.find(class_="ui_bubble_rating").get("alt") review = items.find(class_="reviewCount").get_text(strip=True) mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES (%s,%s,%s)",(name,bubble,review)) mydb.commit() def get_data(): mydb = mysql.connector.connect( host="localhost", user="root", passwd = "test123", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM webdata") for item in mycursor.fetchall(): print(item) mydb.close() if __name__ == '__main__': store_info(URL) get_data() #retrieve the data from that table </code></pre>
[]
[ { "body": "<ul>\n<li>The database setup <code>mydb</code> should be in it's own function, or even just\na global since this script is rather minimal. There's no reason to\nduplicate this code.</li>\n<li>If <code>mysql.connector</code> doesn't, I'd look for a database connector that\nsupports the <code>with ......
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T09:56:29.727", "Id": "204521", "Score": "2", "Tags": [ "python", "python-3.x", "mysql", "web-scraping" ], "Title": "Scrape data from a webpage and store them in a database" }
204521
<p>I would really appreciate if someone could take a look at this code. I am not very advanced, so ANY kind of feedback and critique would be precious to me.</p> <p>What this program is supposed to do is to go to a given URL, download the list of cities, for which it will download the data, based on a <a href="https://openweathermap.org/api" rel="noreferrer">https://openweathermap.org/api</a> . It should be run on a regular basis and write all of the results to the CSV file.</p> <p>It is divided into two parts. The first one consists only of the scheduler, final function which is being run by it and the list of columns I want to get as the final result.</p> <p>Code is written for Python 3.6.</p> <pre><code>from API.helpers import get_weather_data, json_to_df, create_dict import schedule, time URL = 'https://pm1aapplicantsdata.blob.core.windows.net/databases/CitiesWeather/CitiesWeather.csv' columns = ["name","sys.country","main.temp", "main.humidity","main.pressure", "visibility", "wind.speed"] #Writing results to CSV def weather_api(URL): dict = create_dict(URL) for city, code in dict.items(): data = get_weather_data(city, code) json_to_df(data, columns) schedule.every().day.at("10:30").do(weather_api, URL) while True: schedule.run_pending() time.sleep(1) </code></pre> <p>Here is the second part, which is my "helper" file.</p> <pre><code>import json import requests from pandas.io.json import json_normalize import pandas as pd import os import requests import csv api_key = "xxxxxxxxxxxxxxxxxxxxxxx" #function to build api requests def build_request(city, code): base_url = "http://api.openweathermap.org/data/2.5/weather?" complete_url = base_url + "appid=" + api_key + "&amp;q=" + city +"," + code return complete_url #function to get weather data def get_weather_data(city, code): url = build_request(city, code) try: response = requests.get(url) response.status_code except requests.exceptions.HTTPError: print('Error occured while downloading data') except requests.exceptions.URLError: print('Error occured while downloading data') citydataJSON = response.text citydata = json.loads(citydataJSON) return citydata def json_to_df(data, columns): df = pd.DataFrame.from_dict(json_normalize(data), orient='columns') new_df = df[columns] new_df.insert(0, 'TimeStamp', pd.datetime.now().replace(microsecond=0)) if not os.path.isfile('weather.csv'): return new_df.to_csv('weather.csv', header='column_names', index=False) else: return new_df.to_csv('weather.csv', mode='a', header=False, index=False) #creating a dictionary of cities and city codes(based on the CSV file downloaded from a given URL def create_dict(URL): with requests.Session() as s: dict = {} download = s.get(URL) decoded_content = download.content.decode('utf-8') cs = csv.reader(decoded_content.splitlines(), delimiter=',') next(cs, None) my_list = list(cs) for row in my_list: dict[row[0]] = row[1] return dict </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T11:45:16.127", "Id": "394447", "Score": "0", "body": "What Python version did you write this for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T15:13:54.380", "Id": "394470", "Score": "1", ...
[ { "body": "<p>Your code is very nicely split into functions. As a next step I would split it to classes. What you want to do is </p>\n\n<ol>\n<li>Collect the data for a given city</li>\n<li>Convert it into a schema that fits your purposes and write it to a file</li>\n</ol>\n\n<p>In my opinion, the scheduling of...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T11:00:08.173", "Id": "204524", "Score": "8", "Tags": [ "python", "python-3.x", "csv" ], "Title": "Getting current weather data using OpenWeatherMap API" }
204524
<p>I want to model a object of air, the temperature of which can be given in 3 different ways:</p> <ol> <li>if the value is known (assuming the temperature is a constant)</li> <li>if a curve of the values with different time is known (using interpolation)</li> <li>if the formula of the temperature vs time is known.</li> </ol> <p>My code is below:</p> <pre><code>from script.interpolate import interp1d from importlib import import_module class Air1: # case 1: temperature, which is a constant value, is given in the input. def __init__(self, meta: dict): self.city = meta['city'] self.temperature = meta['temperature'] class Air2(Air1): # case 2: a curve of temperature vs time is given in meta. # times is a list, temperatures is a list. # so self.get_temperature is an interpolated function. # To get a new temperature, I can use new_temp = self.get_temperature(new_time) def __init__(self, meta: dict): super().__init__(meta=meta) times = meta['times'] temperatures = meta['temperatures'] self.get_temperature = interp1d(times, temperatures) class Air3(Air1): # case 3: the formula to calculate temperature from time is known. # this formula is implemented in a python file called file_of_fomurla. # so self.get_temperature is an imported function. # To get a new temperature, I can use new_temp = self.get_temperature(new_time) def __init__(self, meta: dict): super().__init__(meta=meta) file_of_formula = meta['file_of_formula'] self.get_temperature = import_module(file_of_formula + '.my_function') </code></pre> <p>One thing I have noticed in my code is that <code>.temperature</code> should only be in <code>Air1</code>, since <code>Air2</code> and <code>Air3</code> both just have a function to calculate temperature value based on time. However, like in my code, <code>Air2</code> and <code>Air3</code> are sub classes of <code>Air1</code>, but their input <code>meta</code> will not have the key 'temperature'. So this is an error.</p> <p>Do you have any better way to implement the physics behind into the model. Maybe using some abstract class?</p>
[]
[ { "body": "<p>As you yourself have noted, the inheritance isn't benefiting you at all. Just write one class.</p>\n\n<p>Passing <code>meta</code> as a <code>dict</code> is unidiomatic. Use <code>**kwargs</code> or parameters with defaults instead.</p>\n\n<p>Consider <a href=\"https://stackoverflow.com/a/6618176/...
{ "AcceptedAnswerId": "204532", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T13:22:12.207", "Id": "204531", "Score": "3", "Tags": [ "python", "python-3.x", "inheritance" ], "Title": "Build object with different input, using super-class and sub-class style, Python 3" }
204531
<p>I've been doing some Codility challenges lately and the <a href="https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/" rel="nofollow noreferrer">MaxCounters challenge</a> got me stumped:</p> <blockquote> <p>You are given N counters, initially set to 0, and you have two possible operations on them:</p> <ul> <li><em>increase(X)</em> — counter X is increased by 1,</li> <li><em>max counter</em> — all counters are set to the maximum value of any counter. </li> </ul> <p>A non-empty array A of M integers is given. This array represents consecutive operations:</p> <ul> <li>if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X), </li> <li>if A[K] = N + 1 then operation K is max counter.</li> </ul> <p>[...] The goal is to calculate the value of every counter after all operations. </p> </blockquote> <p>Below is my solution in Python. I can't reach 100% on it even though I am pretty confident it is an O(n+m) complexity solution. Codility fails it and says its an O(n*m) complexity solution.</p> <pre><code>def solution(N, A): counter = [0] * N max_val = 0 for v in A: if v &lt;= N and v &gt;= 1: if counter[v-1] &lt; max_val+1: counter[v-1] = max_val+1 else: counter[v-1] += 1 else: max_val = max(counter) for i in range(len(counter)): if counter[i] &lt; max_val: counter[i] = max_val return counter </code></pre>
[]
[ { "body": "<p>A couple of hints, to avoid spoiling the problem.</p>\n\n<p>Hint 1</p>\n\n<blockquote class=\"spoiler\">\n <p> What would happen if every entry in <code>A</code> were <code>N + 1</code>?</p>\n</blockquote>\n\n<p>Hint 2</p>\n\n<blockquote class=\"spoiler\">\n <p> What is the complexity of <code>m...
{ "AcceptedAnswerId": "204537", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T14:41:44.223", "Id": "204534", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "MaxCounters Codility Challenge" }
204534
<p>I have a 2d array of <strong>m * n</strong> dimension (m and n can vary from 1 to 100000). The following snippet of code checks if the sequence exists in the row and stores the index if it exists. <strong>The time taken by the following code on 10000*10000 matrix is 650 milliseconds. The sequential version of the code also takes the same time.</strong> </p> <p><strong>This on Intel Core i7-7560U CPU @ 2.40GHz × 4</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;future&gt; std::vector&lt;int&gt; lps; void ComputeLPSArray(std::vector&lt;int&gt; const &amp;pattern) { std::vector&lt;int&gt; lps(pattern.size()); int len = 0; lps[0] = 0; int i = 1; while (i &lt; (int) pattern.size()) { if (pattern[i] == pattern[len]) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } } int SearchPattern(std::vector&lt;int&gt; const &amp;pattern, std::vector&lt;int&gt; const &amp;row) { auto M = (int) pattern.size(); auto N = (int) row.size(); int i = 0; int j = 0; while (i &lt; N) { if (pattern[j] == row[i]) { j++; i++; } if (j == M) { return 1; } else if (i &lt; N &amp;&amp; pattern[j] != row[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } return -1; } std::vector&lt;int&gt; SearchSequence(std::vector&lt;std::vector&lt;int&gt;&gt; const &amp;matrix, std::vector&lt;int&gt; const &amp;sequence) { ComputeLPSArray(sequence); std::vector&lt;int&gt; result(matrix.size()); unsigned int length = 0; std::vector&lt;std::future&lt;int&gt;&gt; f(matrix.size()); for (unsigned int i = 0; i &lt; matrix.size(); i++) { std::vector&lt;int&gt; row = matrix[i]; f[i] = async(std::launch::async, [sequence, row] { return SearchPattern(sequence, row); }); } for (unsigned int i = 0; i &lt; f.size(); ++i) { if (f[i].get() == 1) result[length++] = i; } result.resize(length); return result; } int main() { int m = 25, n = 20; // assume `m` and `n` can vary. std::vector&lt;std::vector&lt;int &gt;&gt; matrix(m, std::vector&lt;int&gt;(n)); for (int i = 0; i &lt; m; ++i) { for (int j = 0; j &lt; n; ++j) { matrix[i][j] = rand() % 1000; } } std::vector&lt;int&gt; sequence = matrix[24]; // This is purely for testing purpose, actual input(matrix&amp;sequence) is read from files. std::vector&lt;int&gt; result; result = SearchSequence(matrix, sequence); // This is the ONLY function which needs to be optimised. return 0; } </code></pre> <p><strong>How do I speed up the search time in this scenario?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T15:13:00.083", "Id": "394469", "Score": "0", "body": "what does the matrix store? any int up to about 2^32?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T15:19:02.440", "Id": "394472", "Scor...
[ { "body": "<p>I rewrote your <code>SearchSequence</code> function to be as absolutely brain-dead as possible:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;chrono&gt;\n\nstd::vector&lt;int&gt; SearchSequence(std::vector&lt;std::vector&lt;int&gt;&g...
{ "AcceptedAnswerId": null, "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T14:54:58.773", "Id": "204536", "Score": "3", "Tags": [ "c++", "performance", "c++11", "asynchronous", "search" ], "Title": "Search for rows in a 2D array that contain a given sequence" }
204536
<p>the question is taken from Pramp(really cool site!)<br> there is a more straight forward solution.<Br> using recursion. but I thought trying it using BFS.<Br> please review only the code of GetCheapestCost function and comment on space and time complexity <br></p> <blockquote> <p>The car manufacturer Honda holds their distribution system in the form of a tree (not necessarily binary). The root is the company itself, and every node in the tree represents a car distributor that receives cars from the parent node and ships them to its children nodes. The leaf nodes are car dealerships that sell cars direct to consumers. In addition, every node holds an integer that is the cost of shipping a car to it.</p> <p>Take for example the tree below:</p> <pre><code> 0 / | \ 5 3 6 / / \ / \ 4 2 0 1 5 / / 1 10 \ 1 </code></pre> <p>A path from Honda’s factory to a car dealership, which is a path from the root to a leaf in the tree, is called a Sales Path. The cost of a Sales Path is the sum of the costs for every node in the path. For example, in the tree above one Sales Path is 0→3→0→10, and its cost is 13 (0+3+0+10).</p> <p>Honda wishes to find the minimal Sales Path cost in its distribution tree. Given a node rootNode, write a function getCheapestCost that calculates the minimal Sales Path cost in the tree.</p> <p>Implement your function in the most efficient manner and analyze its time and space complexities.</p> <p>For example:</p> <p>Given the rootNode of the tree in diagram above</p> <p>Your function would return:</p> <p>7 since it’s the minimal Sales Path cost (there are actually two Sales Paths in the tree whose cost is 7: 0→6→1 and 0→3→2→1→1)</p> </blockquote> <pre><code>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// Sales Path [TestClass] public class PrampSalesPath { [TestMethod] public void TestMethod1() { SalesNode rootNode = new SalesNode(); rootNode.children = new SalesNode[3]; rootNode.cost = 0; rootNode.children[0] = new SalesNode {cost = 5}; rootNode.children[1] = new SalesNode {cost = 3}; rootNode.children[2] = new SalesNode {cost = 6}; Assert.AreEqual(3, PrampSalesPathelper.GetCheapestCost(rootNode)); } } public class SalesNode { public int cost; public SalesNode[] children; public SalesNode parent; public SalesNode() { children = null; parent = null; } } public class PrampSalesPathelper { public static int GetCheapestCost(SalesNode rootNode) { //check root node is not null was not defined. Queue&lt;SalesNode&gt; Q = new Queue&lt;SalesNode&gt;(); Q.Enqueue(rootNode); int min = Int32.MaxValue; while (Q.Count != 0) { var tempNode = Q.Dequeue(); //this is a leaf if (tempNode.children == null) { min = Math.Min(min, tempNode.cost); } else { foreach (var node in tempNode.children) { node.cost += tempNode.cost; Q.Enqueue(node); } } } return min; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T01:07:01.077", "Id": "482026", "Score": "0", "body": "There's an O(n) time and O(1) space complexities solution: https://matheusdio.wordpress.com/2020/07/13/example-post-2/" } ]
[ { "body": "<p>Just a short answer, because I havn't the energy to type a long one.</p>\n\n<h2>Algorithm</h2>\n\n<p>This is indeed a Breadth-First-Search.</p>\n\n<p>If you can assume that the costs will never be negative (i.e. path cost grows monotonically) then in either BFS or DFS it is easy to cut short paths...
{ "AcceptedAnswerId": "204543", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T16:41:38.690", "Id": "204538", "Score": "4", "Tags": [ "c#", "programming-challenge", "tree", "interview-questions", "breadth-first-search" ], "Title": "Pramp: Sales path" }
204538
<p>I am experimenting with <code>Span&lt;&gt;</code> and <code>Memory&lt;&gt;</code> and checking how to use it for example for reading UTF8 text from a <code>NetworkStream</code> using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.read?view=netcore-2.1#System_IO_Stream_Read_System_Span_System_Byte__" rel="nofollow noreferrer"><code>Read(Span&lt;Byte&gt;)</code></a>. I created a fake method that simulates the byte read, and although this code works for the test, I am wondering if this is the right way of doing the most with these new structures in terms of efficiency and memory.</p> <pre><code>static void Main(string[] args) { Memory&lt;byte&gt; byteMemory = new byte[3]; Memory&lt;char&gt; charMemory = new char[1024]; var byteMemoryPos = 0; var byteMemoryReaded = 0; var charMemoryPos = 0; var readed = -1; var decoder = Encoding.UTF8.GetDecoder(); do { // pass the sliced part of the memory where I want to write as span readed = FakeNetworkStreamRead(byteMemory.Slice(byteMemoryPos + byteMemoryReaded).Span); Console.WriteLine($"Readed {readed} bytes"); byteMemoryReaded += readed; // pass the sliced part of the memory I want to parse, and the part // of the char buffer where I want to write decoder.Convert(byteMemory.Slice(byteMemoryPos, byteMemoryReaded).Span, charMemory.Slice(charMemoryPos).Span, false, out int bytesUsed, out int charsUsed, out bool completed); // update offsets and counts byteMemoryPos -= bytesUsed; charMemoryPos += charsUsed; byteMemoryReaded -= bytesUsed; // reset offset if nothing to read if (byteMemoryReaded == 0) byteMemoryPos = 0; } while (readed != 0); Console.WriteLine(new string(charMemory.Slice(0, charMemoryPos).Span)); } static int _position = 0; static byte[] _data = Encoding.UTF8.GetBytes("Hi this is test!!"); /// &lt;summary&gt; /// Pretends to be NetworkStream.Read, that only manages to read 5 bytes each time /// &lt;/summary&gt; /// &lt;param name="span"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; static int FakeNetworkStreamRead(Span&lt;byte&gt; span) { var pending = Math.Min(_data.Length - _position, span.Length); pending = Math.Min(pending, 5); for (int i = _position, j = 0; i &lt; _position + pending; j++, i++) { span[j] = _data[i]; } _position += pending; return pending; } </code></pre>
[]
[ { "body": "<p>I have no experience with <code>Span&lt;T&gt;</code> or <code>Memory&lt;T&gt;</code> so the following is just some general considerations on coding etc.</p>\n\n<hr>\n\n<p>In <code>FakeNetworkStreamRead(...)</code>: why have a internal limit of 5 bytes? Why not let the length of the <code>Span&lt;T...
{ "AcceptedAnswerId": "204575", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T16:57:56.633", "Id": "204539", "Score": "5", "Tags": [ "c#", "console", "stream", ".net-core" ], "Title": "Using Span<> and Memory<> to read UTF8 from a socket" }
204539
<p>To enable unit testing in the VBA IDE I'm using <a href="https://github.com/rubberduck-vba/Rubberduck" rel="nofollow noreferrer">https://github.com/rubberduck-vba/Rubberduck</a>.</p> <p>I've created a class and a custom collection class to work with structural members I need to filter. The following are specific members of the collection class and their intended use.</p> <ul> <li><code>UniqueWidths</code>: Used to obtain the unique widths of the members put into the collection.</li> <li><code>WithAWidthOf</code>: Return a subset of the contained <code>Section</code>s that are of the specified width.</li> <li><code>FirstAdded</code>: Obtain the first <code>Section</code> that was added.</li> </ul> <p>I have tried to test each member to check for unintended behavior. Are there any tests that I could be using that I've not presently thought of.</p> <p>Where it's used <code>SectionShapes.hssHollowStructuralSection</code> is a fully qualified enumeration member.</p> <pre><code>'Section class Option Explicit Private Type THelper Name As String Width As Double Weight As Double Depth As Double Shape As SectionShapes End Type Private this As THelper Public Sub Init(ByVal Name As String, ByVal Width As Double, ByVal Weight As Double, ByVal Depth As Double, ByVal Shape As SectionShapes) With this .Name = Name .Width = Width .Weight = Weight .Depth = Depth .Shape = Shape End With End Sub Public Property Get Name() As String Name = this.Name End Property Public Property Get Width() As Double Width = this.Width End Property Public Property Get Weight() As Double Weight = this.Weight End Property Public Property Let Weight(ByVal RHS As Double) 'Allows weight penalty to be applied this.Weight = RHS End Property Public Property Get Depth() As Double Depth = this.Depth End Property Public Property Get Shape() As SectionShapes Shape = this.Shape End Property </code></pre> <hr> <pre><code>'Sections collection class Option Explicit Private Type THelper dictSections As Dictionary collSections As Collection End Type Private this As THelper Private Sub Class_Initialize() Set this.collSections = New Collection Set this.dictSections = New Dictionary End Sub Public Property Get Section(ByVal value As Section) As Section Section = this.dictSections(value.Name) End Property Public Sub Add(ByVal value As Section) this.dictSections.Add value.Name, value this.collSections.Add value, value.Name End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = this.collSections.[_NewEnum] End Property Public Property Get Exists(ByVal value As Section) As Boolean Exists = this.dictSections.Exists(value.Name) End Property Public Property Get Widths() As Dictionary Set Widths = New Dictionary Dim sectionWidth As Section For Each sectionWidth In this.collSections If Not Widths.Exists(sectionWidth.Name) Then Widths.Add sectionWidth.Name, sectionWidth.Width End If Next End Property Public Property Get UniqueWidths() As Dictionary Set UniqueWidths = New Dictionary Dim checkWidth As Section For Each checkWidth In this.collSections If Not UniqueWidths.Exists(checkWidth.Width) Then UniqueWidths.Add checkWidth.Width, checkWidth.Width End If Next End Property Public Property Get Weights() As Dictionary Set Weights = New Dictionary Dim sectionWeight As Section For Each sectionWeight In this.collSections If Not Weights.Exists(sectionWeight.Weight) Then Weights.Add sectionWeight.Name, sectionWeight.Weight End If Next End Property Public Property Get FirstAdded() As Section Set FirstAdded = this.collSections.Item(1) End Property Public Property Get Count() As Long Count = this.dictSections.Count End Property Public Property Get WithAWidthOf(ByVal value As Double) As Sections Set WithAWidthOf = New Sections Dim checkSection As Section For Each checkSection In this.collSections If checkSection.Width = value Then WithAWidthOf.Add checkSection End If Next End Property </code></pre> <hr> <p>Section Tests</p> <pre><code>'@TestMethod Public Sub Name_Getter() On Error GoTo TestFail 'Arrange: Dim sut As Section Set sut = New Section sut.Init "HSS20 x 12 x 5/8", 12, 127.37, 20, SectionShapes.hssHollowStructuralSection 'Act: 'Assert: Assert.AreEqual "HSS20 x 12 x 5/8", sut.Name TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub Depth_Getter() On Error GoTo TestFail 'Arrange: Dim sut As Section Set sut = New Section sut.Init "HSS20 x 12 x 5/8", 12, 127.37, 20, SectionShapes.hssHollowStructuralSection 'Act: 'Assert: Assert.AreEqual CDbl(20), sut.Depth TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub Weight_Getter() On Error GoTo TestFail 'Arrange: Dim sut As Section Set sut = New Section sut.Init "HSS20 x 12 x 5/8", 12, 127.37, 20, SectionShapes.hssHollowStructuralSection 'Act: 'Assert: Assert.AreEqual 127.37, sut.Weight TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub Width_Getter() On Error GoTo TestFail 'Arrange: Dim sut As Section Set sut = New Section sut.Init "HSS20 x 12 x 5/8", 12, 127.37, 20, SectionShapes.hssHollowStructuralSection 'Act: 'Assert: Assert.AreEqual CDbl(12), sut.Width TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub Shape_Getter() On Error GoTo TestFail 'Arrange: Dim sut As Section Set sut = New Section sut.Init "HSS20 x 12 x 5/8", 12, 127.37, 20, SectionShapes.hssHollowStructuralSection 'Act: 'Assert: Assert.AreEqual SectionShapes.hssHollowStructuralSection, sut.Shape TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub </code></pre> <hr> <p>Sections collection tests</p> <pre><code>'@TestMethod Public Sub Count() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width7second sut.Add width7third sut.Add width8 'Act: 'Assert: Assert.AreEqual CLng(4), sut.Count TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub UniqueWidths_Count() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width7second sut.Add width7third sut.Add width8 'Act: 'Assert: Assert.AreEqual CLng(2), sut.UniqueWidths.Count TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub FirstAdded_IsFirstAdded() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim FirstAdded As Section Set FirstAdded = New Section FirstAdded.Init "HSS12 x 12 x 5/8", 12, 93.34, 12, SectionShapes.hssHollowStructuralSection Dim secondAdded As Section Set secondAdded = New Section secondAdded.Init "HSS14 x 10 x 5/16", 10, 48.86, 14, SectionShapes.hssHollowStructuralSection sut.Add FirstAdded sut.Add secondAdded 'Act: 'Assert: Assert.AreSame FirstAdded, sut.FirstAdded TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub FirstAdded_IsNotFirstAdded() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim FirstAdded As Section Set FirstAdded = New Section FirstAdded.Init "HSS12 x 12 x 5/8", 12, 93.34, 12, SectionShapes.hssHollowStructuralSection Dim secondAdded As Section Set secondAdded = New Section secondAdded.Init "HSS14 x 10 x 5/16", 10, 48.86, 14, SectionShapes.hssHollowStructuralSection sut.Add FirstAdded sut.Add secondAdded 'Act: 'Assert: Assert.AreNotSame secondAdded, sut.FirstAdded TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub WithAWithOf_ResultsMatch() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third 'Act: 'Assert: Assert.AreEqual CLng(3), sut.WithAWidthOf(CDbl(7)).Count TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub WithAWithOf_ReturnsNoResults() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third 'Act: 'Assert: Assert.AreEqual CLng(0), sut.WithAWidthOf(CDbl(0)).Count TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub Weights_Items() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third 'Act: 'Assert: Assert.SequenceEquals Array(19.63, 76.07, 32.58, 59.32), sut.Weights.Items TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub Weights_Keys() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third 'Act: 'Assert: Assert.SequenceEquals Array("HSS9 x 7 x 3/16", _ "A1085-HSS16 x 8 x 1/2", _ "HSS7 x 7 x 3/8", _ "A1085-HSS9 x 7 x 5/8"), sut.Weights.Keys TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub DoesExist() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third 'Act: 'Assert: Assert.IsTrue sut.Exists(width7second) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub '@TestMethod Public Sub DoesNotExist() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third Dim notFound As Section Set notFound = New Section notFound.Init "nope", 0, 0, 0, SectionShapes.hssHollowStructuralSection 'Act: 'Assert: Assert.IsFalse sut.Exists(notFound) TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub Public Sub IteratorSucceeds() On Error GoTo TestFail 'Arrange: Dim sut As Sections Set sut = New Sections Dim width7first As Section Set width7first = New Section width7first.Init "HSS9 x 7 x 3/16", 7, 19.63, 9, SectionShapes.hssHollowStructuralSection Dim width7second As Section Set width7second = New Section width7second.Init "HSS7 x 7 x 3/8", 7, 32.58, 7, SectionShapes.hssHollowStructuralSection Dim width7third As Section Set width7third = New Section width7third.Init "A1085-HSS9 x 7 x 5/8", 7, 59.32, 9, SectionShapes.hssHollowStructuralSection Dim width8 As Section Set width8 = New Section width8.Init "A1085-HSS16 x 8 x 1/2", 8, 76.07, 16, SectionShapes.hssHollowStructuralSection sut.Add width7first sut.Add width8 sut.Add width7second sut.Add width7third Dim checkSection As Section For Each checkSection In sut Debug.Print checkSection.Name Next 'Act: 'Assert: Assert.Succeed TestExit: Exit Sub TestFail: Assert.Fail "Test raised an error: #" &amp; Err.Number &amp; " - " &amp; Err.Description End Sub </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T18:01:09.860", "Id": "204542", "Score": "3", "Tags": [ "vba", "unit-testing", "rubberduck" ], "Title": "Unit testing a custom collection" }
204542
<p>I have a list as follows and I want to shuffle the elements that have the same frequency while keeping the elements with different frequencies in the correct positions. The code below works; however, it is not that nice. I was wondering if anyone had some suggestions e.g. using list comprehension. </p> <pre><code>pieces_needed = [('a',1),('b',1),('d',1),('c',2),('g',3),('f',5),('z',5)] temp = [] new_pieces_needed = [] current_freq = 1 for i in pieces_needed: if i[1] == current_freq: temp.append(i) else: random.shuffle(temp) new_pieces_needed += temp temp = [] temp.append(i) current_freq = i[1] random.shuffle(temp) new_pieces_needed += temp print(new_pieces_needed) </code></pre> <p>Example output:</p> <pre><code>[('d',1),('b',1),('a',1),('c',2),('g',3),('z',5),('f',5)] </code></pre>
[]
[ { "body": "<ol>\n<li><p>Both branches of the <code>if</code> statement have the line:</p>\n\n<pre><code>temp.append(i)\n</code></pre>\n\n<p>This duplication could be avoided.</p></li>\n<li><p>The variable <code>temp</code> could have a better name, for example <code>group</code> or <code>current_group</code>.</...
{ "AcceptedAnswerId": "204572", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T19:22:14.383", "Id": "204548", "Score": "1", "Tags": [ "python", "algorithm", "shuffle" ], "Title": "Shuffling sections of an ordered list based on tuple values" }
204548
<p>I have a DataFrame that contains the data shown below:</p> <pre><code> soc [%] r0 [ohm] tau1 [s] tau2 [s] r1 [ohm] r2 [ohm] c1 [farad] c2 [farad] 0 90 0.001539 1725.035378 54.339882 0.001726 0.001614 999309.883552 33667.261120 1 80 0.001385 389.753276 69.807148 0.001314 0.001656 296728.345634 42164.808208 2 70 0.001539 492.320311 53.697439 0.001139 0.001347 432184.454388 39865.959637 3 60 0.001539 656.942558 63.233445 0.000990 0.001515 663400.436465 41727.472274 4 50 0.001539 296.080424 53.948112 0.000918 0.001535 322490.860387 35139.878909 5 40 0.001539 501.978979 72.015509 0.001361 0.001890 368919.408585 38100.665763 6 30 0.001539 585.297624 76.972464 0.001080 0.001872 542060.285388 41114.220492 7 20 0.001385 1308.176576 60.541172 0.001426 0.001799 917348.863136 33659.124096 8 10 0.001539 1194.993755 57.078336 0.002747 0.001851 435028.073957 30839.130201 </code></pre> <p>Given a value <code>z</code>, I want to select a row in the data frame where <code>soc [%]</code> is closest to <code>z</code>. The code below demonstrates my current approach.</p> <pre><code>import pandas as pd import time def rc_params(df, z): if z &gt; 90: params = df.loc[0] elif 80 &lt; z &lt;= 90: params = df.loc[0] elif 70 &lt; z &lt;= 80: params = df.loc[1] elif 60 &lt; z &lt;= 70: params = df.loc[2] elif 50 &lt; z &lt;= 60: params = df.loc[3] elif 40 &lt; z &lt;= 50: params = df.loc[4] elif 30 &lt; z &lt;= 40: params = df.loc[5] elif 20 &lt; z &lt;= 30: params = df.loc[6] elif 10 &lt; z &lt;= 20: params = df.loc[7] else: params = df.loc[8] r0 = params['r0 [ohm]'] tau1 = params['tau1 [s]'] tau2 = params['tau2 [s]'] r1 = params['r1 [ohm]'] r2 = params['r2 [ohm]'] return r0, tau1, tau2, r1, r2 start = time.time() z = 20 df = pd.read_csv('results/soc_rc.csv') r0, tau1, tau2, r1, r2 = rc_params(df, z) end = time.time() print(f""" z = {z} r0 = {r0:.4f} tau1 = {tau1:.4f} tau2 = {tau2:.4f} r1 = {r1:.4f} r2 = {r2:.4f} run time = {end - start:.4g} s """) </code></pre> <p>Results from the above code give:</p> <pre><code>z = 20 r0 = 0.0014 tau1 = 1308.1766 tau2 = 60.5412 r1 = 0.0014 r2 = 0.0018 run time = 0.002264 s </code></pre> <p>My approach works fine but is there a better (faster) way to lookup the values in the data frame? There is a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html?highlight=lookup#pandas.DataFrame.lookup" rel="nofollow noreferrer"><code>lookup</code></a> function in Pandas but it finds exact values, so if a value doesn't exist then nothing is returned.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T14:49:33.940", "Id": "394579", "Score": "0", "body": "`min(max(9 - round(z / 10), 0), 8)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T15:27:03.340", "Id": "394584", "Score": "0", "body...
[ { "body": "<p>Adapting from <a href=\"https://stackoverflow.com/a/43112103/7486879\">here</a> would be a cleaner way to do what you want.</p>\n\n<pre><code>params = df.iloc[(df['soc [%]']-z).abs().argsort()[:1]]\n</code></pre>\n\n<p>There might be faster ways if your <code>soc [%]</code> column is fixed with th...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T20:13:55.373", "Id": "204549", "Score": "2", "Tags": [ "python", "python-3.x", "pandas", "lookup" ], "Title": "Lookup closest value in Pandas DataFrame" }
204549
<p>I am creating a set of bots. Those bots are made to visit websites and perform certain actions automatically on the website. Different actions are available for the bots depending on the website they are visiting.</p> <p>I would like to know if there is a better version to do this since the current one is not convincing me.</p> <pre><code>class Bot { constructor (name) { this.name = name; this.browser = new Browser(); // Instance of a headless browser. this.website = null; // The current website. } visit (website) { this.website = website; } doAction (name, ...parameters) { return this.website.actions[name](this, ...parameters); } } class Website { constructor (name, url) { this.name = name; this.url = url; this.actions = {}; } addAction (name, call) { this.actions[name] = call; } } // The following is a short use case example. const bot = new Bot("bot1"); const fb = new Website("facebook", "https://www.facebook.com"); fb.addAction("login", (bot, username, password) =&gt; { bot.browser.visit("https://facebook.com/"); bot.browser.query("#username").value = username; bot.browser.query("#password").value = password; bot.browser.query("#login-form").submit(); }); bot.visit(fb); bot.doAction("login", "username", "password"); </code></pre> <p>Do you think it's simple and clear? Have you thought another way to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T21:10:03.290", "Id": "394514", "Score": "0", "body": "Welcome to CodeReview, hope you get some good reviews! I think though if you had a little bit more of a complete program you'd also get more input on how to improve it; as it is ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T20:31:33.507", "Id": "204551", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Creating a bots with different actions" }
204551
<p>This function formats a string by replacing every occurrence of '{n}' with the corresponding argument that was passed to the function where <code>n</code> is an index that starts at 0. The same index can be used multiple times and the order is irrelevant. If <code>n</code> is out of bounds or cannot be converted to an integer number I just add '{n}' to the result. The function is intended to be used e.g with config files that can be changed by the user where it would be unsafe to use <code>sprintf</code>. The use of <code>std::ostringstream</code> allows me to pass any type that has an overloaded <code>&lt;&lt;</code> operator. I was considering using iterators in the loops but I'm not sure whether that would gain anything.</p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; #include &lt;sstream&gt; #include &lt;string_view&gt; namespace util::str{ inline void to_string_vector(std::vector&lt;std::string&gt;&amp;){} //Dummy used to end recursion template&lt;typename T, typename ... Args&gt; void to_string_vector(std::vector&lt;std::string&gt;&amp; result, const T&amp; t, Args&amp;&amp; ...args){ result.push_back((std::ostringstream{} &lt;&lt; t).str()); to_string_vector(result, args...); } template&lt;typename ... Args&gt; std::string format(std::string_view fmt, Args&amp;&amp; ...args){ std::string result; std::vector&lt;std::string&gt; values; result.reserve(fmt.size()); to_string_vector(values, args...); for(std::size_t first = 0; first &lt; fmt.size(); ++first){ if(fmt[first] == '{'){ for(std::size_t second = first + 1; second &lt; fmt.size(); ++second){ if(fmt[second] == '}'){ try{ std::size_t index = std::stoi(std::string{fmt.substr(first + 1, second - first - 1)}); if(index &lt; values.size()) result += values[index]; else result += fmt.substr(first, second - first + 1); }catch(...){ result += fmt.substr(first, second - first + 1); } first = second; break; }else if(fmt[second] == '{'){ result += fmt.substr(first, second - first); first = second - 1; break; } } }else{ result.push_back(fmt[first]); } } return result; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T23:53:06.587", "Id": "394532", "Score": "0", "body": "The code could use some *prettification* (whitespaces) and you could possibly avoid creating the vector of strings by working directly with `ostream`, but it works and looks ok. ...
[ { "body": "<p>As I already said in the comments, some white space would be good to add, especially around <code>{</code> and <code>}</code>. Then I mentioned that you could possibly avoid creating the vector of strings, but well, that's not that easy:</p>\n\n<pre><code>template&lt;class... T&gt; struct pack {\n...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T21:05:10.197", "Id": "204553", "Score": "4", "Tags": [ "c++", "strings", "formatting", "template", "variadic" ], "Title": "Templated string formatting" }
204553
<p>I'm trying to come up with an "elegant" way of calculating Fibonacci for number in Rust, using recursion and memoization (self-imposed requirements).</p> <p>This is what I have so far:</p> <pre><code>fn fib(n: usize, memo: &amp;mut [Option&lt;usize&gt;]) -&gt; usize { memo[n].map(|v| v).unwrap_or_else(|| { let result = { if n &gt; 1 { fib(n - 1, memo) + fib(n - 2, memo) } else { 1 } }; memo[n] = Some(result); result }) } fn main() { let number = 46; let mut memo: Vec&lt;Option&lt;usize&gt;&gt; = vec![None; number + 1]; println!("{}", fib(number, &amp;mut memo)); } </code></pre> <p>My cache in this implementation is just a slice of optional values, if the position contains <code>Some(x)</code> that's a cache hit, otherwise, in a closure, compute the value, passing the cache along, and just before returning the value save it as a <code>Some(v)</code> in the cache.</p> <p>I figured that setting up a cache this way would make writes faster, since the memory is already allocated.</p> <p>Can it be made faster? Or cleaner/more readable?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T23:43:09.713", "Id": "394529", "Score": "1", "body": "`map()` isn't necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T23:53:11.190", "Id": "394533", "Score": "0", "body": "0 is no...
[ { "body": "<ol>\n<li>There's no reason to ascribe a type to <code>memo</code>.</li>\n<li>Don't expose the memoization logic outside the call. Instead, create a shim function that creates the memoization vector for you.</li>\n<li>You can then define the memoized function inside the shim function, preventing peop...
{ "AcceptedAnswerId": "204583", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T21:15:38.420", "Id": "204555", "Score": "9", "Tags": [ "recursion", "rust", "fibonacci-sequence", "memoization" ], "Title": "Recursive Fibonacci in Rust with memoization" }
204555
<p>Here is a link to the workbook, classes, modules and forms:</p> <p><a href="https://github.com/Evanml2030/Excel-SpaceInvader" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-SpaceInvader</a></p> <p>Positive:<br> I have decoupled the view from the control / presenter. I have implemented what I think is an MVP style design. I have refactored much of the code, making it leaner and meaner. I explored was to reduce the number of factories, but found that I to either A) create classes with "constructor" that set initial values B) store initial values in separate functions that I call from the factory method. I felt that my solution was most elegant of these.</p> <p>Negative:<br> I have two BIG issues. First, my method of scaling is not working. I am taking the Game Board dimensions and using them to set the width / length of my game pieces. Somehow my method of figuring these values is not working. </p> <p>Second I have moved from a custom collection to a dictionary as my method of storing game pieces. However as I loop through the pieces I every so often get a 424 Object Required error. This usually comes in the following line:</p> <pre><code>If CheckIfCollided(GamePiecesCollection.Item(MissileKey), GamePiecesCollection.Item(IncomingSpaceObjectKey)) Then </code></pre> <p>My handle ship incoming space objects collision function is not working at all LOL. Almost makes me want to switch back to a custom collection. But for some reason I thought that a dictionary would make condensing all of my collections, that is storing my ship, missiles and incoming space objects in the same collection, would be easier than fitting them into a custom collection.</p> <p>Here is the code. Note the gameboard form wont load without frx file, which I cannot post here: </p> <p><em>Note that I am using the Microsoft Scripting Runtime Library</em></p> <h3>GameBoard:</h3> <pre><code>VERSION 5.00 Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} GameBoard Caption = "UserForm1" ClientHeight = 9495 ClientLeft = 120 ClientTop = 465 ClientWidth = 7725 OleObjectBlob = "GameBoard.frx":0000 StartUpPosition = 1 'CenterOwner End Attribute VB_Name = "GameBoard" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub UserForm_Activate() GameLogic.RunGame Me.InsideHeight, Me.InsideWidth End Sub Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) Dim passVal As Long Select Case KeyCode.value Case 37, 39, 32 passVal = CInt(KeyCode) GameLogic.HandleSendKeys passVal End Select End Sub Public Sub RefreshGameBoard(ByVal ControlsToAdd As Scripting.Dictionary) Dim Ctrl As Image Dim SpaceObjectIndex As Variant For Each Ctrl In Me.Controls Me.Controls.remove Ctrl.Name Next Ctrl For Each SpaceObjectIndex In ControlsToAdd.Keys() Set Ctrl = Me.Controls.Add("Forms.Image.1", ControlsToAdd.Item(SpaceObjectIndex).Name, True) Ctrl.Left = ControlsToAdd.Item(SpaceObjectIndex).Left Ctrl.Top = ControlsToAdd.Item(SpaceObjectIndex).Top Ctrl.Height = ControlsToAdd.Item(SpaceObjectIndex).Height Ctrl.Width = ControlsToAdd.Item(SpaceObjectIndex).Width Ctrl.Picture = LoadPicture(LinkToImage(ControlsToAdd.Item(SpaceObjectIndex).SpaceObjectType)) Ctrl.PictureSizeMode = fmPictureSizeModeZoom Next SpaceObjectIndex End Sub Private Function LinkToImage(ByVal SpaceObjectType As SpaceObjectType) As String Select Case SpaceObjectType Case Alien LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\AlienShip.jpg" Case Comet LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Comet.jpg" Case Star LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Star.jpg" Case Missile LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Missile.jpg" Case Ship LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\SpaceShip.jpg" End Select End Function </code></pre> <h3>CheckObject:</h3> <pre><code>Attribute VB_Name = "CheckObjectType" Option Explicit Public Function IsIncomingSpaceObject(ByVal SpaceObjectOne As ISpaceObject) As Boolean If SpaceObjectOne.SpaceObjectType &lt; Missile Then IsIncomingSpaceObject = True Else IsIncomingSpaceObject = False End If End Function Public Function IsMissile(ByVal SpaceObjectTwo As ISpaceObject) As Boolean If SpaceObjectTwo.SpaceObjectType = Missile Then IsMissile = True Else IsMissile = False End If End Function </code></pre> <h3>Collisions:</h3> <pre><code> Option Explicit Function HandleMissileCollisions() As Dictionary Dim TempDict As Dictionary Dim MissileKey As Variant Dim IncomingSpaceObjectKey As Variant Set TempDict = GamePiecesCollection For Each MissileKey In GamePiecesCollection.Keys() If CheckObjectType.IsMissile(GamePiecesCollection.Item(MissileKey)) = True Then For Each IncomingSpaceObjectKey In GamePiecesCollection.Keys() If CheckObjectType.IsIncomingSpaceObject(GamePiecesCollection.Item(IncomingSpaceObjectKey)) And (IncomingSpaceObjectKey &lt;&gt; MissileKey) = True Then If CheckIfCollided(GamePiecesCollection.Item(MissileKey), GamePiecesCollection.Item(IncomingSpaceObjectKey)) Then TempDict.remove MissileKey TempDict.remove IncomingSpaceObjectKey End If End If Next IncomingSpaceObjectKey End If Next MissileKey Set GamePiecesCollection = TempDict End Function Function HandleShipCollisions() As PlayerShipHit Dim Ship As ISpaceObject Dim IncomingSpaceObjectKey As Variant Set Ship = GamePiecesCollection.Items(0) For Each IncomingSpaceObjectKey In GamePiecesCollection.Keys() If CheckObjectType.IsIncomingSpaceObject(GamePiecesCollection.Item(IncomingSpaceObjectKey)) = True Then If CheckIfCollided(Ship, GamePiecesCollection(IncomingSpaceObjectKey)) Then HandleShipCollisions = Hit Exit For End If End If Next IncomingSpaceObjectKey End Function Private Function CheckIfCollided(ByVal First As ISpaceObject, ByVal Second As ISpaceObject) As Boolean Dim HorizontalOverlap As Boolean Dim VerticalOverlap As Boolean HorizontalOverlap = (First.Left - Second.Width &lt; Second.Left) And (Second.Left &lt; First.Left + First.Width) VerticalOverlap = (First.Top - Second.Height &lt; Second.Top) And (Second.Top &lt; First.Top + First.Height) CheckIfCollided = HorizontalOverlap And VerticalOverlap End Function </code></pre> <h3>GameLogic:</h3> <pre><code>Attribute VB_Name = "GameLogic" Option Explicit Public Enum SpaceObjectType Alien = 1 Comet = 2 Star = 3 Missile = 4 Ship = 5 End Enum Public Enum PlayerShipHit Hit = 1 NotHit = 0 End Enum Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr) Public GamePiecesCollection As Scripting.Dictionary Const Interval = 3 Sub RunGame(ByVal BoardWith As Long, ByVal BoardHeight As Long) Dim SleepWatch As StopWatch Dim GenerateIncSpaceObjectsRound1 As StopWatch Set SleepWatch = New StopWatch SleepWatch.Start BoardDimensions.Width = BoardWith BoardDimensions.Height = BoardHeight Set GamePiecesCollection = New Scripting.Dictionary Set GenerateIncSpaceObjectsRound1 = New StopWatch GenerateIncSpaceObjectsRound1.Start Set SleepWatch = New StopWatch SleepWatch.Start InitializePlayerShip Do GameBoard.RefreshGameBoard GamePiecesCollection MoveSpaceObjects.MoveIncomingSpaceObjectsAndMissiles Collisions.HandleMissileCollisions Collisions.HandleShipCollisions If Format(GenerateIncSpaceObjectsRound1.Elapsed, "0.000000") &gt; 3.25 Then ReleaseIncomingSpaceObject ReleaseIncomingSpaceObject ReleaseIncomingSpaceObject GenerateIncSpaceObjectsRound1.Restart End If If Format(SleepWatch.Elapsed, "0.000000") &lt; Interval Then Sleep Interval - Format(SleepWatch.Elapsed, "0.000000") SleepWatch.Restart End If DoEvents Loop End Sub Public Sub HandleSendKeys(ByVal KeyCode As Long) Select Case KeyCode Case 37 MoveSpaceObjects.MoveShip Left Case 39 MoveSpaceObjects.MoveShip Right Case 32 LaunchMissile End Select End Sub Private Function InitializePlayerShip() Dim PlayerShip As ISpaceObject Set PlayerShip = SpaceObjectFactory.NewSpaceObject(Ship) GamePiecesCollection.Add PlayerShip.Name, PlayerShip End Function Private Function LaunchMissile() Dim LaunchedMissile As ISpaceObject CountMissiles.IncrementMissileCount Set LaunchedMissile = SpaceObjectFactory.NewSpaceObject(Missile) GamePiecesCollection.Add LaunchedMissile.Name, LaunchedMissile End Function Private Function ReleaseIncomingSpaceObject() Dim IncomingSpaceObject As ISpaceObject CountIncomingSpaceObjects.IncrementCountIncomingSpaceObjects Set IncomingSpaceObject = SpaceObjectFactory.NewSpaceObject(Application.WorksheetFunction.RandBetween(1, 3)) GamePiecesCollection.Add IncomingSpaceObject.Name, IncomingSpaceObject End Function </code></pre> <h3>MoveSpaceObjects:</h3> <pre><code>Attribute VB_Name = "MoveSpaceObjects" Option Explicit Public Enum Direction Left = 0 Right = 1 End Enum Sub MoveIncomingSpaceObjectsAndMissiles() Dim SpaceObjectIndex As Variant For Each SpaceObjectIndex In GamePiecesCollection.Keys() If CheckObjectType.IsMissile(GamePiecesCollection.Item(SpaceObjectIndex)) = True Then If GamePiecesCollection.Item(SpaceObjectIndex).Top - 1 &lt;= 0 Then GamePiecesCollection.remove SpaceObjectIndex Else GamePiecesCollection.Item(SpaceObjectIndex).Top = GamePiecesCollection.Item(SpaceObjectIndex).Top - 1 End If ElseIf CheckObjectType.IsIncomingSpaceObject(GamePiecesCollection.Item(SpaceObjectIndex)) = True Then If GamePiecesCollection.Item(SpaceObjectIndex).Top + 1 &gt;= BoardDimensions.Height Then GamePiecesCollection.remove SpaceObjectIndex Else GamePiecesCollection.Item(SpaceObjectIndex).Top = GamePiecesCollection.Item(SpaceObjectIndex).Top + 1 End If End If Next SpaceObjectIndex End Sub Sub MoveShip(ByVal MoveShipDirection As Direction) Select Case MoveShipDirection Case Direction.Left If GamePiecesCollection.Item("SHIP").Left - 4 &gt;= 0 Then GamePiecesCollection.Item("SHIP").Left = GamePiecesCollection.Item("SHIP").Left - 5 Else GamePiecesCollection.Item("SHIP").Left = 0 End If Case Direction.Right If (GamePiecesCollection.Item("SHIP").Left + GamePiecesCollection.Item("SHIP").Width) &lt; BoardDimensions.Width Then GamePiecesCollection.Item("SHIP").Left = GamePiecesCollection.Item("SHIP").Left + 4 Else GamePiecesCollection.Item("SHIP").Left = BoardDimensions.Width - GamePiecesCollection.Item("SHIP").Width End If End Select End Sub </code></pre> <h3>SpaceObjectFactory:</h3> <pre><code>Attribute VB_Name = "SpaceObjectFactory" Option Explicit Public Function NewSpaceObject(ByVal SpaceObjectType As SpaceObjectType) As SpaceObject Select Case SpaceObjectType Case Alien Set NewSpaceObject = NewSpaceObjectAlien Case Comet Set NewSpaceObject = NewSpaceObjectComet Case Missile Set NewSpaceObject = NewSpaceObjectMissile Case Ship Set NewSpaceObject = NewSpaceObjectShip Case Star Set NewSpaceObject = NewSpaceObjectStar End Select End Function Private Function NewSpaceObjectAlien() As SpaceObject CountIncomingSpaceObjects.IncrementCountIncomingSpaceObjects With New SpaceObject .SetInitialLeft Application.WorksheetFunction.RandBetween(1, BoardDimensions.Width) .SetInitialTop 1 .Height = BoardDimensions.Width / 10 .Width = BoardDimensions.Width / 10 .SpaceObjectType = Alien .Name = "INCSPACEOBJECT" &amp; CountIncomingSpaceObjects.Count Set NewSpaceObjectAlien = .Self End With End Function Private Function NewSpaceObjectComet() As SpaceObject CountIncomingSpaceObjects.IncrementCountIncomingSpaceObjects With New SpaceObject .SetInitialLeft Application.WorksheetFunction.RandBetween(1, BoardDimensions.Width) .SetInitialTop 1 .Height = BoardDimensions.Height / 7 .Width = BoardDimensions.Height / 7 .SpaceObjectType = Comet .Name = "INCSPACEOBJECT" &amp; CountIncomingSpaceObjects.Count Set NewSpaceObjectComet = .Self End With End Function Private Function NewSpaceObjectMissile() As SpaceObject CountMissiles.IncrementMissileCount With New SpaceObject .SetInitialLeft ((GamePiecesCollection.Item("SHIP").Width - (BoardDimensions.Width / 20)) / 2) + GamePiecesCollection.Item("SHIP").Left .SetInitialTop GamePiecesCollection.Item("SHIP").Top - BoardDimensions.Height / 15 .Height = BoardDimensions.Height / 15 .Width = BoardDimensions.Width / 20 .SpaceObjectType = Missile .Name = "MISSILE" &amp; CountMissiles.Count Set NewSpaceObjectMissile = .Self End With End Function Private Function NewSpaceObjectShip() As SpaceObject With New SpaceObject .SetInitialLeft BoardDimensions.Width / 2 - ((BoardDimensions.Height / 7) / 2) .SetInitialTop BoardDimensions.Height - ((BoardDimensions.Height / 7) * 1.25) .Height = BoardDimensions.Height / 7 .Width = BoardDimensions.Width / 7 .SpaceObjectType = Ship .Name = "SHIP" Set NewSpaceObjectShip = .Self End With End Function Private Function NewSpaceObjectStar() As SpaceObject CountIncomingSpaceObjects.IncrementCountIncomingSpaceObjects With New SpaceObject .SetInitialLeft Application.WorksheetFunction.RandBetween(1, BoardDimensions.Width) .SetInitialTop 1 .Height = BoardDimensions.Height / 5 .Width = BoardDimensions.Height / 5 .SpaceObjectType = Star .Name = "INCSPACEOBJECT" &amp; CountIncomingSpaceObjects.Count Set NewSpaceObjectStar = .Self End With End Function </code></pre> <h3>BoardDimensions:</h3> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "BoardDimensions" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private Type BoardDimensionsData Width As Long Height As Long End Type Private this As BoardDimensionsData Public Property Let Width(ByVal Width As Long) this.Width = Width End Property Public Property Get Width() As Long Width = this.Width End Property Public Property Let Height(ByVal Height As Long) this.Height = Height End Property Public Property Get Height() As Long Height = this.Height End Property </code></pre> <p><strong>COUNT INCOMING SPACE OBJECTS:</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "CountIncomingSpaceObjects" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private pCount As Long Public Property Get Count() As Long Count = pCount End Property Private Property Let Count(ByRef value As Long) pCount = value End Property Public Sub IncrementCountIncomingSpaceObjects() pCount = pCount + 1 End Sub </code></pre> <h3>CountMissiles:</h3> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "CountMissiles" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private pCount As Long Public Property Get Count() As Long Count = pCount End Property Private Property Let Count(ByRef value As Long) pCount = value End Property Public Sub IncrementMissileCount() pCount = pCount + 1 End Sub </code></pre> <h3>ISpaceObject:</h3> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "ISpaceObject" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False Option Explicit Public Property Let Left(ByVal changeLeft As Long) End Property Public Property Get Left() As Long End Property Public Property Let Top(ByVal changeTop As Long) End Property Public Property Get Top() As Long End Property Public Property Get Width() As Long End Property Public Property Get Height() As Long End Property Public Property Get Name() As String End Property Public Property Get SpaceObjectType() As SpaceObjectType End Property </code></pre> <h3>SpaceObject:</h3> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "SpaceObject" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False Option Explicit Implements ISpaceObject Private Type SpaceObjectData Left As Long Top As Long Height As Long Width As Long SpaceObjectType As String Name As String End Type Private this As SpaceObjectData Public Sub SetInitialLeft(ByVal InitialLeft As Long) this.Left = InitialLeft End Sub Public Sub SetInitialTop(ByVal InitialTop As Long) this.Top = InitialTop End Sub Public Property Let Height(ByVal Height As Long) this.Height = Height End Property Public Property Let Width(ByVal Width As Long) this.Width = Width End Property Public Property Let SpaceObjectType(ByVal SpaceObjectType As SpaceObjectType) this.SpaceObjectType = SpaceObjectType End Property Public Property Let Name(ByVal Name As String) this.Name = Name End Property Public Property Get Self() As SpaceObject Set Self = Me End Property Private Property Let ISpaceObject_Top(ByVal changeTop As Long) this.Top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.Top End Property Private Property Let ISpaceObject_Left(ByVal changeLeft As Long) this.Left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.Left End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.Height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.Width End Property Private Property Get ISpaceObject_Name() As String ISpaceObject_Name = this.Name End Property Private Property Get ISpaceObject_SpaceObjectType() As Long ISpaceObject_SpaceObjectType = this.SpaceObjectType End Property </code></pre> <h3>StopWatch:</h3> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "StopWatch" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False Option Explicit Private Declare PtrSafe Function QueryPerformanceCounter Lib "kernel32" ( _ lpPerformanceCount As UInt64) As Long Private Declare PtrSafe Function QueryPerformanceFrequency Lib "kernel32" ( _ lpFrequency As UInt64) As Long Private pFrequency As Double Private pStartTS As UInt64 Private pEndTS As UInt64 Private pElapsed As Double Private pRunning As Boolean Private Type UInt64 LowPart As Long HighPart As Long End Type Private Const BShift_32 = 4294967296# ' 2 ^ 32 Private Function U64Dbl(U64 As UInt64) As Double Dim lDbl As Double, hDbl As Double lDbl = U64.LowPart hDbl = U64.HighPart If lDbl &lt; 0 Then lDbl = lDbl + BShift_32 If hDbl &lt; 0 Then hDbl = hDbl + BShift_32 U64Dbl = lDbl + BShift_32 * hDbl End Function Private Sub Class_Initialize() Dim PerfFrequency As UInt64 QueryPerformanceFrequency PerfFrequency pFrequency = U64Dbl(PerfFrequency) End Sub Public Property Get Elapsed() As Double If pRunning Then Dim pNow As UInt64 QueryPerformanceCounter pNow Elapsed = pElapsed + (U64Dbl(pNow) - U64Dbl(pStartTS)) / pFrequency Else Elapsed = pElapsed End If End Property Public Sub Start() If Not pRunning Then QueryPerformanceCounter pStartTS pRunning = True End If End Sub Public Sub Pause() If pRunning Then QueryPerformanceCounter pEndTS pRunning = False pElapsed = pElapsed + (U64Dbl(pEndTS) - U64Dbl(pStartTS)) / pFrequency End If End Sub Public Sub Reset() pElapsed = 0 pRunning = False End Sub Public Sub Restart() pElapsed = 0 QueryPerformanceCounter pStartTS pRunning = True End Sub Public Property Get Running() As Boolean Running = pRunning End Property </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T06:15:05.477", "Id": "394547", "Score": "1", "body": "Code not working? \"[...] I have two BIG issues. First, my method of scaling is not working. [...] . Second [...] every so often get a 424 Object Required error. \"" }, { ...
[ { "body": "<p>At the risk of answering an off-topic question(*): Nothing says \"<strong><em>review all logic in the program</em></strong>\" than code like the following: </p>\n\n<pre><code>Public Function IsMissile(ByVal SpaceObjectTwo As ISpaceObject) As Boolean\n If SpaceObjectTwo.SpaceObjectType = Missile...
{ "AcceptedAnswerId": "204569", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T04:06:47.857", "Id": "204564", "Score": "1", "Tags": [ "beginner", "algorithm", "object-oriented", "vba", "excel" ], "Title": "Space Invader game written In VBA, 3rd iteration" }
204564
<p>What I'd like to see in your review, in order of relevance:</p> <ol> <li>Is there any bugs? (I see none, but...)</li> <li>Is the code efficient? (by whatever metric you'd like to use)</li> <li>Is the code easy to understand?</li> </ol> <p>However any feedback is welcomed.</p> <p><strong>tags.lua</strong></p> <pre><code>return { tokens = { num = 1, add = 2, sub = 3, mul = 4, div = 5, rpa = 6, lpa = 7, eof = -1 }, nodes = { num = 1, neg = 2, add = 3, sub = 4, mul = 5, div = 6 } } </code></pre> <p><strong>tokenizer.lua</strong></p> <pre><code>local tags = require 'tags' local function tokenize (s) local i = 1 local tokens = {} local sub = string.sub local function current () return sub(s, i, i) end local function is_digit () local c = current() or ' ' return c &gt;= '0' and c &lt;= '9' end while i &lt;= #s do if current() == '+' then tokens[#tokens + 1] = { tag = tags.tokens.add, pos = i } elseif current() == '-' then tokens[#tokens + 1] = { tag = tags.tokens.sub, pos = i } elseif current() == '*' then tokens[#tokens + 1] = { tag = tags.tokens.mul, pos = i } elseif current() == '/' then tokens[#tokens + 1] = { tag = tags.tokens.div, pos = i } elseif current() == '(' then tokens[#tokens + 1] = { tag = tags.tokens.lpa, pos = i } elseif current() == ')' then tokens[#tokens + 1] = { tag = tags.tokens.rpa, pos = i } elseif is_digit(current()) then local j = i while is_digit() do i = i + 1 end if current() == '.' then i = i + 1 if not is_digit() then error({ message = 'Expected digit after dot', pos = i }) end while is_digit() do i = i + 1 end end i = i - 1 tokens[#tokens + 1] = { tag = tags.tokens.num, lexeme = string.sub(s, j, i), pos = j } elseif current() ~= ' ' then error({ message = 'Symbol not recognized', pos = i }) end i = i + 1 end tokens[#tokens + 1] = { tag = tags.tokens.eof, pos = 1 } return tokens end return { tokenize = tokenize } </code></pre> <p><strong>parser.lua</strong></p> <pre><code>local tags = require 'tags' local tokenizer = require 'tokenizer' local tremove = table.remove local parse_expression_1 local context local function advance() context.i = context.i + 1 end local function is_at(tag_name) return context.tokens[context.i].tag == tags.tokens[tag_name] end local function add(node) context.ast[#context.ast + 1] = node end local function pop() return tremove(context.ast, #context.ast) end local function current() return context.tokens[context.i] end local function report_syntax_error(message) error({ message = message, pos = current().pos }) end local function parse_expression_3 () if is_at('num') then add({ tag = tags.nodes.num, lexeme = current().lexeme }) advance() elseif is_at('sub') then advance() parse_expression_3() add({ tag = tags.nodes.neg, expr = pop() }) elseif is_at('lpa') then advance() parse_expression_1() if is_at('rpa') then advance() else report_syntax_error('Expected right parenthese') end else report_syntax_error('Expected number, left parenthese or minus sign') end end local function parse_expression_2 () parse_expression_3() while true do local next_tag if is_at('mul') then next_tag = tags.nodes.mul elseif is_at('div') then next_tag = tags.nodes.div else return end advance() parse_expression_3() local right = pop() local left = pop() add({ tag = next_tag, left = left, right = right }) end end function parse_expression_1 () parse_expression_2() while true do local next_tag if is_at('add') then next_tag = tags.nodes.add elseif is_at('sub') then next_tag = tags.nodes.sub else return end advance() parse_expression_2() local right = pop() local left = pop() add({ tag = next_tag, left = left, right = right }) end end local function parse (raw_code) context = { tokens = tokenizer.tokenize(raw_code), i = 1, ast = {} } parse_expression_1() if not is_at('eof') then report_syntax_error('Expected end of input') end return context.ast[1] end return { parse = parse } </code></pre> <hr> <p>The following codes are not part of the parser, but you may find them handy in order to test the parser -- and you can review them too if you like.</p> <p><strong>interpreter.lua</strong></p> <pre><code>local tags = require 'tags' local function evaluate (ast) if ast.tag == tags.nodes.num then return tonumber(ast.lexeme) end if ast.tag == tags.nodes.neg then return -evaluate(ast.expr) end if ast.tag == tags.nodes.add then return evaluate(ast.left) + evaluate(ast.right) end if ast.tag == tags.nodes.sub then return evaluate(ast.left) - evaluate(ast.right) end if ast.tag == tags.nodes.mul then return evaluate(ast.left) * evaluate(ast.right) end if ast.tag == tags.nodes.div then local left = evaluate(ast.left) local right = evaluate(ast.right) if right == 0 then error({ message = 'Cannot divide by 0' }) end return left / right end error('Internal error: Unexpected ast_tag') end return { evaluate = evaluate } </code></pre> <p><strong>repl.lua</strong></p> <pre><code>local parser = require 'parser' local interpreter = require 'interpreter' local function repl () print('type "exit" to exit') while true do io.write('&gt; ') local s = io.read() if s == 'exit' then break end local success, v = pcall(function () return interpreter.evaluate(parser.parse(s)) end) if success then print(v) else print('Error: ' .. v.message) if v.pos then print(s) print(string.rep(' ', v.pos - 1) .. '^') end end end print() print('Bye ;)') end repl() </code></pre>
[]
[ { "body": "<h2>Style</h2>\n\n<p>Your placement of the parameters in a function definition isn't consistent. The typical convention, across languages, is no space between the name and the <code>(</code>. There is no \"standard\" style for Lua, though, so if you want to put a space before, go ahead! Just do it on...
{ "AcceptedAnswerId": "220324", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T04:54:32.217", "Id": "204565", "Score": "5", "Tags": [ "parsing", "math-expression-eval", "lua" ], "Title": "Recursive descent parser for simple arithmetic expressions grammar" }
204565
<p>The purpose of this class is to have that can maintain data set where the samples contained within the set have an expiry time. Samples are inserted in chronological order. In an attempt to memory consumption, allocation and deallocations a circular buffer has been implemented. </p> <pre><code>template&lt;typename T&gt; class TemporalBuffer { public: using Clock = std::chrono::steady_clock; using TimePoint = Clock::time_point; using Duration = Clock::duration; struct Sample { TimePoint timestamp{}; T data{}; friend bool operator&lt;(const Sample&amp; lhs, const Sample&amp; rhs) { return lhs.timestamp &lt; rhs.timestamp; } friend bool operator&lt;=(const Sample&amp; lhs, const Sample&amp; rhs) { return !(rhs &lt; lhs); } friend bool operator&gt;(const Sample&amp; lhs, const Sample&amp; rhs) { return rhs &lt; lhs; } friend bool operator&gt;=(const Sample&amp; lhs, const Sample&amp; rhs) { return !(lhs &lt; rhs); } }; using DataSet = std::vector&lt;Sample&gt;; using Head = typename DataSet::iterator; using Tail = typename DataSet::iterator; using AgeLimit = Duration; private: AgeLimit mAgeLimit; DataSet mContainer; Head mHead; Tail mTail; long long GetTimeDelta(TimePoint point1, TimePoint point2) const { return point1 &gt; point2 ? std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(point1 - point2).count() : std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(point2 - point1).count(); } void Clean() { auto expiryTimestamp = Clock::now() - mAgeLimit; while (mTail-&gt;timestamp &lt; expiryTimestamp) { if (std::next(mTail) == std::end(mContainer)) { mTail = std::begin(mContainer); } else { ++mTail; } } } public: explicit TemporalBuffer(AgeLimit ageLimit, int startingBufferSize = 32) : mAgeLimit(ageLimit) { mContainer = DataSet(startingBufferSize); mHead = std::begin(mContainer); mTail = std::begin(mContainer); }; ~TemporalBuffer() = default; void AddSample(T&amp;&amp; sampleData) { if (std::next(mHead) == std::end(mContainer) &amp;&amp; mTail != std::begin(mContainer)) { mHead = std::begin(mContainer); } else if (std::next(mHead) == mTail || (std::next(mHead) == std::end(mContainer) &amp;&amp; mTail == std::begin(mContainer))) { //Our vector is not big enough auto headLocation = mHead - std::begin(mContainer); auto it = std::rotate(mContainer.rbegin(), mContainer.rbegin() + (mContainer.end() - mTail), mContainer.rend()); auto headIncremented = mContainer.size() - (std::rend(mContainer) - it); mContainer.resize(mContainer.size() * 2); mTail = std::begin(mContainer); mHead = std::begin(mContainer) + headLocation + headIncremented; } (*mHead).timestamp = Clock::now(); (*mHead).data = std::move(sampleData); ++mHead; Clean(); } void IncrementIterator(typename DataSet::iterator&amp; it) { if (std::next(it) == std::end(mContainer)) { it = std::begin(mContainer); } else { ++it; } } std::vector&lt;T&gt; GetSamples() { std::vector&lt;T&gt; samples; samples.reserve(Size()); for (auto it = mTail; it != mHead;) { samples.emplace_back(it-&gt;data); IncrementIterator(it); } return samples; } DataSet GetRange(TimePoint start, TimePoint end) { DataSet sampleRange{}; sampleRange.reserve(Size()); for (auto it = mTail; it != mHead;) { if (it-&gt;timestamp &gt;= start &amp;&amp; it-&gt;timestamp &lt;= end) { sampleRange.emplace_back(*it); } IncrementIterator(it); } return sampleRange; } const DataSet&amp; GetDataSet() const { return mContainer; } typename DataSet::size_type Size() const { return mTail &lt;= mHead ? mHead - mTail : mContainer.size() - (mTail - mHead); } boost::optional&lt;Sample&gt; GetNearest(TimePoint timestamp) { if (mContainer.empty() || mTail == mHead) { return boost::none; } if (timestamp &lt;= mTail-&gt;timestamp) { return *mTail; } auto olderIt = std::end(mContainer); auto newerIt = mTail; while (newerIt != mHead) { if (newerIt-&gt;timestamp &gt; timestamp) { olderIt = newerIt == mContainer.begin() ? std::prev(mContainer.end()) : std::prev(newerIt); break; } IncrementIterator(newerIt); } if (olderIt == std::end(mContainer) || newerIt == std::end(mContainer)) { return boost::none; } auto timeToOlder = GetTimeDelta(olderIt-&gt;timestamp, timestamp); auto timeToNewer = GetTimeDelta(newerIt-&gt;timestamp, timestamp); return timeToOlder &lt;= timeToNewer ? *olderIt : *newerIt; } }; </code></pre> <p>The following is a simple example of this code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include "TemporalBuffer.h" int main() { TemporalBuffer&lt;double&gt; timeSeries(std::chrono::seconds{ 60 }); auto lastStatistics = std::chrono::steady_clock::now(); while (true) { timeSeries.AddSample(static_cast&lt;double&gt;(std::rand() % 100)); auto now = std::chrono::steady_clock::now(); if (now - lastStatistics &gt; std::chrono::seconds{ 1 }) { lastStatistics = now; auto dataSet = timeSeries.GetSamples(); auto end = std::chrono::steady_clock::now(); auto delta = std::chrono::milliseconds{ rand() % 30000 }; auto lookupTime = now - delta; auto optional = timeSeries.GetNearest(lookupTime); auto startTime = now - std::chrono::milliseconds{ 2000 + rand() % 5000 }; auto endTime = now - std::chrono::milliseconds{ 2000 - rand() % 2000 }; auto sampleRange = timeSeries.GetRange(startTime, endTime); std::cout &lt;&lt; "Size: " &lt;&lt; dataSet.size() &lt;&lt; ". Dataset population time: " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end - now).count() &lt;&lt; "us. "; std::cout &lt;&lt; "Sample size is " &lt;&lt; sampleRange.size() &lt;&lt; ", for a " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(endTime-startTime).count() &lt;&lt; "ms window. "; if (optional) { std::cout &lt;&lt; delta.count() &lt;&lt; "ms ago, the value was: " &lt;&lt; optional.value().data &lt;&lt; "."; } std::cout &lt;&lt; '\n'; } std::this_thread::sleep_for(std::chrono::milliseconds{ 100 }); } } </code></pre> <p>My initial implementation used a std::map container. I was pleasantly surprised at the performance gain in moving to vector (~50-60x faster). If you have a view on this, please provide feedback/critism and if you know of any implementations similar to this, please provide a link as I would like to see how others have done this - however I didn't find an solutions.</p>
[]
[ { "body": "<h2>Design</h2>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">\"Single Responsibility Principle\"</a> says (paraphrasing) that a class should be responsible for only one thing. <code>TemporalBuffer</code> contains the circular buffer i...
{ "AcceptedAnswerId": "204596", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T08:35:45.933", "Id": "204571", "Score": "3", "Tags": [ "c++", "c++11", "collections" ], "Title": "Time series dataset with temporally enforced object lifetime" }
204571
<blockquote> <p>Find nCr for given n and r.</p> <p><strong>Input:</strong></p> <p>First line contains no of test cases T, for every test case 2 integers as inputs (n,r).</p> <p><strong>Output:</strong></p> <p>Compute and print the value in separate line. Modulus your output to 10^9+7. If n</p> <p><strong>Constraints:</strong> </p> <p>1&lt;=T&lt;=50 </p> <p>1&lt;=n&lt;=1000</p> <p>1&lt;=r&lt;=800</p> <p><strong>Example:</strong></p> <p>Input: </p> <p>1 </p> <p>3 2</p> <p>Output: </p> <p>3</p> </blockquote> <p>My approach:</p> <pre><code>import java.util.Scanner; import java.lang.Math; import java.math.BigInteger; class GFG { private static int calcBinCoeff (int num, int r) { BigInteger numerator = new BigInteger("1"); int limit = (int)(Math.pow(10,9) + 7); BigInteger modulus = new BigInteger(String.valueOf(limit)); for (int i = num; i &gt; num - r ; i--) { BigInteger ind = new BigInteger(String.valueOf(i)); numerator = numerator.multiply(ind); } BigInteger fact = new BigInteger("1"); for (int i = 2; i &lt;= r; i++) { BigInteger elem = new BigInteger(String.valueOf(i)); fact = fact.multiply(elem); } BigInteger ans = (numerator.divide(fact)).mod(modulus); return ans.intValue(); } public static void main (String[] args) { try (Scanner sc = new Scanner(System.in)) { int numTests = sc.nextInt(); while (numTests-- &gt; 0) { int num = sc.nextInt(); int r = sc.nextInt(); System.out.println(calcBinCoeff(num, r)); } } } } </code></pre> <p>I have the following questions with regards to the above code:</p> <p>1.Is there a smarter way to approach this question?</p> <ol start="2"> <li><p>How can I improve the space and time complexity of the given question?</p></li> <li><p>Have I gone too overboard by using BigInteger Library for this question?</p></li> </ol> <p><a href="https://www.geeksforgeeks.org/binomial-coefficient-dp-9/" rel="nofollow noreferrer">Reference</a></p>
[]
[ { "body": "<ul>\n<li>Is there a smarter way to approach this question?</li>\n</ul>\n\n<p>We'll see in a moment. Parts of it can be improved for sure.</p>\n\n<ul>\n<li>How can I improve the space and time complexity of the given question?</li>\n</ul>\n\n<p>You can't. The <em>complexity</em> will remain the same....
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T10:32:05.373", "Id": "204574", "Score": "3", "Tags": [ "java", "beginner", "interview-questions" ], "Title": "Binomial coefficient in Java" }
204574
<p>The idea is this: To determine whether a string is funny, create a copy of the string in reverse e.g. . Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny.</p> <p>This is my Python code for the same:</p> <pre><code>def funnyString(s): temp = s[::-1] arr1,arr2 = [],[] for i in range(len(s)-1): arr1.append(abs(ord(s[i+1])-ord(s[i]))) arr2.append(abs(ord(temp[i+1])-ord(temp[i]))) if arr1 == arr2: return "Funny" else: return "Not Funny" </code></pre> <p>It works but I want to get some feedback if this is too verbose and should/can be shortened. One solution example:</p> <pre><code>acxz bcxz Funny Not Funny </code></pre> <p>The same implementation in C++</p> <pre><code>string funnyString(string s) { string temp; temp = s; vector&lt;int&gt; arr1, arr2; reverse(temp.begin(), temp.end()); for (int i = 0; i &lt; s.length()-1; i++) { arr1.push_back(fabs(int(s[i + 1]) - int(s[i]))); arr2.push_back(fabs(int(temp[i + 1]) - int(temp[i]))); } if (arr1 == arr2) return "Funny"; else return "Not Funny"; } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Separate the logic from output. <code>funnyString</code> shall return a boolean, and the caller would decide what to print. Also consider renaming it <code>is_funny</code>.</p></li>\n<li><p>There is no need to actually reverse the string. Just iterate it backwards.</p></li>\n<li><p>There...
{ "AcceptedAnswerId": "204590", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T15:05:13.917", "Id": "204584", "Score": "1", "Tags": [ "python", "c++", "strings" ], "Title": "Checking if a string is funny or not" }
204584
<p>In my data there can be different number of bars in each chart. Here is a picture:</p> <p><a href="https://i.stack.imgur.com/5lJJL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5lJJL.png" alt="vertical bar charts"></a></p> <p>When pressing the button labeled <em>change bars layout</em> the view of the charts toggles between horizontal and vertical bars. For example, like this:</p> <p><a href="https://i.stack.imgur.com/SB7X4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SB7X4.png" alt="horizontal bar charts"></a></p> <p>Since I might get bar chart stacked vertically or horizontally and there may be a different number of stacks I wasn't able use the D3 stack function and had to do most of the calculation myself.</p> <p>2 more important points:</p> <ol> <li><p>my code is inside VueJS framework.</p></li> <li><p>the variable <code>stackedXorY</code> is 1 or 0, when it's 1 the stack is horizontal when it's 0 the stack is vertical. </p></li> </ol> <p>A couple of questions:</p> <ol> <li><p>Is there a way to use the d3 stack or some other method to create this kind of chart?</p></li> <li><p>I noticed that when I update the chart (in <code>handleChartLayout</code> function) each selected stage holds the y property, even though the data itself (tasks) and stages in it don't hold it. How is that possible? It seems to me I have an issue but not sure.</p></li> </ol> <p>Here is the an example of the data:</p> <pre><code>{ "id":"ACra92XfQ696H7BUCCYT", "isTaskFinished":true, "taskName":"t1", "initTaskTime":1536427448023, "endTaskTime":1536427471408, "taskStages":[ { "initTime":1536427447023, "timeStamps":[ 1536427449994, 1536427453242, 1536427456115 ], "totalTime":12503 }, { "initTime":1536427460526, "timeStamps":[ 1536427465433, 1536427470250 ], "totalTime":10882 } ], "taskTotalTime":23385 } </code></pre> <p>Here is the code:</p> <pre><code> &lt;template&gt; &lt;div&gt; &lt;svg ref="stacked-svg-tasks" id="stacked-svg-tasks" :width="svgWidth" :height="svgHeight" &gt;&lt;/svg&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import * as d3 from 'd3'; export default { name: 'TasksStackedBarChart', props: ['tasks', 'svgWidth', 'svgHeight', 'stackedXorY'], data() { return { X_AXIS_HEIGHT: 20, Y_AXIS_WIDTH: 50, svgMargin: { top: 20 }, barChartGroup: { width: 0, height: 0, x: 0, y: 0, }, GbT: 50, // gap between tasks stageWidth: 0, toalStages: 0, xPosOfTasks: [], yScale: null, yScaleDomainEnd: 0, }; }, created() { this.barChartGroup.width = this.svgWidth - this.Y_AXIS_WIDTH; this.barChartGroup.height = this.svgHeight - this.X_AXIS_HEIGHT; this.barChartGroup.x = this.Y_AXIS_WIDTH; this.barChartGroup.y = this.X_AXIS_HEIGHT; this.toalStages = this.tasks.map(v =&gt; v.taskStages.length).reduce((s, v) =&gt; s + v, 0); this.stageWidth = this.getStageWidth(); this.xPosOfTasks = this.getXPosOfTask(this.GbT, this.tasks, this.stageWidth, this.stackedXorY); this.yScaleDomainEnd = this.getLongestTask(); this.yScale = this.getScaleForTask(this.barChartGroup.height, this.yScaleDomainEnd); }, mounted() { this.chartBuilder(); }, methods: { getScaleForTask(rangeEnd, domainEnd) { const calcRangeEnd = rangeEnd - this.svgMargin.top - this.X_AXIS_HEIGHT; return d3.scaleLinear() .range([0, calcRangeEnd]) .domain([0, domainEnd]); }, getLongestTask() { return d3.max(this.tasks.map(t =&gt; t.taskTotalTime)); }, getStageWidth() { // will keep using this. to see if it's better to work like this or i should pass parameters const numOfChartBars = this.stackedXorY ? this.toalStages : this.tasks.length; return Math.floor((this.svgWidth - (this.GbT * (this.tasks.length + 1))) / numOfChartBars); }, getPosOfStage(stage, stageIndex) { const x = stageIndex * this.stageWidth * this.stackedXorY; // this sets the bars at the bottom than this.yScale(s.y) moves them accordingly const y = this.barChartGroup.height - this.yScale(stage.totalTime) - ((1 - this.stackedXorY) * this.yScale(stage.y)); return `translate(${x}, ${y})`; }, getXPosOfTask(gapBetweenTasks, tasks, widthOfBar, stackedYorX) { const newXPosOfTasks = [0]; // [gapBetweenTasks + 50]; for (let c = 0; c &lt; tasks.length - 1; c += 1) { const barsInTask = stackedYorX ? tasks[c].taskStages.length : 1; const taskXPos = gapBetweenTasks + (barsInTask * widthOfBar) + newXPosOfTasks[c]; newXPosOfTasks.push(taskXPos); } return newXPosOfTasks; }, cumulativeTimeOfStages(taskStages) { return taskStages.reduce((sums, curItem) =&gt; { const newSum = sums[sums.length - 1] + curItem.totalTime; sums.push(newSum); return sums; }, [0]); }, reconstructedStageData(taskStages) { const cumulativeSums = this.cumulativeTimeOfStages(taskStages); return taskStages.map((stage, i) =&gt; ({ y: cumulativeSums[i], ...stage })); }, chartBuilder() { // clearing svg d3.selectAll('#stacked-svg-tasks').selectAll('g').remove(); const svg = d3.select('#stacked-svg-tasks'); // adding Y axis const yAxisScale = d3 .scaleTime() .domain([this.yScaleDomainEnd, 0]) .range([0, this.svgHeight - this.X_AXIS_HEIGHT - this.svgMargin.top]); const yAxis = d3.axisLeft().scale(yAxisScale); const barChartGroup = svg .selectAll('g') .data([this.tasks]) .enter() .append('g') .attr('class', 'bar-chart-group') .attr('transform', `translate(${this.barChartGroup.x},${this.barChartGroup.y})`); const taskGroups = barChartGroup .selectAll('g') .data(t =&gt; t) .enter() .append('g') .attr('class', (t, i) =&gt; `bar${i}`) .attr('transform', (t, i) =&gt; `translate(${this.xPosOfTasks[i]},0)`); const stageGroups = taskGroups .selectAll('g') .data(t =&gt; this.reconstructedStageData(t.taskStages)) .enter() .append('g') .attr('transform', (s, i) =&gt; this.getPosOfStage(s, i)) .append('rect') .attr('width', this.stageWidth) .attr('height', s =&gt; this.yScale(s.totalTime)) .attr('fill', (d, i) =&gt; (i % 2 === 0 ? '#66ccff' : '#99ff66')) .attr('style', 'stroke:rgb(150,150,150);stroke-width:2'); }, handleChartLayout() { const svg = d3.select('#stacked-svg-tasks'); this.tasks.forEach((task, taskIndex) =&gt; { svg .selectAll(`.bar${taskIndex}`) .data([task]) .transition() .duration(750) .attr('transform', `translate(${this.xPosOfTasks[taskIndex]}, 0)`) .selectAll('g') .attr('transform', (s, i) =&gt; this.getPosOfStage(s, i)) .selectAll('rect') .attr('width', this.stageWidth); }); }, }, watch: { stackedXorY() { this.stageWidth = this.getStageWidth(); this.xPosOfTasks = this.getXPosOfTask(this.GbT, this.tasks, this.stageWidth, this.stackedXorY); this.handleChartLayout(); }, }, }; &lt;/script&gt; </code></pre>
[]
[ { "body": "<h1>Overall Feedback</h1>\n\n<p>In general, the code looks good and is fairly easy to read. Most of the methods are concise and would lend themselves well to unit tests. I like the use of <code>const</code> by default for variables and only using <code>let</code> for the iterator variable <code>c</co...
{ "AcceptedAnswerId": "207995", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T16:06:28.037", "Id": "204586", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "data-visualization", "d3.js", "vue.js" ], "Title": "D3 Updating stacked bar chart" }
204586
<p>As I'm mastering STL I wrote a solution for generating all the prime tuples of the form <code>(p1,p2)</code> where "twin" means <code>p2-p1=2</code>, "cousin" <code>p2-p1=4</code> and "sexy" <code>p2-p1=6</code>.</p> <p>I'm interested in all the comments about the efficiency and style of this solution.</p> <p>I use the following subroutine from <code>utilities_template.h</code> to print vector container:</p> <pre><code>template &lt;class C&gt; void printContainer(C v, std::string msg = "Container", bool rowWise = true) { std::cout &lt;&lt; msg &lt;&lt; " " &lt;&lt; std::endl; for (auto it = v.cbegin(); it != v.cend(); ++it) std::cout &lt;&lt; std::setw(3) &lt;&lt; *it &lt;&lt; (rowWise ? " " : "\n"); std::cout &lt;&lt; std::endl; } </code></pre> <p>And here is my solution:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "utilities_template.h" enum primeClassification { twin = 2, cousin = 4, sexy = 6 }; void removeElementsInListDivisibleByP(int p, std::list&lt;int&gt;&amp; l) { l.remove_if([p](int n) { return n % p == 0; }); } std::vector&lt;int&gt; getAllPrimesLessN(int n, bool debugMode = false) { using namespace std; list&lt;int&gt; l; for (int i = 2; i &lt; n + 1; i++) { l.push_back(i); } int min_element = 2; // vector&lt;int&gt; primes = {min_element}; while (min_element != l.back()) { removeElementsInListDivisibleByP(min_element, l); if (debugMode) printContainer( l, "After divisible by " + std::to_string(min_element) + " removed:"); min_element = *std::min_element(l.cbegin(), l.cend()); primes.push_back(min_element); } auto temp_it = adjacent_find(primes.cbegin(), primes.cend(), [](const int&amp; a, const int&amp; b) { return (b - a) == 1; }); printContainer(primes, "Primes up to " + std::to_string(n)); return primes; } std::vector&lt;std::pair&lt;int, int&gt; &gt; formPrimePairs(primeClassification pClass, std::vector&lt;int&gt;&amp; primes) { using namespace std; std::vector&lt;std::pair&lt;int, int&gt; &gt; pairs; for (auto it = next(primes.cbegin(), 1); it != primes.cend(); it++) { if (*it - *std::prev(it, 1) == pClass) { auto this_pair = make_pair(*prev(it, 1), *it); pairs.push_back(this_pair); } } return pairs; } void s4PrimePairs() { using namespace std; int n = 0; cout &lt;&lt; "Please enter the limit: "; cin &gt;&gt; n; vector&lt;int&gt; primes = getAllPrimesLessN(n); printVectorOfPairs(formPrimePairs(primeClassification::twin, primes), "\nTwin pairs (delta=2): ", true); printVectorOfPairs(formPrimePairs(primeClassification::cousin, primes), "\nCousin pairs(delta=4): ", true); printVectorOfPairs(formPrimePairs(primeClassification::sexy, primes), "\nSexy pairs(delta=6): ", true); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:55:09.700", "Id": "394662", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y...
[ { "body": "<ul>\n<li><p><code>std::min_element</code> is unwarranted. The list is initially sorted, and <code>remove_if</code> guarantees to maintain the order of remaining elements. A minimal element is <code>*l.cbegin()</code>.</p></li>\n<li><p><code>removeElementsInListDivisibleByP</code> is very hard to rea...
{ "AcceptedAnswerId": "204593", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T16:57:15.823", "Id": "204588", "Score": "3", "Tags": [ "c++", "primes" ], "Title": "C++/STL Prime tuples (twin, cousin, sexy) up to the given limit" }
204588
<p>My program has to detect the real file type of a given file using signatures. For now I'm just checking <strong>JPG</strong>, but I want to add more.</p> <pre><code>Dim files() As String = IO.Directory.GetFiles(pictures) Dim file_data As Byte() Dim jpg_file_extension() As Byte = {&amp;HFF, &amp;HD8, &amp;HFF} Dim office_file_extension() As Byte = {&amp;H50, &amp;H4B, &amp;H3, &amp;H4, &amp;H14, &amp;H0, &amp;H6, &amp;H0} Dim check As Integer = 0 For Each file As String In files file_data = IO.File.ReadAllBytes(file) If file_data.Length &gt; 2 Then For i = 0 To jpg_file_extension.Length - 1 If file_data(i) = jpg_file_extension(i) Then check += 1 Else check = 0 Exit For End If Next If (check.ToString.Length = jpg_file_extension.Length - 1) Then MsgBox(file.Split("\").Last &amp; ": its jpg") End If End If Next </code></pre> <p>The code looks a bit messy right now and It's only checking one file type, my questions are:</p> <ol> <li>How can I improve this code, make it cleaner and efficient.</li> <li>Is there a way to implement this code in such a way that I can have a function, give it the file data and check if the signature is "whitelisted"?</li> </ol>
[]
[ { "body": "<p>Your first step is to wind your thinking back a few steps and re-approach your code with a fresh line of thinking. Looking at your code, you say \"to detect the real file type of a given file\" but you have written code to detect a JPEG(*) file. </p>\n\n<p>There is a subtlety here, but once you ha...
{ "AcceptedAnswerId": "204605", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T19:04:00.190", "Id": "204595", "Score": "4", "Tags": [ "file", "vb.net" ], "Title": "Detect file type using file signatures" }
204595
<p>This is my implementation of LRU caching in PHP. </p> <p>It works fine when I tested as. What are the things that I miss or need attention?</p> <pre><code>&lt;?php class Cache{ private $cache; private $size; public function __construct($size) { $this-&gt;cache = []; $this-&gt;size = $size; } public function put($item) { if($this-&gt;isFull()) { if(in_array($item, $this-&gt;cache)) { $this-&gt;cache = array_diff($this-&gt;cache, [$item]); } else { array_pop($this-&gt;cache); } } array_unshift($this-&gt;cache,$item); } public function display() { var_dump($this-&gt;cache); } private function isFull() { if(count($this-&gt;cache) &gt;= $this-&gt;size) { return true; } } } $cache_size = 4; $entries = [3,4,4,5,6,7,4,4,3,5,2,3,1,1,4]; $cache = new Cache($cache_size); $cache-&gt;display(); foreach($entries as $entry) { $cache-&gt;put($entry); } $cache-&gt;display(); </code></pre> <p><strong>Output for above provided data</strong></p> <pre><code>//blank cache array(0) { } //insertion of all entries array(4) { [0]=&gt; int(4) [1]=&gt; int(1) [2]=&gt; int(3) [3]=&gt; int(2) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T14:09:49.783", "Id": "394780", "Score": "0", "body": "I think, even if the array `!is_full()`, the $item has to be removed, if it is in_array()." } ]
[ { "body": "<p>This implementation is quite simple. I compared it with some others in PHP as well as other languages like C++, Java and JavaScript. Some use a node class to store a key and value separately (e.g. <a href=\"https://github.com/rogeriopvl/php-lrucache/blob/master/src/LRUCache/LRUCache.php\" rel=\"no...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T19:12:14.207", "Id": "204597", "Score": "2", "Tags": [ "php", "algorithm", "array", "cache" ], "Title": "Simple implementation of LRU caching in PHP" }
204597
<p>I have made a form in HTML and the form data should be send via email. For that purpose I have created a PHP script. </p> <p>I did read a lot about the importance of form validation in order to prevent hackers on using the form to redirect to different website and other malicious use.</p> <p>Can someone please check if I secured the form from hackers attacks?</p> <p><strong>Form:</strong></p> <pre><code> &lt;form method="post" action="send_form.php"&gt; &lt;div class="form-group"&gt; &lt;label for="input-name"&gt;Full name:&lt;/label&gt; &lt;input type="text" class="form-control" id="input-name" name="full_name" placeholder="Name Surname" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="input-email"&gt;Email address:&lt;/label&gt; &lt;input type="email" class="form-control" id="input-email" name="email" placeholder="email@domain.xy" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="input-date"&gt;Wedding date:&lt;/label&gt; &lt;input type="text" class="form-control" id="input-date" name="date" placeholder="dd/mm/yyy" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="input-location"&gt;Location:&lt;/label&gt; &lt;input type="text" class="form-control" id="input-location" name="location" placeholder="Town, restaurant"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;button type="submit" class="btn btn-primary" name="submit"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;?php // check if form was submited if (isset($_POST['submit'])) { $name = test_input($_POST['full_name']); $emailFrom = test_input($_POST['email']); $date = test_input($_POST['date']); $location = test_input($_POST['location']); $emailTo = "xxx"; $subject = "Form was submited at xxx by: ".$emailFrom; $txt = " name: $name \n email: $emailFrom \n date: $date \n location: $location"; if (mail($emailTo, $subject, $txt)) { // return to the main page after form submited header("Location: xxx"); } } // remove empty spaces and convert html characters function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:36:19.767", "Id": "394656", "Score": "0", "body": "Welcome to CodeReview! Please edit your post title to more closely reflect the purpose of the code, perhaps \"Wedding ... contact form validation\" or so. Apart from that looks g...
[ { "body": "<p>First of all you must understand that <strong>validation and sanitization are not synonyms</strong>. But completely different processes that have very little in common.</p>\n<p>Whereas sanitization indeed does prevent the malicious use, validation is merely for your and/or your customer's convenie...
{ "AcceptedAnswerId": "204615", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T21:09:46.470", "Id": "204600", "Score": "1", "Tags": [ "php", "html", "validation", "form" ], "Title": "Check PHP validation code" }
204600
<p>The code is an implementation of looping text (similar to a circular buffer - wraps around when it reaches the edge of the defined bounds) with directional control.</p> <p>The code is functional and works as intended, but I'm curious if there is anyway to improve the code even if it is only a small improvement (e.g. less garbage produced per loop cycle as a micro-optimisation, etc).</p> <pre><code># cleaned up and improved prototype code for looping text scroll. # added direction from the original code. from sys import stdout from time import sleep global_shifted_text_array = [] global_text_length = 0 DIRECTION_LEFT_TO_RIGHT = -1 DIRECTION_RIGHT_TO_LEFT = 1 def set_text(text): global global_shifted_text_array global global_text_length global_shifted_text_array = pad_text(text) global_text_length = len(global_shifted_text_array) def pad_text(text, padding = 5): text += ' ' * padding return list(text) def shift_text(direction): global global_shifted_text_array range = xrange(global_text_length - 1, -1, -1) if direction == DIRECTION_LEFT_TO_RIGHT else xrange(global_text_length) # by the time the zero element is set in the for loop. # it is set to the last element (which is empty) # so we have to account for this by correcting for it. if direction == DIRECTION_RIGHT_TO_LEFT: first_element = global_shifted_text_array[0] for i in range: global_shifted_text_array[i] = global_shifted_text_array[((i + direction) % global_text_length)] # print 'global_shifted_text_array[{}] = global_shifted_text_array[{}]'.format(i, ((i + direction) % global_text_length)) if direction == DIRECTION_RIGHT_TO_LEFT: global_shifted_text_array[global_text_length - 1] = first_element def update_loop(direction = DIRECTION_LEFT_TO_RIGHT, frequency = 0.1): while 1: shift_text(direction) stdout.write('\r{0}'.format(''.join(global_shifted_text_array))) sleep(frequency) set_text('Beautiful Lie') update_loop() </code></pre>
[]
[ { "body": "<p>When I try it, it doesn't really work unless I add <code>stdout.flush()</code> after each <code>stdout.write()</code>.</p>\n\n<p>The padding isn't controllable, as neither <code>set_text()</code> nor <code>update_loop()</code> accepts a <code>padding</code> parameter.</p>\n\n<p>In my opinion, it s...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T21:14:13.323", "Id": "204601", "Score": "2", "Tags": [ "python", "performance", "python-2.x", "animation", "circular-list" ], "Title": "Looping text in Python with directional control" }
204601
<p>I have an <code>interface</code> which is for an object which has <em>bounds</em> in a 2D plane.</p> <pre><code>interface Boundable : Positionable { /** * Returns the [Bounds] (the [Position] and [Size]) of this [Boundable]. */ fun bounds(): Bounds /** * Returns the [Size] of this [Boundable]. */ fun size(): Size /** * Tells whether this [Boundable] intersects the other `boundable` or not. */ fun intersects(boundable: Boundable): Boolean /** * Tells whether `position` is within this boundable's bounds. */ fun containsPosition(position: Position): Boolean /** * Tells whether this boundable contains the other `boundable`. * A [Boundable] contains another if the other boundable's bounds * are within this one's. (If their bounds are the same it is considered * a containment). */ fun containsBoundable(boundable: Boundable): Boolean } </code></pre> <p>This is something like <code>Rect</code> in the <em>Java</em> SDK for example. Currently <code>Boundable</code> inherits from <code>Positionable</code>:</p> <pre><code>/** * Represents an object which is positionable within its parent. * Note that once positioned a [Positionable] can't be moved. * If you want re-positionable objects @see [Movable]. */ interface Positionable { fun position(): Position = Position.zero() } </code></pre> <p><code>Positionable</code> is for objects which have a <code>Position</code> within a larger object on the same plane. This setup worked so far but now I need to have <em>3 versions</em> of <code>Boundable</code>. One, which does not inherit from <code>Positionable</code> (to be used for detached or root objects), one which does and one which is <code>Movable</code>:</p> <pre><code>/** * A [Movable] object is a specialized [Positionable]. * It can not only be positioned but moved as well. */ interface Movable : Positionable { fun moveTo(position: Position): Boolean fun moveBy(position: Position) = moveTo(position() + position) fun moveRightBy(delta: Int) = moveTo(position().withRelativeX(delta)) fun moveLeftBy(delta: Int) = moveTo(position().withRelativeX(-delta)) fun moveUpBy(delta: Int) = moveTo(position().withRelativeY(-delta)) fun moveDownBy(delta: Int) = moveTo(position().withRelativeY(delta)) } </code></pre> <p>My problem is figured out a name for the variants, but I'm not satisfied with them. I came up with <code>PositionableBoundable</code> and <code>MovableBoundable</code> but they sound weird.</p> <p><em>Are these names adequate or should I change them to something more descriptive?</em></p>
[]
[ { "body": "<h3>Everything is an Entity!</h3>\n\n<p>If you would follow the <a href=\"https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system\" rel=\"nofollow noreferrer\">Entity Component System</a> approach, that is. The idea is that all <em>objects</em> are <em>entities</em>, and each Entity has...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T21:34:15.487", "Id": "204602", "Score": "1", "Tags": [ "inheritance", "interface", "kotlin", "mixins", "trait" ], "Title": "Proper naming for objects which have a position and bounds on a plane" }
204602
<p>This is my version of Hangman Game, written in C++. How could it be improved? what should I avoid using/doing in future projects?</p> <pre><code>#include&lt;iostream&gt; #include&lt;iomanip&gt; #include&lt;algorithm&gt; #include&lt;string&gt; #include&lt;limits&gt; #undef max class Hangman { private: std::string wordName{ "0" }, wordHint{ "0" }, answer{ "" }, wordType{ "0" }, hanged[5]{ "JOHN","ALEX","MAX","JIMMY","TIM" } ;// Just for fun names std::string keyboard = "\t\t ___________________________________ \n" "\t\t | KEYBOARD | \n" "\t\t |-----------------------------------| \n" "\t\t | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | \n" "\t\t |-----------------------------------| \n" "\t\t | a | b | c | d | e | f | g | h | i | \n" "\t\t |-----------------------------------| \n" "\t\t | j | k | l | m | n | o | p | q | r | \n" "\t\t |-----------------------------------| \n" "\t\t | s | t | u | v | w | x | y | z | 0 | \n" "\t\t |-----------------------------------| \n" "\t\t |___________________________________| \n"; int countHang{ 0 }; // How many parts of the hanged man char ch{ 0 }; // Input Variable bool active{ 1 }, flag{ 1 }, tag{ 1 }; // check variables public: // Hangman() -&gt; contructor Main Menu to link all the functions together // HintWord() -&gt; Word inputs // Rules() -&gt; pretty simple there // HangBoard() -&gt; the main display board // HangCheck() -&gt; Draws main-body of the Hangman and checks how many left // AgainMenu() -&gt; Final display menu and variable resetting bool exit{ 0 }; // Exiting Variable Hangman() { // STARTING WINDOW active = 1; while (active) { std::cout &lt;&lt; "\t\t ____________________________________ \n" "\t\t | MAIN MENU | \n" "\t\t | ----------- | \n" "\t\t | --XX--- ---XX-- | \n" "\t\t | : ~Hangman~ : | \n" "\t\t | : : | \n" "\t\t | O 1. Play O | \n" "\t\t | /|\\ /|\\ | \n" "\t\t | / \\ 2. Rules / \\ | \n" "\t\t | | \n" "\t\t | 3. Exit | \n" "\t\t |____________________________________| \n\n\n" "\t\t --&gt;"; std::cin &gt;&gt; ch; // Choice menu with conditions incase of wrong input if (ch == '1') { active = 0; system("cls"); HintWord(); } else if (ch == '2') { active = 0; system("cls"); Rules(); } else if (ch == '3') { system("cls"); active = 0; exit = 1;//EXIT } else { system("cls"); //WRONG CHOICE } } }; inline void Rules() { std::cout &lt;&lt; "\n\n\t\t ~WELCOME~ \n" "\n\n\t\t ------------------------------------------------------------------------------------------ \n" "\n\n\t\t (1)Choose one person to be the 'host.' This is the person that invents the puzzle \n" "\t\t for the other person to solve. They will be tasked with choosing a word that 'the players' \n" "\t\t will have to solve. \n\n" "\t\t The host should be able to spell confidently or the game will be impossible to win. \n\n" "\t\t (2)If you are the host, choose a secret word. The other players will need to guess your \n" "\t\t word letter by letter, so choose a word you think will be difficult to guess. Difficult \n" "\t\t words usually have uncommon letters, like 'z,' or 'j,' and only a few vowels. \n\n" "\t\t (3)Start guessing letters if you are the player. Once the word has been chosen and the \n" "\t\t players know how many letters in the secret word, begin playing by entering which letters \n" "\t\t are in the word. \n\n" "\t\t (4)Whenever the players guess a letter that is not in the secret word they get a strike \n" "\t\t that brings them closer to losing. To show this, the game draws a simple stick figure of a \n" "\t\t man being hung, adding a new part to the drawing with every wrong answer. \n\n\n" "\t\t *** 1. Go Back. \n" "\t\t ------------------------------------------------------------------------------------------ \n" "\t\t --&gt;"; std::cin &gt;&gt; ch; if (ch == '1') { active = 0; system("cls"); Hangman(); } else { system("cls"); //WRONG CHOICE } } inline void HintWord() { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | \n" "\t\t | \\ O O \n" "\t\t | |\\ /|7 \n" "\t\t ___|___ / \\ / \\ \n"; std::cout &lt;&lt; "\n\n\t\t *** Host, Enter secret word to be found: \t\t (*) PLAYERS DON'T LOOK AT THIS SCREEN!!\n" "\t\t --&gt; "; std::cin &gt;&gt; wordName; std::transform(wordName.begin(), wordName.end(), wordName.begin(), tolower); // Takes main word input here and converts to lower-case std::cout &lt;&lt; std::endl; std::cout &lt;&lt; "\t\t *** Enter word type e.g Movie,Food/Drink,Song..etc: \n" "\t\t --&gt; "; // Had a problem here as the getline() function wasn't accepting all of the input correctly , which numeric limit seemed to fix here std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); std::getline(std::cin, wordType); std::cout &lt;&lt; std::endl; std::cout &lt;&lt; "\t\t *** Enter hint: \n" "\t\t --&gt; "; std::getline(std::cin, wordHint); // Converting all of it into Underscores for (unsigned i = 0; i &lt; wordName.length(); ++i) answer += "_"; system("cls"); HangBoard(); } inline void HangBoard() { int i = 0; active = 1; while (active) { HangCheck(); std::cout &lt;&lt; "\t\t ~TYPE~ \"" &lt;&lt; wordType &lt;&lt; "\"\t\t "; //Displaying the word as underscores with spaces for (unsigned i = 0; i &lt; wordName.length(); ++i) { std::cout &lt;&lt; answer[i] &lt;&lt; " "; } //ABC std::cout &lt;&lt; "\n\n\t\t ~HINT~ \"" &lt;&lt; wordHint &lt;&lt; "\"\n\n"; std::cout &lt;&lt; "\t\t\t\t\t\t\t (*) '#' Shown on the keyboard means it's already tried."; std::cout &lt;&lt; "\t\t\t\t\t\t\t\t (*) Enter '.' to exit."; std::cout &lt;&lt; "\n\n" &lt;&lt; keyboard; // Just wanted to try doing a little fun trick , if they inputted "#" as their first choice of character // It would automatically show the first letter of the hidden word , if they use "#" as any other input of character // Which isnt the first choice, it wouldn't work :: will mark the trick part with //TRICK comment if (flag == 1) { std::cout &lt;&lt; "\t\t ~X~ --&gt;"; std::cin &gt;&gt; ch; } else { //TRICK std::cout &lt;&lt; "\t\t ;) ~O~ --&gt;"; std::cin &gt;&gt; ch; } if (ch == '.') { system("cls"); Hangman(); active = 0; break; } //Converting if (ch &lt;= 90 &amp;&amp; ch &gt;= 65) ch += 32; // incase of input of any of those signs to keep keyboard same outline format , using # sign as letter being taken if (ch != '|'&amp;&amp; ch != '_' &amp;&amp; ch != '-' &amp;&amp; keyboard.find(ch) != std::string::npos) keyboard[keyboard.find(ch)] = '#'; if (ch != '#') tag = 0; //TRICK if (ch == '#' &amp;&amp; flag == 1 &amp;&amp; tag == 1) { ch = wordName[0]; flag = 0; } //END of KEYBOARD // Checking if correct input here with find function i = wordName.find(ch); while (wordName.find(ch, i) != std::string::npos) { answer[wordName.find(ch, i)] = ch; i++; } if (wordName.find(ch) == std::string::npos) { countHang++; // testing the basic alarm bell sound for wrong character input std::cout &lt;&lt; "\a"; } if (countHang == 6) { system("cls"); AgainMenu(); } else if (answer == wordName) { system("cls"); AgainMenu(); } system("cls"); } } inline void AgainMenu() { active = 1; while (active) { if (countHang == 6) { std::cout &lt;&lt; "\t\t ____________________________________ \n" "\t\t | " &lt;&lt; std::setw(5) &lt;&lt; hanged[rand() % 5] &lt;&lt; " DIED! | \n" "\t\t | ----------- | \n" "\t\t | ( X _ X ) | \n" "\t\t | | \n" "\t\t | ________ | \n" "\t\t | / Nooo!!!\\ | \n" "\t\t | _____ \\ ______/ | \n" "\t\t | ( ) &lt;O&gt; \\/ | \n" "\t\t | | RIP | | | \n" "\t\t | |_____| &lt;&lt; | \n" "\t\t | ------------------------------ | \n" "\t\t | | \n" "\t\t | 1. Play Again | \n" "\t\t | | \n" "\t\t | 2. Exit | \n" "\t\t |____________________________________| \n\n\n"; } else { std::cout &lt;&lt; "\t\t ____________________________________ \n" "\t\t | " &lt;&lt; std::setw(5) &lt;&lt; hanged[rand() % 5] &lt;&lt; " LIVES! | \n" "\t\t | ----------- | \n" "\t\t | ________ | \n" "\t\t | / I LIVE!\\ | \n" "\t\t | \\ ______/ | \n" "\t\t | \\/ | \n" "\t\t | |O/ | \n" "\t\t | | | \n" "\t\t | / &gt; | \n" "\t\t | _____ \\O&gt; \\O/ | \n" "\t\t | / \\ | | | \n" "\t\t | / \\ &lt; \\ / \\ | \n" "\t\t | ------------------------------ | \n" "\t\t | | \n" "\t\t | 1. Play Again | \n" "\t\t | | \n" "\t\t | 2. Exit | \n" "\t\t |____________________________________| \n\n\n"; } std::cout &lt;&lt; "\t\t --&gt;"; std::cin &gt;&gt; ch; if (ch == '1') { active = 0; system("cls"); // Variable resetting countHang = 0; flag = 1; tag = 1; wordName = "0"; wordHint = "0"; answer = ""; wordType = "0"; keyboard = "\t\t ___________________________________ \n" "\t\t | KEYBOARD | \n" "\t\t |-----------------------------------| \n" "\t\t | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | \n" "\t\t |-----------------------------------| \n" "\t\t | a | b | c | d | e | f | g | h | i | \n" "\t\t |-----------------------------------| \n" "\t\t | j | k | l | m | n | o | p | q | r | \n" "\t\t |-----------------------------------| \n" "\t\t | s | t | u | v | w | x | y | z | 0 | \n" "\t\t |-----------------------------------| \n" "\t\t |___________________________________| \n"; HintWord(); } else if (ch == '2') { system("cls"); active = 0; exit = 1;//EXIT } else { system("cls"); //WRONG CHOICE } } } inline void HangCheck() { if (countHang == 0) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | \n" "\t\t | \n" "\t\t | \n" "\t\t ___|___ \n\n\n"; } else if (countHang == 1) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | O \n" "\t\t | \n" "\t\t | \n" "\t\t ___|___ \n\n\n"; } else if (countHang == 2) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | O \n" "\t\t | | \n" "\t\t | \n" "\t\t ___|___ \n\n\n"; } else if (countHang == 3) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | O \n" "\t\t | |\\ \n" "\t\t | \n" "\t\t ___|___ \n\n\n"; } else if (countHang == 4) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | O \n" "\t\t | /|\\ \n" "\t\t | \n" "\t\t ___|___ \n\n\n"; } else if (countHang == 5) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | O \n" "\t\t | /|\\ \n" "\t\t | / \n" "\t\t ___|___ \n\n\n"; } else if (countHang == 6) { std::cout &lt;&lt; "\t\t ______ \n" "\t\t | | \n" "\t\t | : \n" "\t\t | O \n" "\t\t | /|\\ \n" "\t\t | / \\ \n" "\t\t ___|___ \n\n\n"; } } }; int main() { std::ios::sync_with_stdio(0); Hangman game; if (game.exit == 1) return 0; std::cin.get(); return 0; } </code></pre> <p>Thanks again</p>
[]
[ { "body": "<p>This is a lot of code. It may take multiple edits over multiple days to provide all my feedback. (Of course, others may provide feedback in areas I haven't got to yet...)</p>\n\n<hr>\n\n<p>C++11 allows \"raw\" string literals. Instead of:</p>\n\n<pre><code> std::cout &lt;&lt; \"\\t\\t __...
{ "AcceptedAnswerId": "204654", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-29T21:35:14.773", "Id": "204603", "Score": "4", "Tags": [ "c++", "beginner", "object-oriented", "game", "hangman" ], "Title": "Hangman Game in C++" }
204603
<p>I have this table on SQL: </p> <pre><code>record_type | user | date type_1 | user1| 2018-09-27T09:13:15.946545 type_2 | user1| 2018-09-27T09:13:30.052329 type_1 | user1| 2018-09-27T09:11:18.724686 type_2 | user1| 2018-09-27T08:11:18.724686 type_1 | user2| 2018-09-25T09:13:15.946545 type_2 | user2| 2018-09-25T09:13:30.052329 type_1 | user2| 2018-09-25T09:11:18.724686 type_2 | user2| 2018-09-25T08:11:18.724686 </code></pre> <p>I need to count how many users for a <code>record_type</code> have data older than X days. Expected result for record older than a day is:</p> <pre><code>record_type | count type_1 | 2 type_2 | 2 </code></pre> <p>This is my query: </p> <pre><code>select record_type, count(*) from (select record_type, user, max(date) as MaxDate from table group by record_type, user having to_timestamp(max(date), 'YYYY-MM-DD HH24:MI:SS.M') &lt; NOW() - interval '15' day order by MaxDate desc ) as test group by record_type; </code></pre> <p>This works, but I wonder if there's a better way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T11:58:50.830", "Id": "394921", "Score": "0", "body": "Please take a look at our [SQL tag](https://codereview.stackexchange.com/tags/sql/info) information. We require context, the schema and output of `explain select`. You got a goo...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T01:49:49.933", "Id": "204609", "Score": "2", "Tags": [ "sql", "postgresql" ], "Title": "SQL query for selecting count from grouped columns of latest records" }
204609
<p>I solved the <a href="https://www.hackerrank.com/challenges/luck-balance/problem" rel="nofollow noreferrer">Hackerrank Luck Balance problem</a> the "C" way (I am much more used to C) and I wanted to know if there were any C++ features I could have used that would have made my code more concise/neater. That's it! Any other criticism is welcome, of course.</p> <p>All the stuff that I wrote is in the <code>LuckBalance()</code> function. Pay no attention to anything else - that was provided by the challenge (which wasn't really a challenge)</p> <blockquote> <p>Lena is preparing for an important coding competition that is preceded by a number of sequential preliminary contests. She believes in "saving luck", and wants to check her theory. Each contest is described by two integers, <span class="math-container">\$L[i]\$</span> and <span class="math-container">\$T[i]\$</span>. <span class="math-container">\$L[i]\$</span> is the amount of luck associated with a contest. If Lena wins the contest, her luck balance will decrease by <span class="math-container">\$L[i]\$</span>; if she loses it, her luck balance will increase by <span class="math-container">\$L[i]\$</span>.</p> <p><span class="math-container">\$T[i]\$</span> denotes the contest's importance rating. It's equal to <span class="math-container">\$1\$</span> if the contest is important, and it's equal to <span class="math-container">\$0\$</span> if it's unimportant.</p> <p>If Lena loses no more than <span class="math-container">\$k\$</span> important contests, what is the maximum amount of luck she can have after competing in all the preliminary contests? This value may be negative.</p> </blockquote> <p>Note that the <code>k</code> parameter in the luckBalance function is the maximum number of important contests Lena can lose, and the <code>vector&lt;vector&lt;int&gt;&gt; contests</code> input is a column vector of <span class="math-container">\$L[i]\$</span> along with a column vector of <span class="math-container">\$T[i]\$</span>.</p> <pre><code>#include &lt;bits/stdc++.h&gt; #include &lt;stdlib.h&gt; using namespace std; vector&lt;string&gt; split_string(string); // Complete the luckBalance function below. int luckBalance(int k, vector&lt;vector&lt;int&gt;&gt; contests) { int totalLostLuck = 0; int totalGainedLuck = 0; int totalRegainedLuck = 0; vector&lt;int&gt; regainedLuck(k, 0); for(int i = 0; i &lt; contests.size(); i++) { if(contests[i][1] == 1) { totalLostLuck += contests[i][0]; for(int j = 0; j &lt; k; j++) { // Choose to win the contests that have the greatest // amount of luck if(regainedLuck[j] &lt; contests[i][0]) { regainedLuck[j] = contests[i][0]; sort(regainedLuck.begin(), regainedLuck.end()); j = k; } } } // If it is a non-important contest, we get the luck for free! else { totalGainedLuck += contests[i][0]; } } for(int i = 0; i &lt; k; i++) { totalRegainedLuck += regainedLuck[i]; } return totalGainedLuck - totalLostLuck + (2*totalRegainedLuck); } int main() { //ofstream fout(getenv("OUTPUT_PATH")); string nk_temp; getline(cin, nk_temp); vector&lt;string&gt; nk = split_string(nk_temp); int n = stoi(nk[0]); int k = stoi(nk[1]); vector&lt;vector&lt;int&gt;&gt; contests(n); for (int i = 0; i &lt; n; i++) { contests[i].resize(2); for (int j = 0; j &lt; 2; j++) { cin &gt;&gt; contests[i][j]; } cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'); } int result = luckBalance(k, contests); cout &lt;&lt; result &lt;&lt; "\n"; //fout.close(); return 0; } vector&lt;string&gt; split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &amp;x, const char &amp;y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector&lt;string&gt; splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T09:04:33.157", "Id": "394628", "Score": "0", "body": "Also, based on the stuff I see on the homepage, this is a lot more trivial than the average query on this website. If this is too trivial to belong I will take it down at the fir...
[ { "body": "<h1>Prefer standard headers</h1>\n<p><code>&lt;bits/stdc++.h&gt;</code> isn't in any standard; even on those platforms where it exists, it's probably a poor choice if it includes the whole of the Standard Library. Instead, include (only) the standard library headers that declare the types that are r...
{ "AcceptedAnswerId": "204729", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T09:03:25.330", "Id": "204618", "Score": "3", "Tags": [ "c++", "programming-challenge" ], "Title": "Hackerrank Luck Balance solution in C++" }
204618
<h2>Backstory</h2> <p>Recently, we've changed the PCs at my workplace to un Linux Mint.<br> It works amazing, is blazing fast and the adjustment time was very short.</p> <p>However, I noticed my PC would freeze completely, sometimes.<br> I've determined that it is low RAM memory.</p> <p>My working habits require me to open 10+ tabs (sometimes 100, in 5-8 Google Chrome windows).<br> This makes it so the swap is stuffed, as well as the RAM (Physical Memory).<br> Sometimes I have to use a VM running off of my PC, which takes 4GB for itself.</p> <h2>The code</h2> <p>Since old habits are hard to kill and isn't fun, I've decided to write code (which is a lot more fun).</p> <p>Since Linux Mint doesn't warn about low available RAM, I've scattered around and put together a script to run every minute, and warn me when the memory is running low.</p> <p>This script can also be executed from the console, displaying a message on it, if needed.<br> A detection method had to be added, since the output sent to <code>cron</code> is emailed by default.</p> <pre class="lang-sh prettyprint-override"><code>#!/usr/bin/env bash # based from https://askubuntu.com/questions/234292/warning-when-available-ram-approaches-zero LANG=en_US.UTF-8 # gets available and total ram RAM=$(free -m) total=$(echo "$RAM"|awk '/^[mM]em\.?:/{print $2}') available=$(echo "$RAM"|awk '/^[mM]em\.?:/{print $7}') # warn if less than these levels is free # warning = 20% # critical = 10% WARNING=$(expr $total / 5) CRITICAL=$(expr $total / 10) # -h int:transient:1 &lt;-- don't store the notification # https://unix.stackexchange.com/questions/393397/get-notify-send-to-clear-itself-from-notification-tray/401587 if [ $available -lt $CRITICAL ]; then # using -u critical doesn't allow the notification to go away after -t ms have past # this causes issues if afk, since the notifications will queue until the -u critical is closed notify-send -i error -h int:transient:1 -t 60000 "Low memory!" "$available/$total MB free, critical at $CRITICAL MB" elif [ $available -lt $WARNING ]; then notify-send -h int:transient:1 -t 15000 "Memory is going low" "Available: $available/$total MB, warns at $WARNING MB" fi # outputs if not ran by cron # https://unix.stackexchange.com/questions/46789/check-if-script-is-started-by-cron-rather-than-invoked-manually if [ -t 0 ]; then echo "Available: $available/$total MB, warns at $WARNING MB, critical at $CRITICAL MB" fi </code></pre> <p>This script runs in <code>crontab -e</code>, with the following:</p> <pre><code># https://unix.stackexchange.com/questions/247860/notify-send-doesnt-work-at-cinnamon DISPLAY=":0.0" XAUTHORITY="/home/&lt;username&gt;/.Xauthority" XDG_RUNTIME_DIR="/run/user/&lt;output from id -u&gt;" * * * * * /usr/bin/env bash /home/&lt;username&gt;/&lt;script-from-above&gt;.sh </code></pre> <h2>Conclusion</h2> <p>It was really hard to get to this point, with plenty of issues.<br> Most information was available online, but, making it work was a pain.</p> <p>I'm not really good with Bash scripting, which probably means that I have some really bad mistakes.<br> As far as I know, it works as intended, when intended:</p> <p><a href="https://i.stack.imgur.com/OOhjT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OOhjT.png" alt="Notification"></a></p> <p>Besides that, is there anything I can improve or change?<br> Any optimization/optimisation I can do?<br> Any localization/localisation issues that may come?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:55:56.360", "Id": "394663", "Score": "1", "body": "Bravo for a large percentage of your code comments being StackExchange links." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:57:45.177", "...
[ { "body": "<p>Kudos to you! This is a nice little script, easy to read and to understand. However, there is no reason to reach for <code>expr</code>. Most shells (including <code>dash</code> or even <code>busybox sh</code>) can interpret arithmetic expressions on their own:</p>\n\n<pre><code>WARNING=$(($total /...
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T13:02:47.177", "Id": "204625", "Score": "7", "Tags": [ "bash", "memory-management", "linux", "shell", "status-monitoring" ], "Title": "Bash script to send notifications when low on ram" }
204625
<p>This is the third time I am asking for a review of this code (first time can be found here: <a href="https://codereview.stackexchange.com/questions/203728/arabic-language-lesson-program">Arabic language lesson program</a> and the second can be found here: <a href="https://codereview.stackexchange.com/questions/203869/arabic-language-lesson-program-part-2">Arabic language lesson program Part 2</a>). </p> <p>The goal of the program is to house Arabic language lessons and teach Arabic to English speakers, somewhat similar to how Duolingo works. </p> <p>The first time around I was instructed to move the questions out of the code and into a separate text file. Now all my questions are sorted by lesson number and part number into a .json file and I call certain questions from the file in the code. In the second round of reviews, I learned how to use for loops to consolidate a significant amount of my code. Though I've been able to greatly reduce the amount of repetition in my code, I still would like to move my code into a class based system. Eventually I plan on having 50 to 100 questions housed in several lessons each with multiple part so I want to be as efficient as possible in my coding to make code maintenance as manageable as I can. </p> <p><strong>Review Objective:</strong> I would like help figuring out how to take my current code and migrate it into a more manageable setup (I'm assuming something class-based) that would allow me to continue to build this program in a manageable fashion. Also, would it be worth having a separate python file for each lesson and then have a main python program to tie them all together or would it be better to just have one large python program? Any advice would be appreciated. </p> <pre><code>def Part1(): Root_File_Name = "C:\\LearningArabic\\LiblibArriby\\" JSON_File = Root_File_Name + "Lessons\\Lesson_1\\" with open(JSON_File+"Arabic_Lesson_1.json", "r", encoding = "utf-8-sig") as question_file: data = json.load(question_file) def create_widgets_in_first_frame(): # Create the label for the frame current_frame=frames[0] #Make the frame number generic so as to make copy/paste easier. ##UPDATE PER QUESTION## question_number = "question0" question_frame_populator(current_frame, question_number) def question_frame_populator(current_frame, question_number): #This is what displayes all of the information on the frame questionDirectory = data["lesson 1"]["part one"][question_number] ##UPDATE PER QUESTION## This is the directory for the question. wronganswer = questionDirectory["wronganswer"] #This is the directory for the wrong answers question = questionDirectory.get("question") #This is the question text correctanswer = questionDirectory.get("answer") #This is the answer for whichever question has been selected. arabic = questionDirectory.get("arabic") #This is the arabic text for the question transliteration = questionDirectory.get("transliteration") global var var = IntVar() var.set(0) #Sets the initial radiobutton selection to nothing answers = generate_answers(wronganswer, correctanswer) #Pulls answers generated from the "generate_answers" function choices = [] for i in range(3): choice = Radiobutton(current_frame, image=answers[i], variable = var, value=i+1, command= Check_Answer) choice.image = answers[i] choices.append(choice) random.shuffle(choices) #This line of code randomizes the order of the radiobuttons. choices[0].grid(row=1, column=0) choices[1].grid(row=1, column=1) choices[2].grid(row=1, column=2) L1 = Label(current_frame, text=question, font=("Helvetica", 35)) #This displays the question at the top of the screen L1.grid(columnspan=4, row=0) transliteration_button = Button(current_frame, text="Show Transliteration", command= lambda: Transliteration(current_frame, arabic, transliteration)) # Makes the phonetic pronunciation button. ##### transliteration_button.grid(column=0, row=2) #Previous_Button() # Creates the "previous" button and displays it. Next_Button() # Creates the "next" button and displays it. Quit_Button(current_frame) # Creates the "quit" button and displays it. def Transliteration(current_frame, arabic, transliteration): Transliteration = Label(current_frame, text="'"+arabic+"'" + " is pronounced " + "'"+transliteration+"'", font=("Helvetica", 35)) Transliteration.grid(row=3, columnspan=4) def generate_answers(wronganswer, correctanswer): Wans=random.sample(wronganswer, 2) images = [os.path.join(ImagePath, f"{Wans[i]}.png") for i in range(2)] images += [os.path.join(ImagePath, f"{correctanswer}.png")] answers = [PhotoImage(file=images[i]) for i in range(3)] return answers def Check_Answer(): global lives global score if str(var.get()) !="3": special_frames[1].grid_forget() #This is the frame for right answers special_frames[0].grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E)) #This is the frame for wrong answers lives -=1 Incorrect = Label(special_frames[0], text ="That's incorrect!\n Lives: " +str(lives) + "\n Score: " + str(score), font=("Helvetica", 35)) Incorrect.grid(row=0, rowspan=2, column=0, columnspan=3) if str(var.get()) == "3": score +=1 special_frames[0].grid_forget() #This is the frame for wrong answers special_frames[1].grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E)) #This is the frame for right answers Correct = Label(special_frames[1], text = " That's right! \n Lives: " +str(lives)+ "\n Score: " + str(score), font=("Helvetica", 35)) Correct.grid(row=0, rowspan=2, column=0, columnspan=5) def all_frames_forget(): for i in range(6): #This is for question frames frames[i].grid_forget() for i in range(3): #This is for special frames, like the correct and incorrect answer frames special_frames[i].grid_forget() def check_remaining_lives(create_widgets_in_current_frame, current_frame): if lives&lt;= 0: Zero_Lives() else: create_widgets_in_current_frame current_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E)) def Zero_Lives(): special_frames[2].grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E)) L5 = Label(special_frames[2], text="You have no remaining lives. \nPlease quit the lesson and try again.", font=("Helvetica", 35)) L5.grid(columnspan=4, row=0) quit_button = Button(special_frames[2], text = "Quit", command = root_window.destroy) quit_button.grid(column=1, columnspan = 2, row=2) def Quit_Button(current_frame): quit_button = Button(current_frame, text = "Quit", command = quit_program) quit_button.grid(column=4, row=2) def quit_program(): root_window.destroy() def Next_Button(): next_button = Button(special_frames[1], text = "Next Question", command = next_question) next_button.grid(column=0, columnspan=5, row=3) def next_question(): global frameNumber frameNumber +=1 call_frame(frameNumber) def create_widgets_function(frameNumber): current_frame=frames[frameNumber] #Make the frame number generic so as to make copy/paste easier. ##UPDATE PER QUESTION## question_number = "question"+ str(frameNumber) question_frame_populator(current_frame, question_number) def call_frame(frameNumber): all_frames_forget() create_widgets_in_current_frame =create_widgets_function(frameNumber) current_frame = frames[frameNumber] check_remaining_lives(create_widgets_in_current_frame, current_frame) def call_frame_1(): all_frames_forget() create_widgets_in_current_frame = create_widgets_in_first_frame() #This line is unique current_frame = frames[0] #This line is unique check_remaining_lives(create_widgets_in_current_frame, current_frame) ##### Program starts here ##### Lesson1_FilePath = Root_File_Name + "Lessons\\Lesson_1\\" ImagePath = Lesson1_FilePath + "Images\\" root_window = Tk() # Create the root GUI window. root_window.title("Lesson 1: Part 1") # Label the root GUI window. global score score = 0 #Setting the initial score to zero. global lives lives = 3 #Setting the initial number of lives. global frameNumber frameNumber = 1 window_width = 200 # Define window size window_heigth = 100 frames = [] # This includes frames for all questions for i in range(6): frame=tkinter.Frame(root_window, width=window_width, height=window_heigth) frame['borderwidth'] = 2 frame['relief'] = 'sunken' frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E)) frames.append(frame) special_frames=[] #This includes the frames for: wrong answers, right answers, and zero lives for i in range(3): special=tkinter.Frame(root_window, width=window_width, height=window_heigth) special['borderwidth'] = 2 special['relief'] = 'sunken' special.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E)) special.grid_forget() special_frames.append(special) call_frame_1() #Calls the first function which creates the firist frame root_window.mainloop() </code></pre> <p>Here is a section of my .json file fore reference:</p> <pre><code>{"lesson 1": {"part one": { "question0": { "question": "What is the meaning of 'واد' in English?", "arabic": "واد", "transliteration": "walid", "answer": "boy", "wronganswer" : [ "girl", "woman", "man", "waiter", "mom", "priest", "driver", "teacher", "doctor", "grandparents", "chef" ] }, "question1": { "question": "What is the meaning of 'بنت' in English?", "arabic": "بنت", "transliteration": "bint", "answer": "girl", "wronganswer" : [ "woman", "man", "waiter", "mom", "priest", "driver", "teacher", "doctor", "grandparents", "Chef" ] }, "question2": { "question": "What is: 'He is a boy' in Arabic?", "arabic": "هو ولد", "transliteration": "Huwa walid", "answer": "Heboy", "wronganswer" : [ "Shegirl" ] }, "question3": { "question": "What is: 'She is a girl' in Arabic?", "arabic": "هي بنت", "transliteration": "Hia bint", "answer": "Shegirl", "wronganswer" : [ "Heboy" ] }, "question4": { "question": "What is the meaning of 'ست' in English?", "arabic": "ست", "transliteration": "sit", "answer": "woman", "wronganswer" : [ "girl", "boy", "man", "waiter", "mom", "priest", "driver", "teacher", "doctor", "grandparents", "Chef" ] }, "question5": { "question": "What is the meaning of 'رخل' in English?", "arabic": "رخل", "transliteration": "ragul", "answer": "man", "wronganswer" : [ "girl", "woman", "boy", "waiter", "mom", "priest", "driver", "teacher", "doctor", "grandparents", "Chef" ] } }, } </code></pre> <p>Here is an example of one of the questions:</p> <p><a href="https://i.stack.imgur.com/I1rcz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I1rcz.png" alt="enter image description here"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T13:36:58.920", "Id": "204628", "Score": "1", "Tags": [ "python", "python-3.x", "gui", "tkinter", "pygame" ], "Title": "Arabic Language lesson program Part 3" }
204628
<p>I would like to ask the experts here if this is secure. If it is not can I get an explanation as to why it would not be secure? I have been reading off and on on sites for this and I have trouble understanding a couple of things.</p> <p>Here is the main registration script:</p> <pre><code>&lt;?php $name = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $hash = md5 (rand(0,1000)); if(isset($name)) { if (trim($name) == '' || trim($name) == ' ') { print_r('Username cannot be empty'); } else { if(preg_match('/^[a-zA-Z0-9]{5,}$/', $name)) { // for english chars + numbers only if( strlen($password) &lt; 8 ) { print_r("Password too short!"); } elseif( !preg_match("#[0-9]+#", $password) ) { print_r("Password must include at least one number!"); } elseif( !preg_match("#[a-z]+#", $password) ) { print_r("Password must include at least one letter!"); } elseif( !preg_match("#[A-Z]+#", $password) ) { print_r("Password must include at least one CAPS!"); } elseif( !preg_match("#\W+#", $password) ) { print_r("Password must include at least one symbol!"); } else { if(isset($_POST['submit'])) { if(filter_var($email, FILTER_VALIDATE_EMAIL)) { $subject = 'Signup | Verification'; // Give the email a subject $message = ' Thanks for signing up! Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below. ------------------------ Username: '.$name.' Password: '.$password.' ------------------------ Please click this link to activate your account: http://www.mywebsite.com/verify.php?email='.$email.'&amp;hash='.$hash.' '; // Our message above including the link $headers = 'From:asdf@mywebsite.com' . "\r\n"; // Set from headers if(!isset($con)) { $config = parse_ini_file('config2.ini'); $con = mysqli_connect(`localhost`,$config["username"],$config["password"],$config["dbname"])or die ("MySQL Error: " . mysqli_connect_error()); } $stmt = $con-&gt;prepare("SELECT login FROM Accounts WHERE login=?"); $stmt-&gt;bind_param("s", $GLOBALS['name']); $stmt-&gt;execute(); $stmt-&gt;bind_result($un); $usernamefound = 'false'; while ($stmt-&gt;fetch()) { if(isset($un)) { $usernamefound = 'true'; print_r ('Username already exists.'); } } $stmt-&gt;close(); if ($usernamefound == 'false') { if (filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) || filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ip = filter_var($_SERVER['REMOTE_ADDR']); mail($email, $subject, $message, $headers); // Send our email $hashed_password = password_hash($GLOBALS['password'], PASSWORD_DEFAULT); $result = $con-&gt;prepare('INSERT INTO Accounts(login,password,email,lastip,hash) VALUES (?, ?, ?, ?, ?)'); $result-&gt;bind_param("sssss", $GLOBALS['name'], $hashed_password, $GLOBALS['email'], $ip, $GLOBALS['hash']); $result-&gt;execute(); $result-&gt;close(); $con-&gt;close(); echo "Registered: " . $ip; } else { header('Location: noIPError.html'); die(); } echo "&lt;br/&gt;"; // Return Success - Valid Email print_r('Your account has been made, &lt;br /&gt; please verify it by clicking the activation link that has been send to your email.'); } } else { // Return Error - Invalid Email print_r('The email you have entered is invalid, please try again.'); } } } } else { print_r('Invalid Username: Must be alphanumeric and longer than or equal to 5 chars'); echo "&lt;br/&gt;"; print_r('No special characters or spaces allowed'); } } } ?&gt; </code></pre> <p>I would really like to know what i am doing wrong when it comes to <code>mysqli_real_escape_string</code> as well and from what I've been reading it's not even really that secure anyway. What if I do the variables directly and simply just get rid of <code>$name</code>, <code>$password</code> and so on all together. Would that be the most secure way to do it?</p> <p>I'm assuming it's ok for those globals to exist due to the password hash?</p> <p>If there is any major exploit I'd like to learn about it I guess is what this question is mainly about.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:32:54.397", "Id": "394655", "Score": "0", "body": "Welcome to CodeReview! Please edit the title of your post to explain what the code does, not a specific question about it. Apart from that it looks good and I hope you get some g...
[ { "body": "<p><H1>Coding well is hard, but reading code should be easy</h1></p>\n\n<p>After reading through your code I think it is reasonable secure. You protect yourself against SQL-injection and you use <code>password_hash()</code>. All good things. </p>\n\n<p>However this code only provides the most basic s...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:10:56.990", "Id": "204629", "Score": "4", "Tags": [ "php", "mysql", "security", "mysqli" ], "Title": "PHP script security for new user registration" }
204629
<p>I'm creating a page where users can purchase an adult, child or senior ticket, each with it's own pricing. </p> <p>Here's the code for review. Please let me know if there are ways to improve upon this 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>// declare all variables var adultQty = document.getElementById('quantityAdult'); var childQty = document.getElementById('quantityChild'); var seniorQty = document.getElementById('quantitySenior'); var submitBtn = document.getElementById('submitButton'); var outputPara = document.getElementById('totalPrice'); // generic function that takes in quantity and multiplies with appropriate price function calcPrice(qty, price){ return qty * price; } // generic function that outputs final price and amout it tickets purchased function getMessage(qty, total){ return outputPara.innerHTML = 'You purchased ' + qty + ' ticket(s) and your total price is $' + total + '&lt;br&gt;&lt;br&gt;' + '&lt;button&gt;Proceed To Checkout&lt;/button&gt;'; } submitBtn.addEventListener('click', function() { if(adultQty.value === '0' &amp;&amp; childQty.value === '0' &amp;&amp; seniorQty.value === '0'){ alert('Please purchase at least 1 ticket'); } else { var totalAdult = calcPrice(adultQty.value, 49); var totalChild = calcPrice(childQty.value, 20); var totalSenior = calcPrice(seniorQty.value, 30); var totalPrice = totalAdult + totalChild + totalSenior; var totalTix = parseInt(adultQty.value) + parseInt(childQty.value) + parseInt(seniorQty.value); getMessage(totalTix, totalPrice); } }); </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;Purchase your tickets online! &lt;/p&gt; &lt;ul&gt; &lt;li&gt;$49 - Adult&lt;/li&gt; &lt;li&gt;$20 - Child&lt;/li&gt; &lt;li&gt;$30 - Senior &lt;/li&gt; &lt;/ul&gt; &lt;label&gt;Quantity: &lt;/label&gt;&lt;input type="text" id="quantityAdult" value="0"&gt; &lt;label&gt;Adult&lt;/label&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;Quantity: &lt;/label&gt;&lt;input type="text" id="quantityChild" value="0"&gt; &lt;label&gt;Child&lt;/label&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;Quantity: &lt;/label&gt;&lt;input type="text" id="quantitySenior" value="0"&gt; &lt;label&gt;Senior&lt;/label&gt; &lt;br&gt;&lt;br&gt; &lt;button type="submit" id="submitButton"&gt;Submit&lt;/button&gt; &lt;p id="totalPrice"&gt;&lt;/p&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>General advices</h2>\n\n<p>Separate <a href=\"https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976\" rel=\"nofollow noreferrer\">pure</a> functions from impure ones. \nPure functions don't have side effects and they are easy to test and reuse. I...
{ "AcceptedAnswerId": "204642", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T14:26:03.747", "Id": "204630", "Score": "2", "Tags": [ "javascript", "calculator", "form" ], "Title": "Purchase tickets calculation with JavaScript" }
204630
<p>I am developing a userscript that redirects insecure pages (HTTP) to the https: version.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// ==UserScript== // @name Secure Redirect // @namespace http://tampermonkey.net/ // @version 0.1 // @description A simple userscript that redirects pages to https:. // @author You // @match * // @grant none // ==/UserScript== (function() { 'use strict'; window.onload=()=&gt;{ if (location.protocol != "https:") { window.location.href = "https:" + window.location.href.substring(window.location.protocol.length); } }; })();</code></pre> </div> </div> </p> <p>Please tell me if it works and what I can improve on. My GitHub repo for this project is <a href="https://github.com/alphabetadev/secure-redirect" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T01:24:34.273", "Id": "394712", "Score": "0", "body": "It would work but this is something that really should be done server side." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T08:00:57.783", "Id...
[ { "body": "<h2>Overview</h2>\n\n<ul>\n<li>Pass global variables as parameters to IIFE to make your code more independent and clear</li>\n<li>Use <code>addEventListener</code> method to follow recommended way of attaching event listeners\nDo you really need to execute redirection code, only when everything is lo...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T15:26:15.567", "Id": "204632", "Score": "3", "Tags": [ "javascript", "url", "userscript", "https" ], "Title": "Userscript to redirect insecure pages to HTTPS" }
204632
<p>The code below comes from the <a href="https://github.com/KYHSGeekCode/Android-Disassembler/blob/d3db3e3db1c1c46ead8719ee0aff8716ce1da5fb/app/src/main/java/capstone/Arm_const.java" rel="nofollow noreferrer"><code>Arm_const</code></a> class of my <a href="https://github.com/KYHSGeekCode/Android-Disassembler/tree/d3db3e3db1c1c46ead8719ee0aff8716ce1da5fb" rel="nofollow noreferrer">Android disassembler project</a>:</p> <pre><code>// ARM condition code public static final int ARM_CC_INVALID = 0; public static final int ARM_CC_EQ = 1; public static final int ARM_CC_NE = 2; public static final int ARM_CC_HS = 3; public static final int ARM_CC_LO = 4; public static final int ARM_CC_MI = 5; public static final int ARM_CC_PL = 6; public static final int ARM_CC_VS = 7; public static final int ARM_CC_VC = 8; public static final int ARM_CC_HI = 9; public static final int ARM_CC_LS = 10; public static final int ARM_CC_GE = 11; public static final int ARM_CC_LT = 12; public static final int ARM_CC_GT = 13; public static final int ARM_CC_LE = 14; public static final int ARM_CC_AL = 15; public static String getCCName(int cc) { Class clazz=Arm_const.class; Field[] fields=clazz.getFields(); for(Field f:fields) { String s=f.getName(); if(s.contains("ARM_CC_")) try { if (((int)f.get(null))==cc) { return s.replace("ARM_CC_",""); } } catch (IllegalAccessException e) { Log.e("arm","",e); } catch (IllegalArgumentException e) {} } return ""; } </code></pre> <p>The method <code>getCCName</code> returns the name of a constant from the declared <code>public static final int</code>s.</p> <p>Examples:</p> <ul> <li><p>3 → "HS"</p></li> <li><p>12 → "LT"</p></li> </ul> <p>Any suggestions to improve its performance <strong>(speed)</strong> are appreciated!</p>
[]
[ { "body": "<p>If performance is your concern I would implement <code>getCCName</code> as a lookup in a map that's filled when the class is loaded, e.g. like</p>\n\n<pre><code>private static final Map&lt;Integer, String&gt; _int2string;\n\nstatic\n{\n final Map&lt;Integer, String&gt; int2string = new HashMap&...
{ "AcceptedAnswerId": "204636", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T15:28:11.460", "Id": "204633", "Score": "1", "Tags": [ "java", "performance", "reflection", "constants" ], "Title": "Finding the name of a given constant using reflection" }
204633
<p>This simple script computes some basic descriptive statistics, like mean, standard deviation, kurtosis, etc. on data column imported from a CSV file with use of <code>pandas</code>. In addition, the script accepts argument <code>--exclude_zeros</code> and computes the desired statistics excluding zeros. The script delivers the desired results. However, as I come from R background, I would be happy receive feedback on a proper / <em>pythonic</em> way of generating the desired results.</p> <p><strong>Data</strong></p> <p>The data pertains to geographic area sizes of neighbourhood geographies for Scotland and is publicly available. This and other similar data sets can be sourced from <a href="https://statistics.gov.scot/home" rel="nofollow noreferrer">Scottish Government open data portal</a>.</p> <pre><code>#!/Users/me/path/path/path/bin/python """DZ Area check The script sources uses previously used area size file and produces some descriptive statistics. The script additionally computes statistics excluding zeros. """ # Modules # Refresh requirements creation: # $ pipreqs --force ~/where/this/stuff/sits/ import os import argparse import pandas as pd from tabulate import tabulate import numpy as np # Main function running the program def main(csv_data, exclude): """Computer the desired area statisics""" data = pd.read_csv( filepath_or_buffer=csv_data, skiprows=7, encoding='utf-8', header=None, names=['datazone', 'usual_residenrs', 'area_hectares']) print('\nSourced table:\r') print(tabulate(data.head(), headers='keys', tablefmt='psql')) # Replace zero if required if exclude: data = data.replace(0, np.NaN) # Compute statistics area_mean = data.loc[:, "area_hectares"].mean() area_max = data.loc[:, "area_hectares"].max() area_min = data.loc[:, "area_hectares"].min() area_total = data.loc[:, "area_hectares"].sum() obs_count = data.loc[:, "area_hectares"].count() obs_dist = data.loc[:, "area_hectares"].nunique( ) # Count distinct observations area_variance = data.loc[:, "area_hectares"].var() area_median = data.loc[:, "area_hectares"].median() area_std = data.loc[:, "area_hectares"].std() area_skw = data.loc[:, "area_hectares"].skew() area_kurt = data.loc[:, "area_hectares"].kurtosis() # Create results object results = { 'Statistic': [ 'Average', 'Max', 'Min', 'Total', 'Count', 'Count (distinct)', 'Variance', 'Median', 'SD', 'Skewness', 'Kurtosis' ], 'Value': [ area_mean, area_max, area_min, area_total, obs_count, obs_dist, area_variance, area_median, area_std, area_skw, area_kurt ] } # Show results object print('\nArea statistics:\r') print( tabulate( results, headers='keys', tablefmt='psql', numalign='left', floatfmt='.2f')) return (results) # Import arguments. Solves running program as a module and as a standalone # file. if __name__ == '__main__': parser = argparse.ArgumentParser( description='Calculate basic geography statistics.', epilog='Data Zone Area Statistics\rKonrad') parser.add_argument( '-i', '--infile', nargs=1, type=argparse.FileType('r'), help='Path to data file with geography statistics.', default=os.path.join('/Users', 'me', 'folder', 'data', 'folder', 'import_folder', 'stuff.csv')) parser.add_argument( '--exclude-zeros', dest='exclude_zeros', action='store_true', default=False) args = parser.parse_args() # Call main function and computse stats main(csv_data=args.infile, exclude=args.exclude_zeros) </code></pre> <h1>Results</h1> <pre class="lang-none prettyprint-override"><code>Sourced table: +----+------------+-------------------+-----------------+ | | datazone | usual_residenrs | area_hectares | |----+------------+-------------------+-----------------| | 0 | S01000001 | 872 | 438.88 | | 1 | S01000002 | 678 | 30.77 | | 2 | S01000003 | 788 | 13.36 | | 3 | S01000004 | 612 | 20.08 | | 4 | S01000005 | 643 | 27.02 | +----+------------+-------------------+-----------------+ Area statistics: +------------------+-------------+ | Statistic | Value | |------------------+-------------| | Average | 1198.11 | | Max | 116251.04 | | Min | 0.00 | | Total | 7793711.31 | | Count | 6505.00 | | Count (distinct) | 4200.00 | | Variance | 35231279.23 | | Median | 22.00 | | SD | 5935.59 | | Skewness | 9.77 | | Kurtosis | 121.59 | +------------------+-------------+ </code></pre> <h2>Results (excluding zeros)</h2> <pre class="lang-none prettyprint-override"><code>Sourced table: +----+------------+-------------------+-----------------+ | | datazone | usual_residenrs | area_hectares | |----+------------+-------------------+-----------------| | 0 | S01000001 | 872 | 438.88 | | 1 | S01000002 | 678 | 30.77 | | 2 | S01000003 | 788 | 13.36 | | 3 | S01000004 | 612 | 20.08 | | 4 | S01000005 | 643 | 27.02 | +----+------------+-------------------+-----------------+ Area statistics: +------------------+-------------+ | Statistic | Value | |------------------+-------------| | Average | 1199.03 | | Max | 116251.04 | | Min | 1.24 | | Total | 7793711.31 | | Count | 6500.00 | | Count (distinct) | 4199.00 | | Variance | 35257279.16 | | Median | 22.01 | | SD | 5937.78 | | Skewness | 9.77 | | Kurtosis | 121.49 | +------------------+-------------+ </code></pre>
[]
[ { "body": "<p>Suppose that we wanted to add a new statistic, what would we have to do? Well, we'd need to make three changes: </p>\n\n<ol>\n<li><p>Compute the statistic and put its value in a new variable:</p>\n\n<pre><code>new_statistic = data.loc[:, \"area_hectares\"].new_statistic()\n</code></pre></li>\n<li>...
{ "AcceptedAnswerId": "204950", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T16:14:11.000", "Id": "204635", "Score": "4", "Tags": [ "python", "python-3.x", "numpy", "statistics", "pandas" ], "Title": "Python program computing some statistics on Scottish geographic areas" }
204635
<p>The code is an implementation of looping text (similar to a circular buffer - wraps around when it reaches the edge of the defined bounds) with directional control.</p> <p>The code is functional and works as intended, but I'm curious if there is anyway to improve the code even if it is only a small improvement (e.g. less garbage produced per loop cycle as a micro-optimisation, etc).</p> <pre><code>using System; using System.Text; using System.Threading; namespace LoopingTextScroll { internal class Program { private enum Direction { LeftToRight = -1, RightToLeft = 1 } private static StringBuilder PadText(string text, int padding = 5) { var stringBuilder = new StringBuilder(text); stringBuilder.Append(new string(' ', padding)); return stringBuilder; } private static void ShiftText(StringBuilder textBuilder, Direction direction) { var directionOffset = (int)direction; var textLength = textBuilder.Length; switch (direction) { case Direction.LeftToRight: { for(var i = textLength - 1; i &gt;= 0; i--) textBuilder[i] = textBuilder[Modulo(i + directionOffset, textLength)]; break; } case Direction.RightToLeft: { var firstElement = textBuilder[0]; for(var i = 0; i &lt; textLength; i++) textBuilder[i] = textBuilder[Modulo(i + directionOffset, textLength)]; textBuilder[textLength - 1] = firstElement; break; } } } private static void UpdateLoop(string text, Direction direction = Direction.LeftToRight, int updateRate = 100) { var textBuilder = PadText(text); while (true) { ShiftText(textBuilder, direction); Console.Write($"\r{textBuilder}"); Thread.Sleep(updateRate); } } private static int Modulo(int x, int m) { var remainder = x % m; return remainder &lt; 0 ? remainder + m : remainder; } public static void Main(string[] args) { UpdateLoop("Beautiful Lie", Direction.RightToLeft); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T16:46:21.447", "Id": "394678", "Score": "0", "body": "mhmm... are you sure this is working? Because this prints the text without cleaning the console so it just prints and prints and prints... is this how it should work?" }, { ...
[ { "body": "<p>I think the use of StringBuilder is making the code harder to read and isn't giving you a great benefit for the cost of read-ability or maintainability. </p>\n\n<p>To add spaces to the end of a string there is a method build in <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.p...
{ "AcceptedAnswerId": "204727", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T16:42:19.157", "Id": "204638", "Score": "2", "Tags": [ "c#", "performance", "animation", "circular-list" ], "Title": "Looping text with directional control" }
204638
<p>I have just finished a big project in Python. It is a card game.</p> <p>Here are the rules:</p> <p>There are 30 cards in the deck. Before the game starts, the deck is shuffled. Each card has a colour (red, black or yellow) and a number (1-10).</p> <p>There are 15 rounds in the game. In each round both players take 1 card from the top of the deck.</p> <p>The winner of each round depends on the colour of the card.</p> <p>Red beats black. Black beats yellow. Yellow beats red.</p> <p>If both cards have the same colour than the winner is the card with the highest number.</p> <p>If both cards have the same colour and the same number then that round is a draw.</p> <p>The winner of the game is the person with the most cards.</p> <hr> <pre><code>from random import shuffle from time import sleep from random import randint from FileFunctions import * # Card index constants COLOUR = 0 NUMBER = 1 # Colour constants RED = 'red' BLACK = 'black' YELLOW = 'yellow' # Player constants DRAW = 'draw' PLAYER1 = '1' PLAYER2 = '2' def main(): login() menu_loop = True while menu_loop: print('=======================================\n') print('1 - Play game') print('2 - Create new deck') print('3 - Change the speed of the game') print('4 - View the leaderboard') print('5 - Quit') menu_option = input('\nEnter menu option: ') print('\n=======================================') if menu_option == '1': play_game() input('Press enter to continue.') elif menu_option == '2': new_deck_menu() input('Press enter to continue.') elif menu_option == '3': change_speed() input('Press enter to continue.') elif menu_option == '4': top5 = read_top5() display_leaderboard(top5) input('Press enter to continue.') elif menu_option == '5': print('Goodbye.') menu_loop = False else: print('\nPlease choose a number from the menu.\n') def login(): # The passcode (for now) is 'Python'. password = get_passcode() valid = False while not valid: password_attempt = input('Enter password: ') if password_attempt == password: print('Welcome.') valid = True else: print('Incorrect passcode.') print('\n\n') # Returns a tuple containing a colour and a number def new_card(colour): return (colour, randint(1, 10)) # Creates a new random deck def new_random_deck(): deck = [] for i in range(10): deck.append(new_card(RED)) deck.append(new_card(BLACK)) deck.append(new_card(YELLOW)) write_deck(deck) # Returns the name of the winner of the game and the winning cards as a tuple def play_game(): print('\n\n') valid = False while not valid: player1_name = input('Enter player 1\'s name: ') if '_' in player1_name: print('Names cannot contain underscores.') else: valid = True valid = False while not valid: player2_name = input('Enter player 2\'s name: ') if '_' in player2_name: print('Names cannot contain underscores.') elif player2_name == player1_name: print('Player 1 and player 2 must have different names.') else: valid = True deck = load_deck() round_delay = load_round_delay() play_again = True while play_again: player1_cards = [] player2_cards = [] # Read the deck from the deck file. shuffle(deck) game_round = 1 print('\n\n') while len(deck) &gt; 0: sleep(round_delay) player1_card = deck[-1] player2_card = deck[-2] deck.pop() deck.pop() print('ROUND', game_round, '\n') display_cards(player1_card, player2_card) winner = compare_cards(player1_card, player2_card) if winner == PLAYER1: print('\nWinner:', player1_name) elif winner == PLAYER2: print('\nWinner:', player2_name) else: print('\nWinner: draw') print('\n\n') if winner == PLAYER1: player1_cards.append(player1_card) player1_cards.append(player2_card) elif winner == PLAYER2: player2_cards.append(player1_card) player2_cards.append(player2_card) game_round += 1 if len(player1_cards) &gt; len(player2_cards): winner = player1_name winning_cards = player1_cards elif len(player1_cards) &lt; len(player2_cards): winner = player2_name winning_cards = player2_cards else: winner = DRAW if winner != DRAW: write_name_and_cards(winner, winning_cards) print('Winner of game:', winner) valid = False while not valid: yes_or_no = input('\nWould you like to play again? (y/n)').lower() valid = True if yes_or_no == 'n': play_again = False elif yes_or_no != 'y': print('Please answer with \'y\' or \'n\'.') valid = False print('\n\n') # Returns the winner of 2 cards def compare_cards(card1, card2): if card1[COLOUR] == card2[COLOUR]: if card1[NUMBER] &gt; card2[NUMBER]: return PLAYER1 elif card1[NUMBER] &lt; card2[NUMBER]: return PLAYER2 else: return DRAW else: if card1[COLOUR] == RED: return PLAYER1 if card2[COLOUR] == BLACK else PLAYER2 elif card1[COLOUR] == BLACK: return PLAYER1 if card2[COLOUR] == YELLOW else PLAYER2 elif card1[COLOUR] == YELLOW: return PLAYER1 if card2[COLOUR] == RED else PLAYER2 def display_cards(card1, card2): print('=======================================') print('PLAYER 1 PLAYER 2') print('=======================================') print('colour:', card1[COLOUR], end='') space_length = 17 - len(card1[COLOUR]) print(space_length * ' ', end='') print('colour:', card2[COLOUR]) print('number:', card1[NUMBER], end='') space_length = 17 - len(str(card1[NUMBER])) print(space_length * ' ', end='') print('number:', card2[NUMBER]) def display_leaderboard(players): print('\nLEADERBOARD') for i in range(len(players)): score = len(players[i]) - 1 print(str(i+1), ')', players[i][0], '-', score) print('\n') def new_deck_menu(): print('\n\n') valid = False while not valid: yes_or_no = input('\nCreating a new deck will overwrite the current deck. Do you wish to proceed? (y/n)') yes_or_no = yes_or_no.lower() valid = True if yes_or_no == 'y': new_random_deck() print('\nThe new deck has been created.') elif yes_or_no == 'n': print('\nCreation of new deck has been cancelled.') else: print('\nPlease answer with \'y\' or \'n\'.') valid = False print('\n\n') def change_speed(): valid = False current_delay = load_round_delay() while not valid: print('The current round delay is %f.' % (current_delay)) yes_or_no = input('Are you sure you want to change the speed of the game? (y/n)').lower() valid = True if yes_or_no == 'y': global round_delay input_loop = True while input_loop: input_loop = False try: seconds = float(input('\nEnter delay between each round in seconds: ')) except ValueError: input_loop = True print('Please enter a float or an integer.') write_round_delay(seconds) print('\nThe new round delay has been saved.') elif yes_or_no == 'n': print('\nChanging of game speed has been cancelled.') else: print('\nPlease answer with \'y\' or \'n\'.\n') valid = False if __name__ == '__main__': main() </code></pre> <p>FileFunctions.py:</p> <pre><code>from pickle import load EmptyLine = IndexError # Writes deck to deck.txt def write_deck(deck_array): with open('deck.txt', 'w') as deck_file: for card in deck_array: deck_file.write(card[0]) deck_file.write(',') deck_file.write(str(card[1])) deck_file.write('\n') def load_deck(): deck_array = [] with open('deck.txt', 'r') as deck_file: deck_text = deck_file.read() deck_text = deck_text.split('\n') for card_string in deck_text: try: card = card_string.split(',') card[1] = int(card[1]) deck_array.append( (card[0], card[1]) ) except EmptyLine: continue return deck_array def get_passcode(): with open('passcode.bin', 'rb') as passcode_file: return load(passcode_file) # Writes name and cards to win.txt def write_name_and_cards(name, cards): with open('win.txt', 'a') as win_file: win_file.write(name) for card in cards: win_file.write('\n') win_file.write(card[0]) win_file.write(',') win_file.write(str(card[1])) win_file.write('_') # Returns the top 5 players as a tuple def read_top5(): with open('win.txt', 'r') as win_file: players = win_file.read() players = players.split('_') for i in range(len(players)): players[i] = players[i].split('\n') try: while players[-1] == ['']: players.pop() except IndexError: # The players array might be empty pass # The players variable now stores a 2d array top5 = [] maximum = 5 if len(players) &gt;= 5 else len(players) while len(top5) &lt; maximum: index_of_highest = 0 for i in range(len(players)): if len(players[i]) &gt; len(players[index_of_highest]): index_of_highest = i top5.append(players[index_of_highest]) players.pop(index_of_highest) return top5 def write_round_delay(seconds): with open('round_delay.txt', 'w') as rd_file: rd_file.write(str(seconds)) def load_round_delay(): with open('round_delay.txt', 'r') as rd_file: return float(rd_file.read()) </code></pre> <p>deck.txt:</p> <pre><code>red,6 black,5 yellow,6 red,9 black,8 yellow,8 red,5 black,9 yellow,3 red,7 black,2 yellow,9 red,10 black,2 yellow,3 red,5 black,3 yellow,6 red,6 black,3 yellow,7 red,2 black,1 yellow,5 red,3 black,1 yellow,10 red,6 black,10 yellow,2 </code></pre> <p>round_delay.txt:</p> <pre><code>1 </code></pre> <p>win.txt is empty at first.</p> <p>passcode.bin contains the string "Python"</p> <p>Edit: How can I improve the code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T11:34:29.673", "Id": "394752", "Score": "0", "body": "I would recommend that you read [Simon's guide to a good question](https://codereview.meta.stackexchange.com/a/6429/31562), you currently don't have a specific question. Are you ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T17:07:59.623", "Id": "204639", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "450 line Python card game" }
204639
<p>Currently I'm learning OOP and meanwhile I'm trying to keep the SOLID principles. Is it right to inject dependency (<code>GenName</code> - generate file name) on File constructor (for example if someone else wants to write an <code>Image</code> class but he does not know about required dependency injection in constructor)? Does it violate open/close and single responsibility principles?</p> <pre><code>interface iUpload { public function getName(); } interface iGenName { public function genName($file); } class GenName implements iGenName { public function genName($file) { // generate and return file name return 'filename.txt'; } } class File implements iUpload { protected $genName; protected $file; //file obj public function __construct(iGenName $genName) { $this-&gt;genName = $genName; } public function getName() { return $this-&gt;genName-&gt;genName($this-&gt;file); } } class Upload { protected $uploadContent; public function __construct(iUpload $uploadContent) { $this-&gt;uploadContent = $uploadContent; } public function upload() { // upload file return save($this-&gt;uploadContent-&gt;getName(),...,...); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T11:06:00.630", "Id": "394747", "Score": "0", "body": "This is not really a question for code review. For one your code doesn't do much of anything, nor can we even run it. See: https://codereview.stackexchange.com/help/on-topic I al...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T17:19:40.600", "Id": "204641", "Score": "2", "Tags": [ "php", "object-oriented", "dependency-injection" ], "Title": "Dependency Inversion in constructor" }
204641
<p>Learning how to use function generators in Python I practiced with the following code that finds the next permutation of a word and then uses this new word as input for the next one until there are no further permutations. So for example 'dbac' is followed by 'dacb' followed by 'dabc' and so on.</p> <p>Basically two questions: 1) the use of two times <code>break</code> to stop the two for-loops is there a better way to break out of the loops, and 2) the final part <code>try: return finally: StopIteration</code> is this a proper construction? </p> <pre><code>def nextperm(word): stoploop = True while stoploop: wordlist = [*word] length = len(wordlist)-1 stoploop = False for index_1 in range(length-1, -1, -1): for index_2 in range(length, index_1-1, -1): if wordlist[index_2] &lt; wordlist[index_1]: wordlist[index_2], wordlist[index_1] = wordlist[index_1], wordlist[index_2] _first = wordlist[0:index_1+1] _second = wordlist[-1:index_1:-1] wordlist = _first + _second word = ''.join(wordlist) stoploop = True yield word break if stoploop: break try: return print('no further permutation possible') finally: raise StopIteration </code></pre> <p>so if you do:</p> <pre><code>for i, word in enumerate(nextperm('dcba')): print(f'{i:2}, {word}') </code></pre> <p>output is:</p> <pre><code> 0, dcab 1, dbca 2, dbac 3, dacb 4, dabc 5, cdba 6, cdab 7, cbda 8, cbad 9, cadb 10, cabd 11, bdca 12, bdac 13, bcda 14, bcad 15, badc 16, bacd 17, adcb 18, adbc 19, acdb 20, acbd 21, abdc 22, abcd no further permutation possible </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T09:39:18.093", "Id": "394737", "Score": "1", "body": "is the order of permutations important? And why not just use [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations)" }, { "Co...
[ { "body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>The name <code>nextperm</code> is misleading as (i) it generates permutations that <em>precede</em> its argument; (ii) it generates multiple permutations, not just one. So a name like <code>preceding_permutations</code> would be clearer.</p></li>\n<li><p>There is no...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T18:23:09.763", "Id": "204643", "Score": "1", "Tags": [ "python", "python-3.x", "combinatorics" ], "Title": "Python finding next word permutation with function generator" }
204643
<p>I am learning circular / cyclic buffer using this <a href="https://embeddedartistry.com/blog/2017/4/6/circular-buffers-in-cc" rel="nofollow noreferrer">link</a>. Here is the code that I have written so far:</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;cstddef&gt; class CircularBuffer { std::unique_ptr&lt;int[]&gt; u_ptr; std::size_t head; std::size_t tail; const std::size_t capacity; bool full_v; public: CircularBuffer(std::size_t); void reset(); bool full() const; bool empty() const; std::size_t size() const; void write(int); int read(); }; // Constructor // Set the capacity via initializer list because it is const CircularBuffer::CircularBuffer(std::size_t space):capacity{space} { u_ptr = std::unique_ptr&lt;int[]&gt;(new int[space]); head = 0; tail = 0; full_v = false; } // Reset the Buffer void CircularBuffer::reset() { head = 0; tail = 0; full_v = false; u_ptr[head] = int{}; } // Check if buffer is full bool CircularBuffer::full() const { return full_v; } // Check if buffer is empty bool CircularBuffer::empty() const { return (!full_v &amp;&amp; head == tail); } // Return the size of the buffer std::size_t CircularBuffer::size() const { if(full_v) { return capacity; } if(head &gt;= tail) { return head - tail; } else { return capacity - (tail - head); } } // Write values into the buffer void CircularBuffer::write(int data) { u_ptr[head] = data; head = (head + 1) % capacity; if(full_v) { tail = (tail + 1) % capacity; } full_v = (head == tail); } // Read from buffer int CircularBuffer::read() { if(this -&gt; empty()) { return int{}; } int ret_val = u_ptr[tail]; full_v = false; tail = (tail + 1) % capacity; return ret_val; } int main() { CircularBuffer cb{10}; std::cout &lt;&lt; "Empty: " &lt;&lt; cb.empty() &lt;&lt; "\n"; for(int i = 0; i &lt; 10; i++) { cb.write(i); } std::cout &lt;&lt; "Full: " &lt;&lt; cb.full() &lt;&lt; "\n"; std::cout &lt;&lt; "Read: " &lt;&lt; cb.read() &lt;&lt; "\n"; std::cout &lt;&lt; "Full: " &lt;&lt; cb.full() &lt;&lt; "\n"; std::cout &lt;&lt; "Empty: " &lt;&lt; cb.empty() &lt;&lt; "\n"; std::cout &lt;&lt; "Size: " &lt;&lt; cb.size() &lt;&lt; "\n"; cb.write(35); std::cout &lt;&lt; "Size: " &lt;&lt; cb.size() &lt;&lt; "\n"; std::cout &lt;&lt; "Read: " &lt;&lt; cb.read() &lt;&lt; "\n"; std::cout &lt;&lt; "Size: " &lt;&lt; cb.size() &lt;&lt; "\n"; cb.reset(); std::cout &lt;&lt; "Size: " &lt;&lt; cb.size() &lt;&lt; "\n"; return 0; } </code></pre> <ol> <li><p>Is the implementation correct? What are the shortcomings that can be fixed?</p></li> <li><p>I see that the original reference uses a <code>mutex</code> object and uses lock. Is such an approach used with all data structures? If not, is there a reason why that has been used here?</p></li> </ol>
[]
[ { "body": "<p>Your ringbuffer has a compile time size, so it would be appropriate to make it a template class rather than simply passing it as an argument to the constructor. You never plan to change it anyway?</p>\n\n<pre><code>template&lt;size_t bufSize&gt;\nclass CircularBuffer\n</code></pre>\n\n<p>That lead...
{ "AcceptedAnswerId": "204646", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T18:27:57.850", "Id": "204644", "Score": "3", "Tags": [ "c++", "pointers", "locking", "circular-list" ], "Title": "Circular / Cyclic Buffer implementation" }
204644
<p>I'm aware that people have implemented password/passphrase generators before, but I still went ahead and wrote my own, which I actually use for my own passwords and/or phrases.</p> <p>By "secure", I mean that the strength of the results is maintained even if an attacker knows all of the following:</p> <ul> <li>the list of words used,</li> <li>the set of alphanumeric characters used,</li> <li>that this program was used to generate the result,</li> <li>what the source code of this program looks like, and/or</li> <li>the amount of entropy produced by the process</li> </ul> <p>In other words (paraphrasing Shannon), the attacker knows the whole system. The program generates both passphrases and passwords.</p> <p>The passphrase is generated from a words list included as part of the installation of this program. The words list was created by the Electronic Frontier Foundation (EFF), and can be found <a href="https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases" rel="nofollow noreferrer">here</a>. There are 7776 words in the list, meant for diceware. (The only processing I did to the file was to remove the left column with the numbers and leave the words only.)</p> <p>Passwords are generated from ASCII lower/upper-case characters, digits, and punctuation symbols, for a total 94 symbols.</p> <p>The code is divided into several modules:</p> <ul> <li><code>makesecret</code>: the main program;</li> <li><code>validators</code>: allows <code>makesecret</code> to validate some inputs with <code>argparse</code>;</li> <li><code>providers</code>: classes that generate the actual secrets, e.g. <code>PasswordProvider</code>, <code>PassphraseProvider</code>; (I avoided using <code>Generator</code> to prevent ambiguity when talking about actual python generators)</li> <li><code>analyzers</code>: provides a simple analysis of the generated result to the user in a way they can understand (e.g. average time required to guess it, etc)</li> </ul> <p>There's also a <code>tests/</code> package with some automated test cases, but I've chosen not to include those here. (If you'd like to see them, just post a comment to that effect.)</p> <p>The source code is below. While anything is fair game, I'm primarily interested in the following:</p> <ul> <li>any issues with my stated assumptions regarding security;</li> <li>any issues with the implementation that weakens the results generated by the program;</li> <li>any issues that might cause problems in other non-GNU+Linux platforms (e.g. it doesn't work in Windows/macOS unless _____, etc)</li> <li>other design/implementation improvements or details I may've missed</li> </ul> <hr> <h2><code>makesecret.py</code></h2> <p>This is the main program. It parses CLI arguments, validates them using a validator, and relies on providers to generate the secret.</p> <pre><code>#!/usr/bin/env python3 '''Generate cryptographically strong passphrases and passwords''' import sys import argparse as ap from pkg_resources import resource_filename from makesecret.providers import PasswordProvider, PassphraseProvider from makesecret.analyzers import analyze_secret from makesecret.validators import valid_positive_number _epilog = 'IMPORTANT: Read the documentation to properly understand ' \ ' how to use this program. In GNU+Linux, you can use ' \ '`pydoc3 makesecret`. In Windows you may use `py -m pydoc ' \ 'makesecret`.' _providers = { 'password' : PasswordProvider, 'passphrase': PassphraseProvider } def parse_arguments() -&gt; ap.Namespace: '''Parse CLI arguments with an `ArgumentParser`.''' parser = ap.ArgumentParser( description='A secure password and passphrase generator', formatter_class=ap.ArgumentDefaultsHelpFormatter, epilog=_epilog ) parser.add_argument( '--brute-force', metavar='ATTEMPTS', type=valid_positive_number, dest='attacks_per_sec', default=10**9, help='assumed guess attempts per second' ) parser.add_argument( '--min-entropy', metavar='BITS', type=valid_positive_number, default=60, dest='min_entropy_bits', help='minimum amount of entropy bits to consider result acceptable' ) parser.add_argument( '--precision', metavar='PLACES', dest='precision', type=valid_positive_number, default=4, help='the number of decimal places to show during analysis' ) subparser = parser.add_subparsers( dest='command', title='subcommands', help='additional help for specific subcommands' ) subparser.required = True setup_passphrase_parser(subparser) setup_password_parser(subparser) return parser.parse_args() def setup_passphrase_parser(subparser: ap.ArgumentParser) -&gt; None: '''Setup passphrase-specific parsing options.''' parser = subparser.add_parser( 'passphrase', formatter_class=ap.ArgumentDefaultsHelpFormatter, epilog=_epilog, help='help for generating passphrases' ) parser.add_argument( '--choose', metavar='COUNT', type=valid_positive_number, dest='user_choice_cnt', default=6, help='the number of words to choose from the words list' ) parser.add_argument( '--words-list', metavar='FILE', type=str, dest='wordlist_file', default=resource_filename('makesecret', 'data/eff_wordlist.db'), help='a text file with a long list of words (one per line)' ) parser.add_argument( '--analyze', action='store_true', dest='show_analysis', help='show a simple analysis of your new password/passphrase' ) def setup_password_parser(subparser: ap.ArgumentParser) -&gt; None: '''Setup password-specific parsing options.''' parser = subparser.add_parser( 'password', formatter_class=ap.ArgumentDefaultsHelpFormatter, epilog=_epilog, help='help for generating passwords' ) parser.add_argument( '--choose', metavar='COUNT', type=valid_positive_number, dest='user_choice_cnt', default=12, help='the number of characters to choose from the alphanumeric set' ) parser.add_argument( '--analyze', action='store_true', dest='show_analysis', help='show a simple analysis of your new password/passphrase' ) def main(): args = parse_arguments() provider = _providers[args.command](args) secret = provider.generate() print(str(secret)) if args.show_analysis: msg = analyze_secret( secret=secret, user_choice_cnt=args.user_choice_cnt, attacks_sec=args.attacks_per_sec, min_entropy=args.min_entropy_bits, precision=args.precision ) print(msg, file=sys.stderr) sys.exit(0) if __name__ == '__main__': main() </code></pre> <h2><code>validators.py</code></h2> <p>Validates that CLI arguments that should be positive numbers (e.g. minimum entropy bits, number of words/chars to choose, etc) are actually positive.</p> <pre><code>import argparse as ap def valid_positive_number(s: str) -&gt; int: '''Validates that input is a positive integer.''' msg = 'value must be a positive integer' try: n = int(s) if n &lt;= 0: raise ap.ArgumentTypeError(msg) return n except ValueError: raise ap.ArgumentTypeError(msg) </code></pre> <h2><code>providers.py</code></h2> <p>The providers are the classes that actually generate the secrets. A <code>Secret</code> class is used to represent the result.</p> <pre><code>import argparse as ap from secrets import choice from string import ascii_letters, digits, punctuation from abc import ABCMeta, abstractmethod from typing import Text class Secret: '''A class to store the result returned by a provider.''' def __init__(self, result: Text, pool_size: int): self._result = result self._choice_pool_size = pool_size @property def result(self) -&gt; Text: return self._result @property def choice_pool_size(self) -&gt; int: return self._choice_pool_size def __str__(self): return self.result class _SecretProvider(metaclass=ABCMeta): '''ABC for providers.''' @abstractmethod def generate(self) -&gt; Secret: raise NotImplementedError() class PasswordProvider(_SecretProvider): '''A generator for passwords based on ascii symbols.''' def __init__(self, args: ap.Namespace): self._args = args def generate(self) -&gt; Secret: '''Generate a password using a set of alphanumeric symbols. The alphanumeric set includes lower/upper-case letters, numbers, and punctuation symbols. ''' options = ascii_letters + digits + punctuation return Secret( ''.join(choice(options) for i in range(self._args.user_choice_cnt)), len(options) ) class PassphraseProvider(_SecretProvider): '''A generator for word-based passphrases from word lists.''' def __init__(self, args: ap.Namespace): self._args = args def generate(self) -&gt; Secret: '''Generate a passphrase from a list of common words. The words list comes from the Electronic Frontier Foundation (EFF) and it's made up of common words, so it should be fairly easy to remember. ''' with open(self._args.wordlist_file, 'r') as words: options = [word.strip() for word in words] return Secret( ' '.join(choice(options) for i in range(self._args.user_choice_cnt)), len(options) ) </code></pre> <h2><code>analyzers.py</code></h2> <p>Provides an analysis of a given result in a way that's more user-friendly and easy to understand. For example, stating the amount of entropy is unlikely to be meaningful to the user, so I also provide information in terms of "time to brute-force" at an assumed attack rate.</p> <pre><code>import argparse as ap from typing import Text from os import linesep as eol from math import log2 from makesecret.providers import Secret def analyze_secret(**kw) -&gt; Text: '''Analyze results.''' secret = kw['secret'] choice_cnt = kw['user_choice_cnt'] attacks_sec = kw['attacks_sec'] min_entropy = kw['min_entropy'] precision = kw['precision'] entropy_base = secret.choice_pool_size entropy_bits = log2(entropy_base) entropy_total = entropy_bits * choice_cnt tries_to_crack = int(2**(entropy_total-1)) # average # average time to crack the user's result, assuming # `attacks_sec` attempts per second crack_secs = tries_to_crack / attacks_sec crack_hours = crack_secs / 3600 crack_days = crack_hours / 24 crack_weeks = crack_days / 7 crack_years = crack_days / 365.25 crack_decades = crack_years / 10 crack_centuries = crack_years / 10**2 crack_millenia = crack_years / 10**3 crack_millions = crack_years / 10**6 crack_billions = crack_years / 10**9 prec = precision msg = eol msg += 'Facts About Your Result' + eol msg += ' Selection Pool : {:,}'.format(entropy_base) + eol msg += ' Entropy (bits per choice) : {:,.{p}f}'.format(entropy_bits, p=prec) + eol msg += ' Entropy (bits overall) : {:,.{p}f}'.format(entropy_total, p=prec) + eol + eol msg += 'Attack: Brute-Force ({:,} attemps/sec assumed)'.format(attacks_sec) + eol msg += ' Guess Attempts (avg.): {:,}'.format(tries_to_crack) + eol msg += ' Time to Crack (avg.) :' + eol msg += ' Seconds : {:,.{p}f}'.format(crack_secs, p=prec) + eol msg += ' Hours : {:,.{p}f}'.format(crack_hours, p=prec) + eol msg += ' Days : {:,.{p}f}'.format(crack_days, p=prec) + eol msg += ' Weeks : {:,.{p}f}'.format(crack_weeks, p=prec) + eol msg += ' Years : {:,.{p}f}'.format(crack_years, p=prec) + eol msg += ' Decades : {:,.{p}f}'.format(crack_decades, p=prec) + eol msg += ' Centuries : {:,.{p}f}'.format(crack_centuries, p=prec) + eol msg += ' Millenia : {:,.{p}f}'.format(crack_millenia, p=prec) + eol msg += ' Mega-Annum: {:,.{p}f}'.format(crack_millions, p=prec) + eol msg += ' Giga-Annum: {:,.{p}f}'.format(crack_billions, p=prec) + eol msg += eol msg += ' Strength: {}'.format( 'Good' if entropy_total &gt;= min_entropy else 'Poor' ) + eol return msg </code></pre> <h2><code>setup.py</code></h2> <p>This is the installation script to allow <code>pip3 install git+https://&lt;REPO-URL&gt;/makesecret.git</code> or <code>pip3 install .</code> if they've simply downloaded the compressed archive.</p> <pre><code>#!/usr/bin/env python3 from os.path import join, dirname from setuptools import setup, find_packages REQUIRED_PYTHON = (3, 6) def readme(): with open(join(dirname(__file__), 'README.md')) as f: return f.read() setup( name='makesecret', version='0.1.4', python_requires='&gt;={}.{}'.format(*REQUIRED_PYTHON), description='A generator for secure passwords and passphrases.', long_description=readme(), long_description_content_type='text/markdown', author='&lt;my-name-here&gt;', author_email='&lt;my-email-here&gt;', maintainer='&lt;my-name-here&gt;', maintainer_email='&lt;my-email-here&gt;', url='&lt;my-repo-url-here&gt;', packages=find_packages(), entry_points={ 'console_scripts': [ 'makesecret=makesecret.entrypoints:main' ], }, data_files=[ ('data', ['makesecret/data/eff_wordlist.db']) ], include_package_data=True, keywords='secret password passphrase security cryptography entropy', classifiers=( # https://pypi.org/classifiers/ 'Development Status :: 1 - Planning', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Operating System :: POSIX', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 Only', 'Topic :: Security', 'Topic :: Security :: Cryptography', 'Topic :: Utilities' ), ) </code></pre> <h2>Example Runs</h2> <p>A few examples of what the program looks like during use.</p> <pre class="lang-none prettyprint-override"><code>$ makesecret -h usage: makesecret [-h] [--brute-force ATTEMPTS] [--min-entropy BITS] [--precision PLACES] {passphrase,password} ... A secure password and passphrase generator optional arguments: -h, --help show this help message and exit --brute-force ATTEMPTS assumed guess attempts per second (default: 1000000000) --min-entropy BITS minimum amount of entropy bits to consider result acceptable (default: 60) --precision PLACES the number of decimal places to show during analysis (default: 4) subcommands: {passphrase,password} additional help for specific subcommands passphrase help for generating passphrases password help for generating passwords IMPORTANT: Read the documentation to properly understand how to use this program. In GNU+Linux, you can use `pydoc3 makesecret`. In Windows you may use `py -m pydoc makesecret`. $ makesecret passphrase --analyze affiliate jovial stingray demotion rectified strut Facts About Your Result Selection Pool : 7,776 Entropy (bits per choice) : 12.9248 Entropy (bits overall) : 77.5489 Attack: Brute-Force (1,000,000,000 attemps/sec assumed) Guess Attempts (avg.): 110,536,959,860,366,712,504,320 Time to Crack (avg.) : Seconds : 110,536,959,860,366.7188 Hours : 30,704,711,072.3241 Days : 1,279,362,961.3468 Weeks : 182,766,137.3353 Years : 3,502,704.8908 Decades : 350,270.4891 Centuries : 35,027.0489 Millenia : 3,502.7049 Mega-Annum: 3.5027 Giga-Annum: 0.0035 Strength: Good $ makesecret password --analyze E%!ACbedCgm# Facts About Your Result Selection Pool : 94 Entropy (bits per choice) : 6.5546 Entropy (bits overall) : 78.6551 Attack: Brute-Force (1,000,000,000 attemps/sec assumed) Guess Attempts (avg.): 237,960,157,407,128,324,145,152 Time to Crack (avg.) : Seconds : 237,960,157,407,128.3125 Hours : 66,100,043,724.2023 Days : 2,754,168,488.5084 Weeks : 393,452,641.2155 Years : 7,540,502.3642 Decades : 754,050.2364 Centuries : 75,405.0236 Millenia : 7,540.5024 Mega-Annum: 7.5405 Giga-Annum: 0.0075 Strength: Good $ makesecret password --choose 6 --analyze I,l!O9 Facts About Your Result Selection Pool : 94 Entropy (bits per choice) : 6.5546 Entropy (bits overall) : 39.3275 Attack: Brute-Force (1,000,000,000 attemps/sec assumed) Guess Attempts (avg.): 344,934,890,528 Time to Crack (avg.) : Seconds : 344.9349 Hours : 0.0958 Days : 0.0040 Weeks : 0.0006 Years : 0.0000 Decades : 0.0000 Centuries : 0.0000 Millenia : 0.0000 Mega-Annum: 0.0000 Giga-Annum: 0.0000 Strength: Poor </code></pre> <h2>Built-in Documentation</h2> <p>I'm interested in trying to get the user to have a better <em>understanding</em> of what makes a generator secure and so on, so this is the built-in documentation that is shown to the user by <code>pydoc3 makesecret</code>.</p> <pre class="lang-none prettyprint-override"><code>'''A secrets generator to get strong passwords and passphrases This program locally generates, but does NOT store, user secrets, such as passwords and passphrases, in a way that is cryptographically strong and secure. It is NOT a password manager. Here are the simplest ways to use it for passwords and passphrases: $ makesecret password ... $ makesecret passphrase ... Here is how to get help on available options: $ makesecret --help ... $ makesecret password --help ... $ makesecret passphrase --help ... The passphrase is generated from a words list included as part of the installation of this program. The words list was created by the Electronic Frontier Foundation (EFF), and can be found at the following URL: https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases The security and strength of this generator is maintained even if an attacker knows any and/or all of the following: * the list of words used, * the set of alphanumeric characters used, * that this program was used to generate the result, * what the source code of this program looks like, and/or * the amount of entropy produced by the process Since this program only generates, but does NOT store, the secret, this means that SECURE STORAGE of the secrets IS YOUR RESPONSIBILITY. These are the primary use-cases considered for this tool's implementation and some recommendations for using it in a way that reduces the chances of you unknowingly compromising your own security. It is assumed that you have taken, or will take, the following precautions beforehand: * the system is under your full control and is not shared/public, * the system is not infected with malware or under surveillance, * you have positioned your display to avoid shoulder surfers, * you are using secure storage (e.g. a password manager, encrypted file system, encrypted browser sync services, etc.) The strength of passwords and passphrases is measurable, in terms of the amount of uncertainty, unpredictability, or "randomness" that is built into the process that generates the result, and not by the result itself. In other words, the strength of a result is not determined by its own properties such as length, how "complicated" or "random" it may appear to the human eye, etc. Rather, it is determined by the amount of (Shannon) Entropy in the process used to generate it. In general, Shannon Entropy is measured in terms of the number of options available to choose from, all of which MUST have the same probability of being chosen. In short, selection must be TRULY random. But this presents a problem, because computers are not truly random, they're only pseudo- random because computers are determistic. This means that using a Cryptographically Secure Pseudorandom Number Generator (CSPRNG) is really critical, and that anything that changes the probabilities when choosing alternatives reduces the amount of entropy that can be obtained and weakens the whole system. It is also based on a logarithmic scale, using bits as the unit of measure.[1] For example, consider a fair coin. The coin provides only 2 possible outcomes, head or tails, so we say that the the amount of entropy `S = 2`, because that is the total number of possible choices. To convert this to the actual measurement in bits, we take the base-2 logarithm of 2, i.e. S = 2 E = log₂(S) = 1 which means there is only 1 bit of entropy. Note that this is only for a single throw. Every additional throw adds 1 more bit of entropy to the generated sequence, so a sequence of length `N` would have `N` bits of entropy. Unfortunately, a process with this little entropy would require too long a sequence to make it practical. But we can do better. We need to increase the number of equiprobable alternatives, and thus, the number of entropy bits per selection attempt. Consider a fair 8-sided die. In this case: S = 8 E = log₂(S) = 3 That is, the are 8 (or 2³) equally probable outcomes for each throw of the die. And since `2³ = 8` and `log₂(2³) = 3`, then this shows that the die offers 3 bits of entropy per throw. In more practical terms, this means that, while in the first example you would need 12 coin throws to generate a 12-bit sequence, in the second example you can generate a sequence with the same 12-bit "strength" with only 4 throws of the die. By default, `makesecret` generates passwords that are 12 characters long from a set of 94 symbols including lower/upper-case letters, digits, and special characters (e.g. punctuation). This means: S = 94 E = log₂(S) ≈ 6.6 That is, there are about 6.6 bits of entropy per selection. Since the default length is 12 characters, that means the total amount of entropy bits is: E = 6.6 * 12 ≈ 78.7 which, assuming 1 Billion attempts per second, would take an average of 7.5 Million years to brute-force. On the other hand, things are different when generating passphrases. The passphrases are based on a list of common words with 7776 entries in it. This means: S = 7776 E = log₂(S) ≈ 12.9 showing about 12.9 bits of entropy per selection. Since the default number of words is 6, that means the total amount of entropy is: E = 6 * 12.9 ≈ 77.4 which, under the same assumptions as before, would take an average of 3.5 Million years to brute-force. If you think six words is too much to remember, you can choose a different number. For example: $ makesecret passphrase --choose 5 The consequence of this would be: E = 5 * 12.9 ≈ 64.6 requiring an average of 4.5 centuries to crack under the same conditions. To display an analysis of your results, you can use: $ makesecret ... --analyze Note that all of this relies on selections being made randomly. If you generate a result using a non-random method or a PRNG that is not Crypto- graphically Secure, then the strength of your result is going to go down significantly. In fact, it could have no entropy/strength at all, being completely predictable; e.g. "correct horse battery staple"[2]. [1] This is similar to how the Richter Magnitude Scale for earthquakes works, but using base-2 logarithms instead of base-10 logarithms. What this means is that, in the same way that an earthquake rated as a 5 in the scale is 10 times stronger than a 4 and 100 times stronger than a 3 (because it is base-10), a process with 5 bits of entropy has twice as many choices as one with 4 bits and four times as many choices as one with 3 bits (because it is base-2). In other words, for every bit of entropy that you want to add, you must duplicate the total number of possible choices and make sure that every choice has the same odds of of being selected. [2] https://xkcd.com/936 ''' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T16:30:27.047", "Id": "396601", "Score": "0", "body": "Since this was posted, I've moved the `Secret` class from the `providers` module over to a new `models` module, i.e. `models.Secret`, and updated the rest of the codebase." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T21:25:06.057", "Id": "204648", "Score": "5", "Tags": [ "python", "python-3.x", "security" ], "Title": "Secure Password and Passphrase Generator in Python 3" }
204648
<p>After having rewritten this lexer for the N<sup>th</sup> time, I finally feel confident enough to show it publicly. I'm looking for advices to improve my code.</p> <p>The <strong>lexer</strong> you are going to see is the first step of a WIP 3-step parser for my <em>"Obganism"</em> language:</p> <ol> <li>Lexing: from <code>String</code> to <code>List&lt;Token&gt;</code>.</li> <li>Refining: from <code>List&lt;Token&gt;</code> to a reduced <code>List&lt;Token&gt;</code>.</li> <li>Parsing: from <code>List&lt;Token&gt;</code> to <code>List&lt;Object&gt;</code>.</li> </ol> <h2>The Parsed Language</h2> <p>The language being parsed is designed to describe objects, thoses being seen as a bag of properties, operations, and events. Depending on where you come from, it may remind you a JSON schema, or a C++ structure header:</p> <pre><code>potato { color: string -- ( one of("yellow", "orange", "purple") ) firmness: float -- ( range(0.0, 1.0) ) is peeled: bool -- ( default(false) ) ---- peel(): void } </code></pre> <p>In this example, <code>potato</code> is a type of object &mdash; diclaimer: I'm not a potato domain expert.</p> <p>Here is an express guide to the syntax:</p> <ul> <li>Everything related to this type seats in the <em>body</em> of its definition, surrounded by <code>{</code> and <code>}</code>.</li> <li><code>color</code>, <code>firmness</code> and <code>is peeled</code> &mdash; spaces are allowed in names &mdash; are <em>properties</em> of a <code>potato</code>.</li> <li>They are respectively of type <code>string</code>, <code>float</code> and <code>bool</code>; <em>types</em> are introduced using <code>:</code>.</li> <li><code>--</code> introduces a list of <em>modifiers</em>, i.e. metadata.</li> <li><code>----</code> is the <em>section</em> separator; the first section is for properties, and the second section is for operations.</li> <li><code>peel</code> is an <em>operation</em>, i.e. a method callable on a <code>potato</code> object.</li> </ul> <p>Another tricky thing you may want to know is that commas (<code>,</code>) and line breaks are both considered as <em>breaks</em>, i.e. separators in the scope of a section; thus, the <code>color</code> property above could have been written in a multiline fashion:</p> <pre><code>color: string -- ( one of( "yellow" "orange" "purple" ) ) </code></pre> <h2>The Lexer Code</h2> <p>I am voluntarily excluding package declaration &amp; imports since everything is in the same package, as well as the <code>Token</code> type, which is a Kotlin <code>sealed class</code>, similar to an <em>enumeration with values</em> in Swift.</p> <pre><code>// CR FYI: 180 lines, 45 blank lines, 20 functions. val Char.isSpace: Boolean get() = this in " \t" val Char.isBreak: Boolean get() = this in "\n,\r" val Char.isNumeric: Boolean get() = this in "0123456789-." val Char.isAlphaNumeric: Boolean get() = this.toLowerCase() in "etaoinsrhdlucmfywgpbvkxqjz2301456789" val Char.isEscaper: Boolean get() = this == '\\' class CharCursor(val source: String) { var index: Int = 0 fun canPick(count: Int): Boolean = index + count &lt;= source.length fun pick(count: Int): String = source.substring(index, index + count) val pick: Char get() = source[index] fun canNext(count: Int): Boolean = index + 1 + count &lt;= source.length fun next(count: Int): String = source.substring(index + 1, index + 1 + count) val next: Char get() = source[index + 1] fun pickIs(guess: String): Boolean = canPick(guess.length) &amp;&amp; pick(guess.length) == guess fun pickIs(guess: Char): Boolean = canPick(1) &amp;&amp; pick == guess fun nextIs(guess: String): Boolean = canNext(guess.length) &amp;&amp; next(guess.length) == guess fun nextIs(guess: Char): Boolean = canNext(1) &amp;&amp; next == guess fun move(count: Int) { index += count } fun skipWhile(predicate: (Char) -&gt; Boolean): String { val start = index while (canPick(1) &amp;&amp; predicate(pick)) { move(1) } val end = index return source.substring(start, end) } fun skipUntil(predicate: (Char) -&gt; Boolean): String { return skipWhile { !predicate(it) } } } fun String.lex(): List&lt;Token&gt; { if (this.isEmpty() || all { it.isSpace }) { return emptyList() } val cursor = CharCursor(this) val tokens = mutableListOf&lt;Token&gt;() var token = cursor.lex() while (token != null) { tokens += token token = cursor.lex() } return tokens } fun CharCursor.lex(): Token? { skipWhile { it.isSpace } return if (canPick(1)) when { pick == ':' -&gt; { move(1); Token.TypeIntroducer } pick == '{' -&gt; { move(1); Token.BlockStart } pick == '}' -&gt; { move(1); Token.BlockEnd } pick == '(' -&gt; { move(1); Token.ListStart } pick == ')' -&gt; { move(1); Token.ListEnd } pick.isBreak -&gt; { move(1); Token.Break } pickIs("----") -&gt; { move(4); Token.SectionSeparator } pickIs("--") -&gt; { move(2); Token.ModifierListIntroducer } pick.isNumeric -&gt; lexNumber() pick.isAlphaNumeric -&gt; lexWord() pick.isEscaper -&gt; lexEscapedOfKeyword() pick == '"' -&gt; lexString() pick == '/' -&gt; lexRegExp() else -&gt; throw ParsingException("Encountered invalid symbol: `${pick}`.") } else { null } } fun CharCursor.lexString(): Token = Token.String(readDelimited('"')) fun CharCursor.lexRegExp(): Token = Token.RegExp(readDelimited('/')) fun CharCursor.readDelimited(delimiter: Char): String { move(1) // Skip first delimiter. val content = StringBuilder() do { val chunk = skipUntil { it == delimiter || it.isEscaper } content.append(chunk) if (canPick(1)) { if (pick == delimiter) { break } else when { // Pick is escaper by skipUntil. nextIs('\\') -&gt; { move(2); content.append('\\') } nextIs(delimiter) -&gt; { move(2); content.append(delimiter) } canNext(1) -&gt; { move(1); content.append('\\') } else -&gt; throw ParsingException("Encountered end of code snippet too early.") } } else { throw ParsingException("Encountered end of code snippet too early.") } } while (true) move(1) // Skip last delimiter. return content.toString() } fun CharCursor.lexWord(): Token { val word = skipWhile { it.isAlphaNumeric } return when (word) { "of", "Of", "oF", "OF" -&gt; Token.Word.OfKeyword else -&gt; Token.Word.NamePart(word) } } fun CharCursor.lexEscapedOfKeyword(): Token { move(1) // Skip escaper. skipWhile { it.isSpace || it.isBreak } if (canPick(2)) { val word = skipWhile { it.isAlphaNumeric } if (word == "of") { return Token.Word.NamePart("of") } else { throw ParsingException("Encountered invalid item: `\\` can only be used to escape the `of` keyword.") } } else { throw ParsingException("Encountered end of code snippet too early.") } } fun CharCursor.lexNumber(): Token { val number = skipWhile { it.isNumeric }.toNumber() return if (number is Int) { Token.Integer(number) } else { Token.Real(number.toFloat()) } } fun String.toNumber(): Number = try { if (this.matches(Regex("""^-?\d+\.\d+$"""))) { val floatValue = this.toFloat() if (floatValue == Float.POSITIVE_INFINITY || floatValue == Float.NEGATIVE_INFINITY) { throw ParsingException("Encountered invalid number: `${this}` is too large to be stored.") } floatValue } else { this.toInt() } } catch (error: NumberFormatException) { throw ParsingException("Encountered invalid number: `${this}`.", error) } </code></pre> <h2>See also</h2> <ul> <li><a href="https://github.com/Odepax/obganism/wiki/Language-Syntax-Specification/5c7a588b191466128fc8c5850ca6f1068223036f" rel="nofollow noreferrer">The parsed language's specs</a>.</li> <li><a href="https://github.com/Odepax/obganism-parser-java/tree/5cc4a0019174fecdb93c4257346cc81644cf0d8e/src" rel="nofollow noreferrer">The complete code and tests</a>, though there isn't much more in there than the lexer right now.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T16:41:08.097", "Id": "395547", "Score": "0", "body": "I feel like `is peeled: bool -- ( default(false) )` should look more like this: `peeled: bool`. The initialization syntax being used when not initializing to the default value." ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T21:38:16.383", "Id": "204649", "Score": "1", "Tags": [ "kotlin", "lexical-analysis" ], "Title": "Lexer for my \"Obganism\" language" }
204649
<p>This is a program to generate prime numbers for a given range. The sieve of Eratosthenes algorithm was implemented, but still the SPOJ says time limit exceeded. Where can some optimizations be made?</p> <p>The input begins with the number t of test cases in a single line (t&lt;=10). In each of the next t lines there are two numbers m and n (1 &lt;= m &lt;= n &lt;= 1000000000, n-m&lt;=100000) separated by a space.</p> <pre><code>import java.util.*; import java.lang.*; class Main { public static void prime(int m, int n) { boolean arr[] = new boolean[n+1]; for(int i = 0; i &lt; arr.length; i++) arr[i] = true; for(int p = 2; p*p &lt;= n; p++) { if(arr[p] == true) { for(int j = p*2; j &lt;= n; j += p) arr[j] = false; } } for(int i = m; i &lt;= n; i++) { if(arr[i] == true) System.out.print(i + " "); } } public static void main (String[] args) throws java.lang.Exception { Scanner in = new Scanner(System.in); int test = in.nextInt(); int m = 0,n = 0,flag = 0; while(test &gt; 0) { m = in.nextInt(); n = in.nextInt(); prime(m,n); test--; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T04:15:45.993", "Id": "394715", "Score": "0", "body": "Please add the restrictions. How many test cases? What are the `m, n` ranges?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T05:23:14.513", "...
[ { "body": "<p>When generating prime numbers with the sieve of Eratosthenes, you can treat 2 as a special case. All other prime numbers are odd, so you can increment by 2:</p>\n\n<pre><code>for(int p = 3; p*p &lt;= n; p += 2)\n</code></pre>\n\n<p>When you find a prime number <span class=\"math-container\">\\$p\...
{ "AcceptedAnswerId": "204663", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T02:19:30.530", "Id": "204656", "Score": "0", "Tags": [ "java", "programming-challenge", "time-limit-exceeded", "primes", "sieve-of-eratosthenes" ], "Title": "Prime number generation - SPOJ" }
204656
<p>I'm creating an API endpoint to create and delete associations, essential creating and deleting records of a join model.</p> <p>The code below doesn't seem idiomatic or pragmatic at all. What's the best way to create 2 endpoints, POST and DELETE for the same route?</p> <pre><code>module API module V1 class UserActivities &lt; Grape::API include API::V1::Defaults format :json namespace :users do route_param :user_id do resource :activities do desc 'Create User + Activity associations' route_param :activity_id do post do #pyramid of doom end end end resource :activities do desc 'Delete User + Activity associations' route_param :activity_id do delete do #pyramid of doom end end end end end end end end </code></pre> <p>This generates the following routes:</p> <pre><code> POST | /api/:version/users/:user_id/activities/:activity_id(.:format) | v1 | Create User + Activity associations DELETE | /api/:version/users/:user_id/activities/:activity_id(.:format) | v1 | Delete User + Activity associations </code></pre> <p>But is there a better way to do this using Grape?</p>
[]
[ { "body": "<p>You don't have to define the whole flow per route, this still leads you to the pyramid of hell.</p>\n\n<pre><code> namespace :users do\n route_param :user_id do\n resource :activities do\n desc 'Create User + Activity associations'\n route_param :activity_id do\n po...
{ "AcceptedAnswerId": "204715", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T02:59:13.493", "Id": "204658", "Score": "0", "Tags": [ "ruby", "ruby-on-rails", "api" ], "Title": "Pyramid of doom Grape endpoints" }
204658
<p>I have only begun to learn C++ and am reading through the book, "Programming Principles and Practices Using C++". This bit of code is my attempt to complete exercise 3 at the end of chapter 4.</p> <p>The actual task is:</p> <blockquote> <p>Read a sequence of double values into a vector. Think of each value as the distance between two cities along a given route. Compute and print the total distance (the sum of all distances). Find and print the smallest and greatest distance between two neighboring cities. Find and print the mean distance between two neighboring cities.</p> </blockquote> <p>I am looking for any <strong>constructive</strong> criticism of my code. Keep in mind some things have not been covered. Even saying that, I still wouldn't mind hearing about what could be. Some things have been covered and I just don't implement them well.</p> <pre><code> #include "std_lib_facilities.h" int main() { double ddistance = 0; double dtotaldist = 0; double dgreatest = 0; double dshortest = 0; char cgoagain; bool bgoagain = true; vector&lt;double&gt;vdistance; while (bgoagain) { cout &lt;&lt; "Enter a valid 'double' "; cin &gt;&gt; ddistance; if (cin) { vdistance.push_back(ddistance); dtotaldist += ddistance; dshortest = ddistance; for (int i = 0; i &lt; vdistance.size(); ++i) if ((vdistance[i]) &gt; dgreatest) { dgreatest = vdistance[i]; } for (int i = 0; i &lt; vdistance.size(); ++i) if (vdistance[i] &lt; dshortest) { dshortest = vdistance[i]; } std::cout &lt;&lt; "vdistance size is\t" &lt;&lt; vdistance.size() &lt;&lt; "\n"; std::cout &lt;&lt; "dtotaldist size is\t" &lt;&lt; dtotaldist &lt;&lt; "\n"; std::cout &lt;&lt; "The mean distance is\t" &lt;&lt; dtotaldist / vdistance.size() &lt;&lt; "\n"; std::cout &lt;&lt; "The long distance is\t" &lt;&lt; dgreatest &lt;&lt; "\n"; std::cout &lt;&lt; "The short distance is\t" &lt;&lt; dshortest &lt;&lt; "\n"; } else { std::cout &lt;&lt; "That is not a valid value. Would you like to try again? 'y' / 'n' \n"; std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); cin &gt;&gt; cgoagain; if (cgoagain == 'y' || cgoagain == 'Y') { bgoagain = true; } else{ bgoagain = false; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T08:30:35.687", "Id": "394732", "Score": "1", "body": "Is `\"std_lib_facilities.h\"` something provided by the book? It's probably better to include a small set of standard headers, so that anyone can compile and test your code." ...
[ { "body": "<p>The exercise \"suggests\" you first store the data into a vector (sentence #1), then compute and display some results.</p>\n\n<p>You should define separate functions for the actions : input data, compute sum, compute minimum, compute average etc. See 4.5.1 from your book: \"Why bother with functi...
{ "AcceptedAnswerId": "204674", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T03:36:45.123", "Id": "204659", "Score": "3", "Tags": [ "c++", "error-handling", "io", "vectors" ], "Title": "Calculate total, minimum, maximum and mean from a set of distances" }
204659
<p>It's sometimes useful to pause until a specified time (but inconvenient to use <code>at</code> or the like), so I wrote a tiny script to wait until a user-specified time point is reached.</p> <p>I use this when I want to keep the output of preceding and subsequent commands together, but I don't mind blocking the current terminal. Quite often, this would be <kbd>M-x</kbd><code>compile</code> when I want to wait until after new source code/data have been uploaded, but still have the results in a compilation-mode buffer.</p> <p>Although it's a very short script, my time at Code Review has taught me that almost any program has something that can be improved, so please make your suggestions!</p> <pre><code>#!/bin/sh # Sleep until the specified time # Accepts any date/time format accepted by 'date' # Assumes GNU date and GNU sleep die() { echo "$@" &gt;&amp;2 exit 1 } usage() { echo "Usage: $0 TIME" } test $# = 1 || die $(usage) case "$1" in --version) echo "sleep_until version 1.0" exit 0 ;; --help) usage exit 0 ;; -*) die "Unrecognised option: $1" ;; *) end=$(date -d "$1" +%s.%N) now=$(date +%s.%N) test ${end%.*} -gt ${now%.*} || die "$1 is in the past!" exec sleep $(echo $end $now - p | dc ) ;; esac </code></pre> <h2>Notes:</h2> <ul> <li>We need GNU <code>date</code> for its <code>-d</code> option and a good range of input formats.</li> <li>GNU <code>sleep</code> handles fractional seconds; we could remove <code>.%N</code> from the date formats to work with traditional/POSIX <code>sleep</code>.</li> <li>I've used <code>dc</code> for the arithmetic so we can use plain <code>sh</code> rather than requiring a more heavyweight shell.</li> </ul>
[]
[ { "body": "<p>In a program <em>comment</em> it is said that the program</p>\n\n<pre><code># Accepts any date/time format accepted by 'date'\n</code></pre>\n\n<p>That information should be printed with the <em>usage help,</em> plus one or two examples. Something like</p>\n\n<pre>\n$ ./sleep_until.sh --help\nUsag...
{ "AcceptedAnswerId": "204681", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T08:51:40.863", "Id": "204673", "Score": "4", "Tags": [ "datetime", "timer", "shell", "scheduled-tasks" ], "Title": "Sleep until specified time" }
204673
<p>I am implementing strategy pattern. I have defined a strategy as interfaces and concrete classes to implement the strategy. Based on user selection/configuration, the algorithm to apply the discount changes.</p> <pre><code> public interface IStrategy { double calculate(double x, double y); } </code></pre> <p>concrete classes implementing the gold strategy is listed below -</p> <pre><code>public class clsGoldDiscountStrategy : IStrategy { public double calculate(double x, double y) { return (x * y) * 0.8; } } } </code></pre> <p>concrete classes implementing the platinumstrategy is listed below -</p> <pre><code>public class clsPlatinumDiscountStrategy : IStrategy { public double calculate(double x, double y) { return (x * y) * 0.7; } } </code></pre> <p>The business logic to apply</p> <pre><code>public class clsBL { public double costPrice { get; set; } public double qty { get; set; } IStrategy _strategy; public clsBL(IStrategy strategy) { _strategy = strategy; } public double GetfinalPrice(double cp, double qty) { return _strategy.calculate(cp, qty); } } </code></pre> <p>//Main method</p> <pre><code>static void Main(string[] args) { Console.WriteLine("Enter the discount Plan (Gold/Platinum)"); string filter = Console.ReadLine().ToUpper(); double result = 0; if (filter.Length &gt; 0) { switch (filter) { case "GOLD": //Gold clsBL blgold = new clsBL(new clsGoldDiscountStrategy()); blgold.costPrice = 5; blgold.qty = 10; result = blgold.GetfinalPrice(blgold.costPrice, blgold.qty); break; case "PLATINUM": //Platinum clsBL blplatinum = new clsBL(new clsPlatinumDiscountStrategy()); blplatinum.costPrice = 10; blplatinum.qty = 8; result = blplatinum.GetfinalPrice(blplatinum.costPrice, blplatinum.qty); break; default: Console.WriteLine("Enter the discount value as either gold or platinum"); break; } Console.WriteLine("The result for " + filter + " is " + result); } else { Console.WriteLine("Enter the discount value"); return; } Console.ReadLine(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T05:40:20.937", "Id": "395024", "Score": "1", "body": "I have rolled back your last edit. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers): _**Do not change th...
[ { "body": "<p>The classes seem OK but the usage makes no sense:</p>\n\n<pre><code> case \"GOLD\":\n //Gold \n clsBL blgold = new clsBL(new clsGoldDiscountStrategy());\n blgold.costPrice = 5;\n blgold.qty = 10;\n\n ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T06:29:15.977", "Id": "204676", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Apply discount changes with Strategy pattern" }
204676
<p>I defined a function that generates tables and creates countplots and barplots based on the arguments that it receives. But the snippets of code inside the function are repeated several times, which looks bad. Is there a way to reduce the repetition?</p> <p>The code was run in a Jupyter Notebook. Here is the Titanic dataset link</p> <p><a href="https://www.kaggle.com/c/titanic/data" rel="nofollow noreferrer">data</a></p> <pre><code>import os print(os.listdir("../input")) from IPython.display import display # to use display import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # because I am using Jupyter Notebook # data frame I am using is the Titanic dataset on kaggle.com # use the train.csv file, it has a column called 'Survived' # Read in the dataset titanic_train = pd.read_csv('../input/train.csv') # Define the count_n_plot function def count_n_plot(df, col_name, countsplit = None, bar = False, barsplit = None): """ Creates countplots and barplots of the specified feature (with options to split the columns) and generates the corresponding table of counts and percentages. Parameters ---------- df : DataFrame Dataset for plotting. col_name : string Name of column/feature in "data". countsplit : string Use countsplit to specify the "hue" argument of the countplot. bar : Boolean If True, a barplot of the column col_name is created, showing the fraction of survivors on the y-axis. barsplit: string Use barsplit to specify the "hue" argument of the barplot. """ if (countsplit != None) &amp; bar &amp; (barsplit != None): col_count1 = df[[col_name]].groupby(by = col_name).size() col_perc1 = col_count1.apply(lambda x: x / sum(col_count1) * 100).round(1) tcount1 = pd.DataFrame({'Count': col_count1, 'Percentage': col_perc1}) col_count2 = df[[col_name,countsplit]].groupby(by = [col_name,countsplit]).size() col_perc2 = col_count2.apply(lambda x: x / sum(col_count2) * 100).round(1) tcount2 = pd.DataFrame({'Count': col_count2, 'Percentage': col_perc2}) display(tcount1, tcount2) #, tbar1, tbar2) figc, axc = plt.subplots(1, 2, figsize = (10,4)) sns.countplot(data = df, x = col_name, hue = None, ax = axc[0]) sns.countplot(data = df, x = col_name, hue = countsplit, ax = axc[1]) figb, axb = plt.subplots(1, 2, figsize = (10,4)) sns.barplot(data = df, x = col_name, y = 'Survived', hue = None, ax = axb[0]) sns.barplot(data = df, x = col_name, y = 'Survived', hue = barsplit, ax = axb[1]) elif (countsplit != None) &amp; bar: col_count1 = df[[col_name]].groupby(by = col_name).size() col_perc1 = col_count1.apply(lambda x: x / sum(col_count1) * 100).round(1) tcount1 = pd.DataFrame({'Count': col_count1, 'Percentage': col_perc1}) col_count2 = df[[col_name,countsplit]].groupby(by = [col_name,countsplit]).size() col_perc2 = col_count2.apply(lambda x: x / sum(col_count2) * 100).round(1) tcount2 = pd.DataFrame({'Count': col_count2, 'Percentage': col_perc2}) display(tcount1, tcount2) #, tbar1) fig, axes = plt.subplots(1, 3, figsize = (15,4)) sns.countplot(data = df, x = col_name, hue = None, ax = axes[0]) sns.countplot(data = df, x = col_name, hue = countsplit, ax = axes[1]) sns.barplot(data = df, x = col_name, y = 'Survived', hue = None, ax = axes[2]) elif countsplit != None: col_count1 = df[[col_name]].groupby(by = col_name).size() col_perc1 = col_count1.apply(lambda x: x / sum(col_count1) * 100).round(1) tcount1 = pd.DataFrame({'Count': col_count1, 'Percentage': col_perc1}) col_count2 = df[[col_name,countsplit]].groupby(by = [col_name,countsplit]).size() col_perc2 = col_count2.apply(lambda x: x / sum(col_count2) * 100).round(1) tcount2 = pd.DataFrame({'Count': col_count2, 'Percentage': col_perc2}) display(tcount1, tcount2) fig, axes = plt.subplots(1, 2, figsize = (10,4)) sns.countplot(data = df, x = col_name, hue = None, ax = axes[0]) sns.countplot(data = df, x = col_name, hue = countsplit, ax = axes[1]) else: col_count = df[[col_name]].groupby(by = col_name).size() col_perc = col_count.apply(lambda x: x / sum(col_count) * 100).round(1) tcount1 = pd.DataFrame({'Count': col_count, 'Percentage': col_perc}) display(tcountl) sns.countplot(data = df, x = col_name) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T08:52:43.810", "Id": "394893", "Score": "0", "body": "I don't know if `display` is default Python function or not. All the libraries I imported are given there now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate":...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T11:22:19.087", "Id": "204679", "Score": "2", "Tags": [ "python", "beginner", "pandas", "data-visualization", "matplotlib" ], "Title": "Function that plots data frames, supporting several variants" }
204679
<p>here is my LinkedList Queue Implementation , seems like its almost like the linkedlist implementation with little differences mainly in the poll() method, i think that the offer() method is same like the linkedlist method add() , the point is that in the offer() method we are adding the elements to the tail, than we are moving them to the left, but their next is same like the add() method, where we are adding in the head and moving the elements to the right... Is i'm right? I'm glad to hear any suggestations... </p> <pre><code>import java.util.NoSuchElementException; public class DynamicQueue { private class Node { private Object item; private Node next; Node(Object item){ this.item = item; this.next = null; } Node(Object item, Node prevNode){ this.item = item; prevNode.next = this; } } private Node head; private Node tail; private int count; public DynamicQueue() { this.head = null; this.tail = null; this.count = 0; } public int size() { return count; } public void offer(Object item) { if(tail == null) { tail = new Node(item); head = tail; }else { Node newNode = new Node(item,tail); tail = newNode; } count++; } public void clear() { head = null; } public Object peek() { if(head == null) { throw new NoSuchElementException("Overflow Exception"); }else { return head.item; } } public void poll() { if(head == null) { throw new NoSuchElementException("Overflow Exception"); } Node currentNode = head.next; head.next = null; head = currentNode; count--; } public static void main(String[] args) { DynamicQueue queue = new DynamicQueue(); queue.offer("First"); queue.offer("Second"); queue.offer("Third"); queue.offer("Fourth"); queue.poll(); System.out.println(queue.peek()); queue.poll(); System.out.println(queue.peek()); queue.poll(); System.out.println(queue.peek()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T15:33:58.910", "Id": "394798", "Score": "0", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code ...
[ { "body": "<h1>clear() is buggy</h1>\n\n<p>The following code causes a <code>NoSuchElementException</code>:</p>\n\n<pre><code>DynamicQueue queue = new DynamicQueue();\nqueue.offer(\"First\");\nqueue.clear();\nqueue.offer(\"First\");\nqueue.poll();\n</code></pre>\n\n<p>You can ealy fix it by adding <code>tail = ...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T11:42:15.020", "Id": "204683", "Score": "1", "Tags": [ "java", "linked-list", "queue" ], "Title": "DynamicList/LinkedList Queue Implementation" }
204683
<p>This is an interview question.<br> For the purpose of the question, a valid English word is a string that begins with an uppercase English letter, and the rest of the string contains only lowercase English letters. I needed to implement two functions: </p> <ol> <li>A function that receives a String and returns true if the String is a valid English word, and false otherwise. </li> <li><p>A function that receives a String and convert it to a valid english word. That means that the function removes non-English characters from the string, and also lowercase\uppercase letters that are in the wrong place. Examples: </p> <pre><code>convertToValidString("A") = "A" convertToValidString("a") = "" convertToValidString("Ab") = "Ab" convertToValidString("AB") = "A" convertToValidString("Ab5eA") = "Abe" convertToValidString("aAd") = "Ad" convertToValidString("a6d") = "" </code></pre></li> </ol> <p>Below is the code I wrote, please tell me what do you think. My emphasis is mainly about efficiency (run time + short code), and less about coding conventions. </p> <pre><code>public static boolean isValidString(String s){ int len = s.length(); if (len == 0) return true; if ( (s.charAt(0) &lt; 65) || (s.charAt(0) &gt; 90) ) return false; for (int i = 1; i &lt; len; i++){ if ( (s.charAt(i) &lt; 97) || (s.charAt(i) &gt; 120) ) return false; } return true; } public static String convertToValidString(String s) { StringBuffer ans = new StringBuffer(); int len = s.length(); int i = 0; while ( (i &lt; len) &amp;&amp; ((s.charAt(i) &lt; 65) || (s.charAt(i) &gt; 90)) ) i++; if (i &lt; len){ ans.append(s.charAt(i)); i++; for (; i &lt; len; i++){ if ( (s.charAt(i) &gt;= 97) &amp;&amp; (s.charAt(i) &lt;= 120) ) ans.append(s.charAt(i)); } } return ans.toString(); } </code></pre>
[]
[ { "body": "<p>Way too many magic numbers: 65, 90, 97, 120. Instead, use literal constants that the reader can understand without consulting an ASCII chart, like:</p>\n\n<pre><code>s.charAt(i) &lt; 'A' || s.charAt(i) &gt; 'Z'\n</code></pre>\n\n<p>Store your character in a local variable, instead of calling <co...
{ "AcceptedAnswerId": "204711", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T13:27:14.897", "Id": "204691", "Score": "1", "Tags": [ "java", "performance", "strings", "interview-questions" ], "Title": "Check if a string is a valid english word, and convert to a valid english word" }
204691
<p>As I am still new to web development, refactoring my code is still something that gives me some trouble. I would really appreciate it if someone could look over the Javascript for an interest rate calculator I built, and maybe give me some pointers on how to refactor it/improve on its efficiency.</p> <p>It consists of three functions:</p> <p>The first, <code>createOptions</code>, just loops over the numbers 1 to 100, and appends each of these numbers as an option to the drop down menu for the percentage input.</p> <p>The second, <code>calculateInterest</code>, is self-explanatory. The formula used assumes compound interest. It also contains a loop which iterates over each payment until the payment period entered is reached. By compound interest, I mean the percentage of the initial amount (the principal) representing the interest rate is calculated, added to the principal, and the percentage of their sum (the interest plus the principal) is added to that. This process repeats for each iteration of the loop.</p> <p>The last function <code>onClick</code> gets the form data in the DOM, stores them in variables, then invokes <code>calculateInterest</code>, passing the variables into its parameters.</p> <p>I am mainly interested in advice regarding my Javascript but any HTML and CSS pointers would be appreciated, too.</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>createOptions(); function createOptions(){ let select = document.getElementById('percentage'); for(var i = 0; i &lt;= 100; i++){ var node = document.createElement("option"); node.innerHTML = i; node.setAttribute('value', i); node.setAttribute('class', 'percent'); select.appendChild(node); } } function calculateInterest(amount, payments, interest){ var total = amount; for(var i = 1; i &lt;= payments; i++){ var percent = total * interest; total = total += percent; } return '$' + total.toFixed(2); } function onClick(){ var para = document.getElementById('show'); var result = document.getElementsByTagName('div') var select = document.getElementById('percentage'); var percentValue = select.options[select.selectedIndex].value / 100; var amounts = document.getElementById('amount'); var amountValue = parseFloat(amounts.value); var time = document.getElementById('time'); var timeValue = parseInt(time.value); if(para.className === "show test"){ para.remove() var para = document.createElement('p'); para.id = "show" var result = document.getElementById('result') result.appendChild(para); } para.innerHTML = calculateInterest(amountValue, timeValue, percentValue); para.className = "show"; para.className += " test" }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: linear-gradient( rgb(25, 25, 230), rgb(255, 255, 255)); background-repeat: no-repeat; box-sizing: border-box; } h1 { text-align: center; } #title { font-family: Verdana; text-transform: uppercase; color: white; } label { font-weight: bolder; color: black; } .btn, .btn-light { margin-top: 10px; } #result { margin-top: 10px; font-size: 24px; text-align: center; } .wrap { position: relative; left: 45%; } .show { animation: fadeIn 1.8s ease-in 0.2s 1 normal both running; } @keyframes fadeIn { from { opacity: 0; } to { display: block; opacity: 1; } } .test { font-size: 60px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" type="text/css" href="./style.css"&gt; &lt;h1 id = "title"&gt;Interest Rate Calculator&lt;/h1&gt; &lt;div class="container"&gt; &lt;div class = "wrap"&gt; &lt;label&gt;% INTEREST&lt;/label&gt; &lt;select class = 'form-control' style = "width: 10%" name="percentage" id= "percentage"&gt;&lt;/select&gt; &lt;label&gt; $ AMOUNT&lt;/label&gt; &lt;input type="number" min = '1' max = '999999999' name = "amount" id = "amount" class = "form-control" style = "width: 10%"&gt; &lt;label for=""&gt;# OF PAYMENTS&lt;/label&gt; &lt;input type = "number" min = '1' max = '999' id = "time" class = "form-control" style = "width: 10%"&gt; &lt;button onClick = "onClick()" target = "_top" class = 'btn btn-light'&gt;CALCULATE!&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="result"&gt; &lt;p id = "show"&gt;&lt;/p&gt; &lt;/div&gt; &lt;script type="text/javascript" src = "./script.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>in the function <code>calculateInterest()</code> this is a bit strange :</p>\n\n<pre><code>total = total += percent;\n</code></pre>\n\n<p>it is either:</p>\n\n<pre><code>total += percent;\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>total = total + percent;\n</code></pre>\n", "comments": [ ...
{ "AcceptedAnswerId": "204719", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T13:30:26.450", "Id": "204693", "Score": "3", "Tags": [ "javascript", "html", "calculator", "dom", "finance" ], "Title": "JavaScript interest rate calculator" }
204693
<p>I have been looking over this block of code for hours trying to simplify it. Would there be a better way to check all those conditions before creating a <code>transaction</code> object without using so many if-elses?</p> <pre><code>def create(self, validated_data): user = self.context['request'].user if user.role == 'super_admin': # ref PR 25.1 return Transaction.objects.create(**validated_data) elif user.role == 'user' or user.role == 'org_admin' or user.role == 'site_admin': # ref PR 25.4 if check_user_institution_exists(validated_data['user_institution'].id): if check_user_belongs_to_institution(validated_data['user_institution'].id, None, user.id) &gt; 0: if check_upload_permission(validated_data['user_institution'].id): return Transaction.objects.create(**validated_data) else: raise serializers.ValidationError({'Error': 'You do not have upload permission for this ' 'institution.'}) else: raise serializers.ValidationError({'Error': 'You do not belong to this institution.'}) else: raise serializers.ValidationError({'Error': 'This user institution does not exist.'}) else: raise serializers.ValidationError({'Error': 'You are not assigned a role.'}) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T14:20:00.593", "Id": "394784", "Score": "0", "body": "Are you possibly missing an `else` for the outer-most if, elif?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T14:21:11.723", "Id": "394786",...
[ { "body": "<ol>\n<li>You don't need to use <code>elif</code> you can change that to just an if.</li>\n<li><p>You can simplify code blocks by using guard clauses that have the following layout:</p>\n\n<pre><code>if a:\n ...\nelse:\n raise b\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>if not a:\n raise b\...
{ "AcceptedAnswerId": "204703", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T14:18:02.290", "Id": "204701", "Score": "2", "Tags": [ "python", "validation", "django", "authorization" ], "Title": "Transactionally create something, if allowed" }
204701
<p>This is the &quot;<a href="https://www.hackerrank.com/challenges/beautiful-binary-string/problem" rel="noreferrer">Beautiful Binary String</a>&quot; problem at HackerRank:</p> <blockquote> <p>Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn't contain the substring 010.</p> <p>In one step, Alice can change a 0 to a 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.</p> <p>For example, if Alice's string is 010 she can change any one element and have a beautiful string.</p> </blockquote> <p>This is my Python code:</p> <pre><code>def beautifulBinaryString(b): temp = list(b) count,i = 0,0 if len(b) == 3 and b == &quot;010&quot;: count += 1 elif len(b) == 3 and b != &quot;010&quot;: count = count else: while (i+3 &lt;= len(temp)): if temp[i:i+3] == ['0','1','0']: count += 1 del temp[i:i+3] else: i += 1 return count </code></pre> <p>It seems to me as having too many conditionals (though readable, I guess). Is there a more concise way to accomplish this?</p> <p>Some test cases:</p> <pre><code>0101010 01100 2 0 </code></pre>
[]
[ { "body": "<h1>Style</h1>\n\n<ul>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/?\" rel=\"noreferrer\">Read the PEP8 style guide!</a></p>\n\n<ol>\n<li>Functions and variables should be <code>snake_case</code></li>\n<li>Conditions should be on the next line <code>if a: ...</code> is bad style</li>\n...
{ "AcceptedAnswerId": "204707", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T14:19:48.450", "Id": "204702", "Score": "12", "Tags": [ "python", "strings", "programming-challenge" ], "Title": "Make a beautiful binary string" }
204702
<p>This is the "Gemstones" problem on Hackerrank. </p> <blockquote> <p>John has collected various rocks. Each rock has various minerals embeded in it. Each type of mineral is designated by a lowercase letter in the range <code>a-z</code>. There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in John's collection. Given a list of minerals embedded in each of John's rocks, display the number of types of gemstones he has in his collection. For example, the array of mineral composition strings <code>[abc, abc, bc]</code> The minerals b and c appear in each composite, so there are 2 gemstones.</p> </blockquote> <p>This is my Python code:</p> <pre><code>def gemstones(arr): for i in range(len(arr)): arr[i] = "".join(set(arr[i])) long = max(arr, key=len) arrlen = len(arr) flag,count = 0,0 for i in long: for j in range(arrlen): if i not in arr[j]: flag = 1 if flag is 0: count += 1 flag = 0 return count </code></pre> <p>Are there ways to improve this code? I feel I'm not using the full functionality of Python.</p> <p>A test case:</p> <pre><code>&gt;&gt;&gt; arr = ['abcdde', 'baccd', 'eeabg'] &gt;&gt;&gt; print(gemstones(arr)) 2 </code></pre>
[]
[ { "body": "<p>You need to stop iterating over indexes and <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"noreferrer\">loop like a native</a>. A first rewrite with that in mind would yield:</p>\n\n<pre><code>def gemstones(collection):\n collection = [''.join(set(rock)) for rock in collection]\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T15:21:40.740", "Id": "204712", "Score": "7", "Tags": [ "python", "strings", "programming-challenge" ], "Title": "Count number of gemstones in a set of minerals" }
204712
<p>I'm learning python 3.x and I'm still feeling like a newbie.</p> <p>The program below scrape a given course in <a href="https://symfonycasts.com/" rel="nofollow noreferrer">https://symfonycasts.com/</a> and creates a file containing all the dynamics download links to all the videos in that course.</p> <p>General programming-related tips and better ways to use beautifulsoup would be great.</p> <pre><code>import requests from bs4 import BeautifulSoup agents = { 'mozilla':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0' } download_suffix = '/download/video' base_url = 'https://symfonycasts.com' course_url = '/screencast/rest-ep2/serializer' def get_page_dom(): url = base_url + course_url headers = {'user-agent': agents['mozilla']} r = requests.get(url=url,headers=headers) return r.text def get_links(html): chapter_list = html.find('div',class_='chapter-list') chapter_list_item = chapter_list.find_all('li') for item in chapter_list_item: yield item.div.div.a['href'] def generate_download_link(dl): for i in dl: yield base_url + i + download_suffix def save_to_file(links): links = generate_download_link(links) with open('links.txt', 'w') as f: for i in links: f.write(i + '\n') def Main(): html = BeautifulSoup(get_page_dom(), 'html.parser') download_links = get_links(html) save_to_file(download_links) if __name__ == '__main__': Main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T18:16:30.057", "Id": "394821", "Score": "0", "body": "From my experience, scraping web pages is _almost_ always sketchy. Websites are prone to change and inconcistencies, so it's hard to lay down guidelines specific to scraping." ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T17:04:31.977", "Id": "204718", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "beautifulsoup" ], "Title": "Scraping symfonycasts.com using BeautifulSoup" }
204718
<p>I have the following code which I use to determine how much of each repayment goes into each late payments bucket (i.e. 0-7 days past due, 7-15 days past due... etc)</p> <p>For example, the repayment amount is 100. 20 gets repid early, and then the customer misses the repayment date. Therefore, 80 goes into the 0-7dpd bucket and so on. Similarly, if the customer does not repay for 7 days, the 80 goes into the 7-15dpd bracket.</p> <p>The code works, but takes a long time. I was wondering if there is a method to make the code run faster.</p> <pre><code>repayments['principal_0_7_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 2.0), repayments.amount_principal - (repayments.child_principal_repaid_early), 0) repayments['principal_7_15_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 7.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days), 0) repayments['principal_15_30_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 15.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days), 0) repayments['principal_30_45_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 30.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days), 0) repayments['principal_45_60_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 45.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days), 0) repayments['principal_60_90_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 60.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days + repayments.child_principal_repaid_45_60_days), 0) repayments['principal_90_120_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 90.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days + repayments.child_principal_repaid_45_60_days + repayments.child_principal_repaid_60_90_days), 0) repayments['principal_120_plus_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 120.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days + repayments.child_principal_repaid_45_60_days + repayments.child_principal_repaid_60_90_days + repayments.child_principal_repaid_90_120_days), 0) </code></pre> <p>You can use the following test data. The expected output is also included below:</p> <pre><code>df = pd.DataFrame({ 'amount_principal':[456.6459958, 456.6459958], 'days_since_due':[1068, 1061], 'paid_y_n':['yes, 'no'], 'child_principal_repaid_early':[0, 0], 'child_principal_repaid_1_7_days':[0, 0], 'child_principal_repaid_7_15_days':[0, 0], 'child_principal_repaid_15_30_days':[0, 180.2126753], 'child_principal_repaid_30_45_days':[0, 0], 'child_principal_repaid_45_60_days':[0, 0], 'child_principal_repaid_60_90_days':[0, 0], 'child_principal_repaid_90_120_days':[0, 0], 'child_principal_repaid_120_plus_days':[0, 0]}, index = [0,1]) </code></pre> <p><a href="https://i.stack.imgur.com/jAYqc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jAYqc.png" alt="enter image description here"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T17:53:27.337", "Id": "204723", "Score": "1", "Tags": [ "python", "pandas" ], "Title": "Calculating how much $ goes into each defaulting bucket" }
204723
<p>I want to sort entries in a given list on Entry column in most efficient way. Here is how my entries look:</p> <pre class="lang-none prettyprint-override"><code>#No Detail Entry Number Rate 1 Carpool at 5$ C 1 5 Carpool at 5$ H 2 5 2 Played Cricket at 2$ X 1 2 Played Cricket at 2$ O 2 2 3 Done something at 4$ "" 0 4 4 Done something else at 9$ M 1 9 5 Watched movie at 6$ B 1 6 Watched movie at 6$ Z 2 6 </code></pre> <h3>Some explanation of the format:</h3> <ol> <li>#No column is not present in table. I just mentioned here to give detail about entries.</li> <li>#1,2,5 are special "clubbed" entries and should be sorted together on Entry which have number column set to 1. These entries have specialty that their rate and description would be same and Number would be 1 and 2.</li> <li>There is possibility that there could be some entries which have empty Entry values; such entries will have number set to 0. Such as #3</li> <li>There is possibility that there could be some entries which have single Entry value and will not have any pair and Number column for such entries would be set to 1 and there wouldn't be any entry in list which have same description and rate with Number column set to 2. Such as #4.</li> <li>While sorting clubbed entries on Entry column only consider Entry with Number set to 1 and other entry should tag along.</li> </ol> <p>I want to sort Entry column by ascending or descending order abiding above rules.</p> <h3>My Solution:</h3> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { internal interface IDBEntity { string Detail { get; set; } string Entry { get; set; } int Number { get; set; } int Rate { get; set; } } internal class Data : IDBEntity { public string Detail { get; set; } public string Entry { get; set; } public int Number { get; set; } public int Rate { get; set; } } internal enum SortingOrder { Ascending, Descending } internal enum SortingType { Detail, Entry, Number, Rate } internal class Comparer&lt;T&gt; : IComparer&lt;T&gt; where T : IDBEntity { public SortingType SortingColumn { get; set; } private int sortOrder = 1; public Comparer(SortingOrder order = SortingOrder.Ascending) { if (order == SortingOrder.Ascending) { sortOrder = 1; } else if (order == SortingOrder.Descending) { sortOrder = -1; } else { throw new NotImplementedException("Sorting Order is Undefined"); } } public int Compare(T x, T y) { int result = sortOrder; if (x == null &amp;&amp; y != null) { result *= sortOrder; } else if (x == null &amp;&amp; y == null) { result = 0; } switch (SortingColumn) { case SortingType.Entry: if (x.Detail == y.Detail &amp;&amp; x.Rate == y.Rate) { result = x.Entry.CompareTo(y.Entry); } break; default: break; } return result * sortOrder; } } internal class Program { private static void Main(string[] args) { List&lt;Data&gt; entries = new List&lt;Data&gt;(); // Clubbed entry...While sorting only consider entry with Number set to 1. They will have same rate and Detail. entries.Add(new Data() { Detail = "Carpool at 5$", Entry = "C", Number = 1, Rate = 5 }); entries.Add(new Data() { Detail = "Carpool at 5$", Entry = "H", Number = 2, Rate = 5 }); // Clubbed entry entries.Add(new Data() { Detail = "Played Cricket at 2$", Entry = "X", Number = 1, Rate = 2 }); entries.Add(new Data() { Detail = "Played Cricket at 2$", Entry = "O", Number = 2, Rate = 2 }); // entry which have empty Entry value such entries will have Number set to 0 entries.Add(new Data() { Detail = "Done something at 4$", Entry = "", Number = 0, Rate = 4 }); // entry which will not have an pair and Number column for such entries would be set to 1 and // there wouldn't be any entry in list which have same detail and rate with Number coloumn set to 2 entries.Add(new Data() { Detail = "Done something else at 9$", Entry = "M", Number = 1, Rate = 9 }); // Clubbed entry entries.Add(new Data() { Detail = "Watched movie at 6$", Entry = "B", Number = 1, Rate = 6 }); entries.Add(new Data() { Detail = "Watched movie at 6$", Entry = "Z", Number = 2, Rate = 6 }); entries.Add(new Data() { Detail = "BlahBlah", Entry = "", Number = 0, Rate = 0 }); // Sorting on Entry Coloumn var sortedList = entries.GroupBy(x =&gt; new { x.Detail, x.Rate }) // Grouping entries which have same Detail and Rate .OrderBy(x =&gt; x.FirstOrDefault(y =&gt; y.Number &lt;= 1)?.Entry) // Sort the group based on Entry which has Number set to &lt;=1 .SelectMany(x =&gt; x.OrderBy(z =&gt; z.Number)) // Un-Group entries and make sure order is maintained using Number property .ToList(); var compObj = new Comparer&lt;Data&gt;() { SortingColumn = SortingType.Entry }; entries.Sort(compObj); } } } </code></pre> <h3>LINQ solution</h3> <pre><code>var sortedList = entries.GroupBy(x =&gt; new { x.Detail, x.Rate }) // Grouping entries which have same Detail and Rate .OrderBy(x =&gt; x.FirstOrDefault(y =&gt; y.Number &lt;= 1)?.Entry) // Sort the group based on Entry which has Number set to &lt;=1 .SelectMany(x =&gt; x.OrderBy(z =&gt; z.Number)) // Un-Group entries and make sure order is maintained using Number property .ToList(); </code></pre> <h3>Output:</h3> <pre class="lang-none prettyprint-override"><code>Detail Entry Number Rate Done something at 4$ "" 0 4 Watched movie at 6$ B 1 6 Watched movie at 6$ Z 2 6 Carpool at 5$ C 1 5 Carpool at 5$ H 2 5 Done something else at 9$ M 1 9 Played Cricket at 2$ X 1 2 Played Cricket at 2$ O 2 2 </code></pre> <h3>Questions:</h3> <ul> <li>I have Linq solution working, Any comments on that?</li> <li>Can it be done using <code>IComparer</code> as in rest of my code had sorting done using <code>IComparer</code>? In <code>Compare</code> method, I have switch case on column where I compare two entries but I don't know how to group while comparing.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T20:33:27.570", "Id": "394828", "Score": "1", "body": "Your question is unfortuantelly off-topic because they are mostly about features that are not implemented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "20...
[ { "body": "<blockquote>\n <p>Can it be done using IComparer</p>\n</blockquote>\n\n<p>of course.</p>\n\n<p><a href=\"https://codereview.stackexchange.com/a/104445/10221\">Here is a code review answer</a> that shows how one could sort on multiple criteria. I think it will be useful to read the entire thread.</p>...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T18:11:41.167", "Id": "204724", "Score": "0", "Tags": [ "c#", "sorting", "linq" ], "Title": "Sorting table using multiple columns" }
204724
<p>I am making a website which should host a lot of PDFs. These PDFs are stored on the HDD. There are DossierIds in the database which correspondent with the folder name. In these folders there is 1 layer of folders and in those layers are the PDFs.</p> <p>To make the structure clear:</p> <pre class="lang-none prettyprint-override"><code>- ABC - Dossier1 -File1.pdf -File2.pdf - Dossier2 -File1.pdf -File2.pdf -File3.pdf -DEF - Dossier1 -File1.pdf - Dossier2 -File1.pdf -File2.pdf - Dossier3 -File1.pdf </code></pre> <p>The layer which contains the most folders it the root layer (so in the example: ABC, DEF, etc).</p> <p>I wrote the following code but I'm not sure if it's optimal and if it can handle concurrent access:</p> <pre class="lang-java prettyprint-override"><code>public List&lt;Folder&gt; getFolders(String dossierId) { //Going right to the correct folder. Not sure how heavy this operation is. File file = new File(String.format("%s\\%s", propertyService.getProperties().get("folderLocation"), dossierId)); //Retrieving all folders in that directory. File[] directories = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return new File(dir, name).isDirectory(); } }); List&lt;Folder&gt; folders = new ArrayList&lt;&gt;(); //Going through the folders to check for files for (File f : directories) { File folder = new File(f.getPath()); File[] listOfFiles = folder.listFiles(); List&lt;String&gt; fileNames = new ArrayList&lt;&gt;(); for (File childfile : listOfFiles) { fileNames.add(childfile.getName()); } folders.add(new Folder(f.getName(), fileNames)); } return folders; } </code></pre>
[]
[ { "body": "<p>The code is not optimal. Furthermore, it breaks the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a> since the method can be broken down to smaller, tighter pieces. For example, the for loop can and should be ...
{ "AcceptedAnswerId": "204835", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T18:32:28.850", "Id": "204726", "Score": "1", "Tags": [ "java", "file-system" ], "Title": "Find a folder in Java" }
204726
<p>I have made a little Snake game with Python tkinter. It's my first Python program with one GUI. What can I improve?</p> <pre><code>from tkinter import * import random boardWidth = 30 boardHeight = 30 tilesize = 10 class Snake(): def __init__(self): self.snakeX = [20, 20, 20] self.snakeY = [20, 21, 22] self.snakeLength = 3 self.key = "w" self.points = 0 def move(self): # move and change direction with wasd for i in range(self.snakeLength - 1, 0, -1): self.snakeX[i] = self.snakeX[i-1] self.snakeY[i] = self.snakeY[i-1] if self.key == "w": self.snakeY[0] = self.snakeY[0] - 1 elif self.key == "s": self.snakeY[0] = self.snakeY[0] + 1 elif self.key == "a": self.snakeX[0] = self.snakeX[0] - 1 elif self.key == "d": self.snakeX[0] = self.snakeX[0] + 1 self.eatApple() def eatApple(self): if self.snakeX[0] == apple.getAppleX() and self.snakeY[0] == apple.getAppleY(): self.snakeLength = self.snakeLength + 1 x = self.snakeX[len(self.snakeX)-1] # Snake grows y = self.snakeY[len(self.snakeY) - 1] self.snakeX.append(x+1) self.snakeY.append(y) self.points = self.points + 1 apple.createNewApple() def checkGameOver(self): for i in range(1, self.snakeLength, 1): if self.snakeY[0] == self.snakeY[i] and self.snakeX[0] == self.snakeX[i]: return True # Snake eat itself if self.snakeX[0] &lt; 1 or self.snakeX[0] &gt;= boardWidth-1 or self.snakeY[0] &lt; 1 or self.snakeY[0] &gt;= boardHeight-1: return True # Snake out of Bounds return False def getKey(self, event): if event.char == "w" or event.char == "d" or event.char == "s" or event.char == "a" or event.char == " ": self.key = event.char def getSnakeX(self, index): return self.snakeX[index] def getSnakeY(self, index): return self.snakeY[index] def getSnakeLength(self): return self.snakeLength def getPoints(self): return self.points class Apple: def __init__(self): self.appleX = random.randint(1, boardWidth - 2) self.appleY = random.randint(1, boardHeight - 2) def getAppleX(self): return self.appleX def getAppleY(self): return self.appleY def createNewApple(self): self.appleX = random.randint(1, boardWidth - 2) self.appleY = random.randint(1, boardHeight - 2) class GameLoop: def repaint(self): canvas.after(200, self.repaint) canvas.delete(ALL) if snake.checkGameOver() == False: snake.move() snake.checkGameOver() canvas.create_rectangle(snake.getSnakeX(0) * tilesize, snake.getSnakeY(0) * tilesize, snake.getSnakeX(0) * tilesize + tilesize, snake.getSnakeY(0) * tilesize + tilesize, fill="red") # Head for i in range(1, snake.getSnakeLength(), 1): canvas.create_rectangle(snake.getSnakeX(i) * tilesize, snake.getSnakeY(i) * tilesize, snake.getSnakeX(i) * tilesize + tilesize, snake.getSnakeY(i) * tilesize + tilesize, fill="blue") # Body canvas.create_rectangle(apple.getAppleX() * tilesize, apple.getAppleY() * tilesize, apple.getAppleX() * tilesize + tilesize, apple.getAppleY() * tilesize + tilesize, fill="green") # Apple else: # GameOver Message canvas.delete(ALL) canvas.create_text(150, 100, fill="darkblue", font="Times 20 italic bold", text="GameOver!") canvas.create_text(150, 150, fill="darkblue", font="Times 20 italic bold", text="Points:" + str(snake.getPoints())) snake = Snake() apple = Apple() root = Tk() canvas = Canvas(root, width=300, height=300) canvas.configure(background="yellow") canvas.pack() gameLoop = GameLoop() gameLoop.repaint() root.title("Snake") root.bind('&lt;KeyPress&gt;', snake.getKey) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T22:12:10.403", "Id": "394834", "Score": "0", "body": "_\"In my posted code the indentations are partly wrong, because I couldn't format it correctly.\"_ Indentations are essential for correct python code. [Read up here](https://code...
[ { "body": "<h1>Review</h1>\n<h2>Naming conventions</h2>\n<p>In Python, methods and variables should be named the following way: <a href=\"https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names\">https://stackoverflow.com/questions/159720/what-is-the-na...
{ "AcceptedAnswerId": "205129", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T22:08:05.203", "Id": "204731", "Score": "2", "Tags": [ "python", "object-oriented", "python-3.x", "tkinter", "snake-game" ], "Title": "Python tkinter Snake" }
204731
<p>I'm learning Haskell, and I tried to do an exercise which it is an implementation of the Caesar Cipher method.</p> <p>The problem asks for cipher a text which it is in lower case and can contain characters from 'a' to 'z' without numbers, uppercase letters, symbols etc.., only lower case letters. </p> <p>If the letter it is in an even position inside the message, I need to change for itself but in upper case. Example 'a' will be 'A'</p> <p>If the letter is in an odd position inside the message, I need to change it by an other letter "n" positions next in the alphabet by the original one. Example 'a' will be 'd' if "n" is equal to 3</p> <p>Important thing, the alphabet needs to be circular, so, after z, will be the 'a'</p> <p>So you call the function with a text and a number "n" for example: <code>alfabet 3</code> The result will be: <code>AoFdBhT</code>.</p> <p>This is my personal implementation, I checked it, and works fine, but I think maybe it is not a very good implementation, and I would like some advice to improve it.</p> <pre><code>caesarCipher :: String -&gt; Int -&gt; String caesarCipher = caesarCipherAux [] 0 caesarCipherAux :: String -&gt; Int -&gt; String -&gt; Int -&gt; String caesarCipherAux codedMessage _ [] _ = codedMessage caesarCipherAux codedMessage pos (xs:s) n = if even (pos) then caesarCipherAux (codedMessage++[toUpper xs]) (pos+1) s n else caesarCipherAux (codedMessage++ [cipher xs n]) (pos+1) s n cipher :: Char -&gt; Int -&gt; Char cipher xs n | xs == 'x'='a' | xs == 'y'='b' | xs == 'z'='c' | otherwise = [xs..'z'] !! n </code></pre>
[]
[ { "body": "<p>Heres my implementation, I abused pattern matching so that way I don't need to check for even and odd index. Your cipher function will also only work for 3, using ord and modulo however will cover all wrap around cases for all integers.</p>\n\n<p>All the below line is doing is getting the next n c...
{ "AcceptedAnswerId": "204735", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T22:12:13.310", "Id": "204732", "Score": "2", "Tags": [ "beginner", "haskell", "caesar-cipher" ], "Title": "Caesar Cipher in Haskell, on every other character" }
204732
<p>My concern is mainly the correctness of the algorithm for tokenizing purposes. The code compiles as it is called as a member function in my program. The code does pass my small amount of unit tests for parsing inputs (61 unit tests, all pass). But, I'm slightly stressed out about this part of code, and also paranoid. I could use a pair of foreign mk.I eyeballs looking at my code. This is part of a bigger project and ideally the tokenizing should be bugfree </p> <p>please take a look and give thoughts. :'(</p> <p>BACKGROUND &amp; problem parameters objectives of my tokenizer:</p> <ul> <li>cannot use stringstreams, run out of programmemory</li> <li>input cppstrings will not have newline or any such limiter at the end(will be chucked out before inputting into tokenize_input_refactored() ), IT will be as though the input cppstring was gotten with getline()</li> <li>separate cppstrings into tokens based on single spacebar (delimiter), or the end of the string in regular way ("M4 255" is tokenized into "M4", "255")</li> <li>if there's no delimiter, take the entire cppstring as token</li> <li>backToBack delimiters is immediately invalid input, like " " twoSpacebars in row (or more spacebars in row)</li> <li>cannot begin or end with spacebar(delimiter), immediately invalid input</li> <li>too large string ( 31 or more true chars) is illegal input</li> <li><p>empty string is illegal input</p></li> <li><p>the "garbage strings" that are pushed into the vector "illegalcommand" are later on used for comparison with known words for parsing purposes. Just to be sure that command won't be parsed as valid. (tokens amount as well as tokens themselves are checked against expected values)</p></li> </ul> <p>Possible solution as C++ member-function:</p> <p><code>tokensVec</code> is just an empty vector datamember of <code>Gcodeparser</code> object. It will be cleared empty after each round of tokenizing (or parsing, the same same effect).</p> <pre><code>bool GcodeParser::tokenize_input_refactored(const std::string &amp; rawInput) { /*find delimiter == singleSpacebar*/ auto res = rawInput.find(delimiter); /*find if there was twoOrMoreDelimiters backToBack " " twospacebars */ string backToBackDelim; backToBackDelim += delimiter; backToBackDelim += delimiter; auto res2 = rawInput.find(backToBackDelim); int searchInd = 0; int pos = 0; int size = rawInput.length(); bool returnableResult = false; /*if the input was too large =&gt; reject as illegal*/ if (size &gt; maxCharAmount) { tokensVec.push_back("INVALID_COMMAND!"); return false; } /*check if empty string*/ if (size == 0) { tokensVec.push_back("INVALID_COMMAND!"); return false; } /*found 2delim backtoback*/ if (res2 != string::npos) { tokensVec.push_back("INVALID_COMMAND!"); return false; } /*input ended in delimiter or started with delimiter*/ if (rawInput[0] == delimiter || rawInput[size-1] == delimiter) { tokensVec.push_back("INVALID_COMMAND!"); return false; } /*delimiter wasnt found =&gt; take complete word into vec for later parsing*/ if (res == string::npos) { tokensVec.push_back(rawInput); return true; } else { while (pos != string::npos) { pos = rawInput.find(delimiter, searchInd); if (pos != string::npos) { tokensVec.push_back(rawInput.substr(searchInd, pos - searchInd)); searchInd = pos + 1; } } /*take the last valid token*/ tokensVec.push_back( rawInput.substr(searchInd, size - searchInd) ); return true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T07:48:19.967", "Id": "394882", "Score": "0", "body": "If your main concern is correctness, you should really **include your unit tests** as part of the review. Without that, it's hard to know which aspects are already well covered ...
[ { "body": "<p>As far as I can see, this looks correct for the behavior you've stated. A few possible improvements:</p>\n\n<p>Efficiency:</p>\n\n<ul>\n<li>It would be better to check for failure conditions in a different order: string size, first or last is delimiter, presence of double-delimiter, and only if th...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T22:41:47.317", "Id": "204733", "Score": "4", "Tags": [ "c++", "strings", "parsing" ], "Title": "C++ string tokenizing without streams, with certain conditions" }
204733
<p>Ok, now for some time I've been trying to conquer this challenge without success performance wise. And I'd like some hints about approaching this problem, or the general algorithms I should learn before tackling something like this.</p> <p>Task description :</p> <blockquote> <p>A string is balanced if it consists of exactly two different characters and both of those characters appear exactly the same number of times. For example: "aabbab" is balanced (both 'a' and 'b' occur three times) but "aabba" is not balanced ('a' occurs three times, 'b' occurs two times). String "aabbcc" is also not balanced (it contains three different letters). A substring of string S is a string that consists of consecutive letters in S. For example: "ompu" is a substring of "computer" but "cmptr" is not. Write a function solution that, given a string S, returns the length of the longest balanced substring of S.</p> <p>Examples (input -> output) : </p> <blockquote> <p>'cabbacc' -> 4 ( 'abba') </p> <p>'ab' -> 2 ('ab')</p> <p>'abababa' -> 6 ('ababab' / 'bababa') </p> <p>'abc' -> 2 ('ab'/'bc') </p> <p>'bbbbbbabbbbbbbbbabbbbbbbbbbbbbbbbbbbbaabbabbbbbbbbbbbbb' -> 6 ('baabba')</p> <p>etc.</p> </blockquote> </blockquote> <p>I have tried solving it in number of different ways , but here is the last one that gave me 100% on correctness: </p> <pre><code>def solution(s): c = {} linker = {} for i in range(len(s) - 1, -1, -1): c[s[i]] = c.get(s[i],0) + 1 linker['%s%s'%(len(s)-1,i)] = c.copy() c = {} for i in range(0, len(s)): c[s[i]] = c.get(s[i],0) + 1 linker['%s%s'%(0,i)] = c.copy() window_size = len(s) if len(s) % 2 == 0 else len(s) - 1 if len(s) % 2 == 0: check = linker['%s%s'%(len(s)-1,0)] if(len(check) == 2): if list(check.values())[0] == list(check.values())[1]: return window_size everything = linker["%s%s"%(len(s)-1,0)] #print("WIdnow size : " ,window_size ) for ws in range(window_size, 0, -2): for i in range(0,len(s)-ws+1): sp_inc = i ep_inc = i+ws #print(sp_inc,ep_inc ) d1 = dict() d2 = dict() if sp_inc-1 &gt;= 0: d1 = linker["%s%s"%(0,sp_inc-1)] if ep_inc &lt;= len(s)-1: d2 = linker["%s%s"%(len(s)-1, ep_inc)] #print(d1,d2,everything) result = dict() for k,v in everything.items(): result[k] = v - d1.get(k,0) - d2.get(k,0) if(result[k] == 0): del result[k] if len(result) == 2: if list(result.values())[0] == list(result.values())[1]: #print(result) return ws return 0 tests = [ ["cabbacc", 4], ["ab", 2], ["abababa", 6], ["abc", 2], ["ababbbaa", 8], ['bbbbbbabbbbbbbbbabbbbbbbbbbbbbbbbbbbbaabbabbbbbbbbbbbbb',6], ['aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaa',70] ] for i in tests: print(i[0]) #assert solution(i[0]) == i[1] assert solution(i[0]) == i[1] # break print("everything ok") </code></pre> <p>Here is another approach I tried, but it wasn't totally correct ( for some test cases it gave me result that was equal to correct_result + 2 ), but for all test cases in <code>tests</code> array it gave me correct result.</p> <pre><code>from collections import deque def solution(s): #print(s) window_size = len(s) chars = {} old_window = deque() for d in s: chars[d] = chars.get(d,0) + 1 old_window.append(d) #print(chars) if len(chars) == 2 and window_size % 2 == 0: if chars[list(chars.keys())[0]] == chars[list(chars.keys())[1]]: return window_size if(window_size % 2 == 0): window_size-= 2 c = old_window.pop() chars[c]-=1 if chars[c] == 0: del chars[c] c = old_window.pop() chars[c]-=1 if chars[c] == 0: del chars[c] else: window_size-= 1 c = old_window.pop() chars[c]-=1 if chars[c] == 0: del chars[c] if len(chars) == 2 and window_size % 2 == 0: if chars[list(chars.keys())[0]] == chars[list(chars.keys())[1]]: return window_size #return None #print(s[len(old_window)]); #return None flow = 1 while(window_size &gt; 0): # print("Hello") if flow == 1: # print("Here", len(old_window)+1,len(s)) for i in range(window_size,len(s)): c = old_window.popleft() #print("char poped %s"% c) chars[c]-=1 if chars[c] == 0: del chars[c] old_window.append(s[i]) #print("Hello " , old_window) chars[s[i]] = chars.get(s[i],0) + 1 if len(chars) == 2: if chars[list(chars.keys())[0]] == chars[list(chars.keys())[1]]: #print("".join(old_window)) return window_size #print(":" , "".join(old_window)) flow = 0 else: for i in range(len(s)-window_size-1,-1,-1): c = old_window.pop() chars[c]-=1 if chars[c] == 0: del chars[c] old_window.appendleft(s[i]) #print(old_window) chars[s[i]] = chars.get(s[i],0) + 1 if len(chars) == 2: if chars[list(chars.keys())[0]] == chars[list(chars.keys())[1]]: #print("".join(old_window)) return window_size #print(":" , "".join(old_window)) flow = 1 for i in range(2): if flow == 1: c = old_window.pop() chars[c]-=1 if chars[c] == 0: del chars[c] else: c = old_window.popleft() chars[c]-=1 if chars[c] == 0: del chars[c] window_size-=2 return 0 tests = [ ["cabbacc", 4], ["ab", 2], ["abababa", 6], ["abc", 2], ["ababbbaa", 8], ['bbbbbbabbbbbbbbbabbbbbbbbbbbbbbbbbbbbaabbabbbbbbbbbbbbb',6], ['aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaa',70] ] for i in tests: print(i) #assert solution(i[0]) == i[1] print(solution(i[0])) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T00:06:24.643", "Id": "394843", "Score": "0", "body": "Why `cabbac` is not a solution in the first example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T00:07:06.343", "Id": "394844", "Score...
[ { "body": "<p>It has taken me a while, but I think I understand what you are doing now. And I’ve got some improvements. I’m only going to consider your code that passes 100%. (Your code that doesn’t work properly in all cases is not appropriate for review on Code Review.)</p>\n\n<hr>\n\n<p>First, you compute...
{ "AcceptedAnswerId": "204927", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-01T23:49:19.567", "Id": "204736", "Score": "5", "Tags": [ "python", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "BalancedPassword Codility task" }
204736
<p>This method is part of a larger project and comes after encoding ascii characters into hexadecimal values, so it assumes the parameter is always a valid hex string.</p> <pre><code>public static String toMatrix(String hex) { StringBuilder builder = new StringBuilder(); int rows = 0; int columns = 16; int row = 0; int column = 0; rows = ( hex.length() / 32 ) + ( hex.length() % 32 ); for (row = 0; row &lt; rows; row++) { for (column = 0; column &lt; columns; column++) { if (hex.length() &gt; 0) { builder.append(hex.substring(0,2)); hex = hex.substring(2,hex.length()); if ((column + 1) % 4 == 0) { builder.append(" "); }else { builder.append(" "); } } } builder.append("\n"); column = 0; } return builder.toString().trim(); } </code></pre> <p>Input: </p> <pre><code>1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D </code></pre> <p>Output:</p> <pre><code>1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D 1D </code></pre> <p>In which way can this method be better?</p>
[]
[ { "body": "<blockquote>\n<pre><code> int columns = 16;\n</code></pre>\n</blockquote>\n\n<p>This should be a constant and defined outside the method. </p>\n\n<pre><code>public static final int MATRIX_WIDTH = 32;\n</code></pre>\n\n<p>I prefer singular names for scalar variables. I use plural names for collec...
{ "AcceptedAnswerId": "204748", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T00:03:28.870", "Id": "204738", "Score": "2", "Tags": [ "java", "performance", "strings", "formatting" ], "Title": "Method that receives a hexadecimal string and returns a formatted matrix of those values" }
204738
<p>I want to get a count of each of the category occurrences (in how many rows did it show up in under the taxonomy column). The taxonomy column has a list of categories and I have several thousand rows, and I want to get a count of the number of times the categories shows up. Please note that there could be multiple categories per row but the same category will not be repeated in the same cell.</p> <p>Is there a way to condense or clean the following code when running through a dataframe? I want to combine the <code>if</code> statements somehow without losing the logic.</p> <pre><code>for index, row in df.iterrows(): for key in (row['taxonomy'] ) : if key in technical_issues_list: technical_issues += 1 if key == 'technical_issues' : technical_issues_specific += 1 if key == 'product_not_available': product_not_available += 1 if key == 'site_performance': site_performance += 1 if key in checkout_list: checkout += 1 if key == 'unable_to_checkout': unable_to_checkout += 1 if key == 'unable_to_add_or_remove_products': unable_to_add_or_remove_products += 1 if key == 'promotions': promotions += 1 if key == 'payment_options': payment_options += 1 if key == 'paypal': paypal += 1 if key == 'shipping_cost': shipping_cost += 1 if key == 'order_total_wrong': order_total_wrong += 1 if key == 'backorder': backorder += 1 if key == 'address_not_fitting_or_incorrect': address_not_fitting_or_incorrect +=1 if key in fulfillment_list: fulfillment += 1 if key == 'where_is_my_order': where_is_my_order += 1 if key == 'BOPIS': BOPIS += 1 if key == 'delivery_issues': delivery_issues += 1 if key == 'no_communication_or_delays': no_communication_or_delays += 1 if key == 'damaged_product': damaged_product += 1 if key == 'unassembled_assembly_issues': unassembled_assembly_issues += 1 if 'customer service' == key: customer_service += 1 if 'long-wait_times' == key: long_wait_times +=1 if 'contact_issues' == key: contact_issues +=1 if 'canada_related' == key: canada_related +=1 if 'product + info' == key: product_info += 1 if 'design issues' == key: design_issues += 1 if 'gift_wrapping' in key: gift_wrapping +=1 if 'stores' == key: store += 1 if 'email' == key: email += 1 if 'suggestions' == key: suggestions +=1 if 'rewards' == key: rewards +=1 if 'registry' == key: registry += 1 if 'returns_cancellations' in key: returns_cancellations +=1 </code></pre>
[]
[ { "body": "<p>All I did was convert all <code>if</code> statements with exact values into a dictionary. This way will allow you to increment the values of each key without as much <code>if</code>/<code>else</code> usage. If you then want to later on pass the values of each key to a variable of your choice, you ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T00:07:58.873", "Id": "204739", "Score": "1", "Tags": [ "python" ], "Title": "Count of category occurances (multiple cateogries can fall under each row)" }
204739
<p>I'm learning go by doing it. I tried to port the Java's ZsyncMake <a href="https://raw.githubusercontent.com/salesforce/zsync4j/master/zsync-core/src/main/java/com/salesforce/zsync/ZsyncMake.java" rel="nofollow noreferrer">implementation</a> into Golang. I also employ the Go's concurrency API with goroutine and channel. I have some experience in Java, but never work with native language. One immediately coming problem is <code>int</code> in Golang isn't the same as <code>int32</code> (since it depends on the platform; Java's <code>int</code> is 4 byte), thus I need to cast it most of the time.</p> <p>Here's my code. In some comments I wrote <code>[ASK]</code> to indicate that I'm not sure if it's a proper way of implementation in Go </p> <pre><code>package zsync import ( "bufio" "crypto/sha1" "encoding/binary" "encoding/hex" "goZsyncmake/md4" "goZsyncmake/zsyncOptions" "hash" "io" "log" "math" "os" "strconv" "time" ) var ZSYNC_VERSION = "0.6.2" var BLOCK_SIZE_SMALL = 2048 var BLOCK_SIZE_LARGE = 4096 func ZsyncMake(path string, options zsyncOptions.Options) { checksum, headers, zsyncFilePath := writeToFile(path, options) zsyncFile, err := os.Create(zsyncFilePath) if err != nil { log.Fatal(err) } defer zsyncFile.Close() bfio := bufio.NewWriter(zsyncFile) _, err = bfio.WriteString(headers) if err != nil { log.Fatal(err) } _, err = bfio.Write(checksum) if err != nil { log.Fatal(err) } bfio.Flush() } func writeToFile(path string, options zsyncOptions.Options) ([]byte, string, string) { file, err := os.Open(path) if err != nil { log.Fatal(err) } defer file.Close() outputFileName := file.Name() + ".zsync" fileInfo, err := file.Stat() if err != nil { log.Fatal(err) } opts := calculateMissingValues(options, file) blockSize := opts.BlockSize fileLength := fileInfo.Size() sequenceMatches := 0 if fileLength &gt; int64(options.BlockSize) { sequenceMatches = 2 } else { sequenceMatches = 1 } weakChecksumLength := weakChecksumLength(fileLength, blockSize, sequenceMatches) strongChecksumLength := strongChecksumLength(fileLength, blockSize, sequenceMatches) fileDigest := sha1.New() blockDigest := md4.New() checksum, fileChecksum := computeChecksum(file, blockSize, fileLength, weakChecksumLength, strongChecksumLength, fileDigest, blockDigest) strFileChecksum := hex.EncodeToString(fileChecksum) // [ASK] I suspect I can improve performance here rather than appending string with + strHeader := "zsync: " + ZSYNC_VERSION + "\n" + "Filename: " + fileInfo.Name() + "\n" + "MTime: " + fileInfo.ModTime().Format(time.RFC1123Z) + "\n" + "Blocksize: " + strconv.Itoa(blockSize) + "\n" + "Length: " + strconv.Itoa(int(fileLength)) + "\n" + "Hash-Lengths: " + strconv.Itoa(sequenceMatches) + "," + strconv.Itoa(weakChecksumLength) + "," + strconv.Itoa(strongChecksumLength) + "\n" + "URL: " + opts.Url + "\n" + "SHA-1: " + strFileChecksum + "\n\n" return checksum, strHeader, outputFileName } func sha1HashFile(path string, fileChecksumChannel chan []byte) { file, err := os.Open(path) if err != nil { log.Fatal(err) } defer file.Close() hasher := sha1.New() if _, err := io.Copy(hasher, file); err != nil { log.Fatal(err) } fileChecksumChannel &lt;- hasher.Sum(nil) } func computeChecksum(f *os.File, blocksize int, fileLength int64, weakLen int, strongLen int, fileDigest hash.Hash, blockDigest hash.Hash) ([]byte, []byte) { checksumBytes := make([]byte, 0) block := make([]byte, blocksize) fileChecksumChannel := make(chan []byte) go sha1HashFile(f.Name(), fileChecksumChannel) for { read, err := f.Read(block) if err != nil { if err == io.EOF { break } log.Fatal(err) } if read &lt; blocksize { blockSlice := block[read:blocksize] for i := range blockSlice { blockSlice[i] = byte(0) } } rsum := computeRsum(block) unsignedWeakByte := make([]byte, 4) binary.BigEndian.PutUint32(unsignedWeakByte, uint32(rsum)) tempUnsignedWeakByte := unsignedWeakByte[len(unsignedWeakByte)-weakLen:] checksumBytes = append(checksumBytes, tempUnsignedWeakByte...) blockDigest.Reset() blockDigest.Write(block) strongBytes := blockDigest.Sum(nil) tempUnsignedStrongByte := strongBytes[:strongLen] checksumBytes = append(checksumBytes, tempUnsignedStrongByte...) } fileChecksum := &lt;- fileChecksumChannel checksumBytes = append(checksumBytes, fileChecksum...) return checksumBytes, fileChecksum } // [ASK] A lot of type casting happen here, not sure if it's a good practice in Go func strongChecksumLength(fileLength int64, blocksize int, sequenceMatches int) int { // estimated number of bytes to allocate for strong checksum d := (math.Log(float64(fileLength))+math.Log(float64(1+fileLength/int64(blocksize))))/math.Log(2) + 20 // reduced number of bits by sequence matches lFirst := float64(math.Ceil(d / float64(sequenceMatches) / 8)) // second checksum - not reduced by sequence matches lSecond := float64((math.Log(float64(1+fileLength/int64(blocksize)))/math.Log(2) + 20 + 7.9) / 8) // return max of two: return no more than 16 bytes (MD4 max) return int(math.Min(float64(16), math.Max(lFirst, lSecond))) } // [ASK] A lot of type casting happen here, not sure if it's a good practice in Go func weakChecksumLength(fileLength int64, blocksize int, sequenceMatches int) int { // estimated number of bytes to allocate for the rolling checksum per formula in // Weak Checksum section of http://zsync.moria.org.uk/paper/ch02s03.html d := (math.Log(float64(fileLength))+math.Log(float64(blocksize)))/math.Log(2) - 8.6 // reduced number of bits by sequence matches per http://zsync.moria.org.uk/paper/ch02s04.html rdc := d / float64(sequenceMatches) / 8 lrdc := int(math.Ceil(rdc)) // enforce max and min values if lrdc &gt; 4 { return 4 } else { if lrdc &lt; 2 { return 2 } else { return lrdc } } } // [ASK] A lot of type casting happen here, not sure if it's a good practice in Go func computeRsum(block []byte) int { var a int16 var b int16 l := len(block) for i := 0; i &lt; len(block); i++ { val := int(unsign(block[i])) a += int16(val) b += int16(l * val) l-- } x := int(a) &lt;&lt; 16 y := int(b) &amp; 0xffff return int(x) | int(y) } func unsign(b byte) uint8 { if b &lt; 0 { return b &amp; 0xFF } else { return b } } func calculateMissingValues(opts zsyncOptions.Options, f *os.File) zsyncOptions.Options { if opts.BlockSize == 0 { opts.BlockSize = calculateDefaultBlockSizeForInputFile(f) } if opts.Filename == "" { opts.Filename = f.Name() } if opts.Url == "" { opts.Url = f.Name() } return opts } func calculateDefaultBlockSizeForInputFile(f *os.File) int { fileInfo, err := f.Stat() if err != nil { log.Fatal(err) } if fileInfo.Size() &lt; 100*1&lt;&lt;20 { return BLOCK_SIZE_SMALL } else { return BLOCK_SIZE_LARGE } } </code></pre> <p>Also, coming from Java background, I get use to modularize everything, including this Options struct onto other file. Am I suppose to modularize it?</p> <pre><code>package zsyncOptions type Options struct { BlockSize int Filename string Url string } </code></pre>
[]
[ { "body": "<h3>Always return errors</h3>\n\n<p>Don't use <code>log.Fatal()</code> everywhere ! Instead, return the error with some context: </p>\n\n<pre><code>checksum, fileChecksum, err := computeChecksum(fileByte, options.BlockSize, weakChecksumLength, strongChecksumLength)\nif err != nil {\n return fmt.Er...
{ "AcceptedAnswerId": "210534", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T07:04:02.547", "Id": "204752", "Score": "4", "Tags": [ "file", "go", "casting", "checksum" ], "Title": "Making a Zsync file archive with checksums" }
204752
<p>I recently built a CI for my course project in C. I made 3 stages, to build docker image, compile my C sources and run the said project.</p> <p>That said, i think i could've do way better <a href="https://gitlab.com/artandor/cours-cpp/" rel="nofollow noreferrer">here</a> but i don't really know how. I don't have a really big experience with CI, and even if that one works i would like to hear about what you think about it.</p> <p>What i would like to improve is scalability, generality (there probably will be a need at some point to separate my dockerfiles per subproject (main-atoi is a subproject), ...</p> <p>Source code here : <a href="https://gitlab.com/artandor/cours-cpp/" rel="nofollow noreferrer">Gitlab</a></p> <p><strong>Docker file</strong></p> <pre><code>FROM debian:stretch RUN apt-get update \ &amp;&amp; apt-get install gcc g++ -y ADD ./ /home VOLUME /home/build /home/build </code></pre> <p><strong>.gitlab-ci.yml</strong></p> <pre><code>stages: - build-image - build - run before_script: - docker info build-image: stage: build-image tags: - build-docker script: - docker build -t artandor/debian9-cpp:v1-tp1 . build: stage: build tags: - cours script: - docker run -v /home/build:/home/build --rm artandor/debian9-cpp:v1-tp1 gcc -Wall -Werror /home/main-atoi/myatoibase.c /home/main-atoi/main-atoi.c -o /home/build/main-test run: stage: run dependencies: - build tags: - cours script: - docker run -v /home/build:/home/build --rm artandor/debian9-cpp:v1-tp1 /home/build/main-test - cp /home/build/main-test ./ artifacts: name: "Main Atoi Binary - $CI_COMMIT_REF_NAME" paths: - ./main-test </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T09:01:00.483", "Id": "394896", "Score": "0", "body": "I added the code. Sorry for not respecting the guidelines, but it seemed to be a bit big to add it here. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate...
[ { "body": "<p>You can have a separate project for your Dockfile and let gitlab keep the image in a <a href=\"https://docs.gitlab.com/ee/ci/docker/using_docker_build.html\" rel=\"nofollow noreferrer\">container repository</a>. That way you will not need to rebuild the image every build and you can reuse the cont...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T08:18:04.800", "Id": "204755", "Score": "2", "Tags": [ "c", "integration-testing", "dockerfile" ], "Title": "Dockerfile + CI for C build" }
204755
<p>I'm working on a clientside iOS app for my school that involves students purchasing things, and I wrote a <code>String</code> extension for formatting a <code>String</code> into USD. Is there a way to improve this or make it more "swifty"?</p> <pre><code>extension String { var usdFormat: String { var str = self var postDec = str.components(separatedBy: ".") switch postDec[1].count { case 0: str.append("00") case 1: str.append("0") default: break } str = "$" + str return str } } </code></pre>
[]
[ { "body": "<p>I would begin with more descriptive variable names. Something like <code>formattedString</code> and <code>splitComponents</code> would work in this case. The <code>postDec</code> or <code>splitComponents</code> variable is never mutated so that can be declared as a let.</p>\n\n<pre><code>extensio...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T08:33:32.823", "Id": "204756", "Score": "1", "Tags": [ "strings", "swift", "formatting", "extension-methods", "fixed-point" ], "Title": "Converting a String to USD" }
204756
<p>I'm trying to learn Vuejs and started this project: <a href="https://github.com/GhitaB/datatables-admin" rel="nofollow noreferrer">https://github.com/GhitaB/datatables-admin</a> (Live demo: <a href="https://ghitab.github.io/datatables-admin/" rel="nofollow noreferrer">https://ghitab.github.io/datatables-admin/</a>).</p> <p>Copied the current version (the question will refer to it): <a href="https://jsfiddle.net/ns6umqv2/" rel="nofollow noreferrer">https://jsfiddle.net/ns6umqv2/</a></p> <p>My goal is to have a nice admin panel that will be used by editors to generate tables containing lists of items. An item basically will be a link (URL) + some metadata (the other columns defined by editor).</p> <p>The content will be saved somewhere as json (not needed for the moment). In view mode that json will be rendered as Datatable.</p> <p>In this simplified version you can:</p> <ul> <li>define columns, change their order, delete</li> <li>define rows, change their order, delete</li> <li>edit any cell (navigate between editable cell using Tab / Shift + Tab)</li> <li>delete all columns, delete all rows</li> <li>render the current table as Datatable (and re-render anytime) by pressing "Preview table" button</li> <li>sort the rendered table, filter by any word (the URL is included as searchable text)</li> </ul> <p>Please take a look, I fell like it can be improved - but I can't see exactly where and how.</p> <p>Also, feel free to contribute on GitHub if you like the idea.</p> <p><strong>js code:</strong></p> <pre><code>Vue.component('editable', { template: ` &lt;div contenteditable="true" @blur="emitChange"&gt; {{ content }} &lt;/div&gt; `, props: ['content'], methods: { emitChange(ev) { this.$emit('update', ev.target.textContent) } } }); Vue.component('table-preview', { template: ` &lt;div class="table-preview-container"&gt; &lt;button class='render-table' v-on:click="render_table"&gt;Preview table&lt;/button&gt; &lt;table class="table-render-preview"&gt;&lt;/table&gt; &lt;/div&gt; `, props: ['content'], methods: { render_table() { var columns = this.$parent.columns; var rows = this.$parent.rows; var el = event.srcElement; var parent = el.offsetParent; var table_placeholder = document.querySelector('.table-render-preview'); function make_table_html(columns, rows) { function render_link(url) { if(url !== undefined) { return "&lt;a href='" + url +"' target='_blank' title=" + url + "&gt;Link&lt;span style='display:none !important'&gt;" + url + "&lt;/span&gt;&lt;/a&gt;"; } else { return "N/A"; } } var result = "&lt;table border=1&gt;&lt;thead&gt;&lt;tr&gt;"; for(var i = 0; i &lt; columns.length; i++) { result += "&lt;th&gt;" + columns[i] + "&lt;/th&gt;"; } result += "&lt;/thead&gt;&lt;tbody&gt;" for(var i = 0; i &lt; rows.length; i++) { result += "&lt;tr&gt;"; for(var j = 0; j &lt; rows[i].length; j++) { if(columns[j] == "URL") { result += "&lt;td&gt;" + render_link(rows[i][j]) + "&lt;/td&gt;"; } else { result += "&lt;td&gt;" + rows[i][j] + "&lt;/td&gt;"; } } result += "&lt;/tr&gt;"; } result += "&lt;/tbody&gt;&lt;/table&gt;"; return result; } if ($.fn.DataTable.isDataTable(".table-render-preview")) { $('.table-render-preview').DataTable().clear().destroy(); } var new_el = document.createElement("table"); new_el.className = "table-render-preview"; new_el.innerHTML = make_table_html(columns, rows); table_placeholder.parentNode.replaceChild(new_el, table_placeholder); $('.table-render-preview').dataTable({ "destroy": true, aaSorting: [] }); } } }); new Vue({ el: '#datatables-admin', data: { LOREM: "Click me to edit", NONE: "", columns: ['Click me to edit', 'Demo column 2', 'Demo column 3', 'URL'], rows: [ ['col1 data1', 'col2 data1', 'col3 data1', 'https://www.google.com'], ['col1 data2', 'col2 data2', 'col3 data2', 'https://www.yahoo.com'] ], }, methods: { refresh: function() { this.$forceUpdate(); }, update_col: function(content, col_index) { this.columns[col_index] = content; this.refresh(); }, update_row: function(content, row_index, col_index) { this.rows[row_index][col_index] = content; this.refresh(); }, add_col: function(col_index) { // Add a new column at given index this.columns.splice(col_index, 0, this.LOREM); for(var i = 0; i &lt; this.rows.length; i++) { var row = this.rows[i]; row.splice(col_index, 0, this.NONE); } this.refresh(); }, delete_col: function(col_index, skip_confirm = false) { if(!skip_confirm) { var result = confirm("Are you sure you want to delete this column?"); if(!result) { return; } } // Remove column this.columns.splice(col_index, 1); // Remove related items in rows for(var i = 0; i &lt; this.rows.length; i++) { var row = this.rows[i]; row.splice(col_index, 1); } this.refresh(); }, add_row: function(row_index) { // Add a new row at given index this.rows.splice(row_index, 0, new Array(this.columns.length)); for(var i = 0; i &lt; this.columns.length; i++) { this.rows[row_index][i] = this.NONE; } this.refresh(); }, delete_row: function(row_index, skip_confirm = false) { if(!skip_confirm) { var result = confirm("Are you sure you want to delete this row?"); if(!result) { return; } } this.rows.splice(row_index, 1); this.refresh(); }, delete_all_rows: function() { var result = confirm("Are you sure you want to delete all rows?"); if(!result) { return; } var nr_rows = this.rows.length; for(var i = 0; i &lt; nr_rows; i++) { this.delete_row(0, skip_confirm = true); } this.refresh(); }, delete_all_cols: function() { var result = confirm("Are you sure you want to delete all columns?"); if(!result) { return; } var nr_cols = this.columns.length; for(var i = 0; i &lt; nr_cols; i++) { this.delete_col(0, skip_confirm = true); } this.refresh(); }, move_col_to_left: function(col_index) { if(col_index == 0) { return; } var temp = this.columns[col_index - 1]; this.columns[col_index - 1] = this.columns[col_index]; this.columns[col_index] = temp; for(var i = 0; i &lt; this.rows.length; i++) { temp = this.rows[i][col_index - 1]; this.rows[i][col_index - 1] = this.rows[i][col_index]; this.rows[i][col_index] = temp; } this.refresh(); }, move_col_to_right: function(col_index) { if(col_index == this.columns.length - 1) { return; } var temp = this.columns[col_index + 1]; this.columns[col_index + 1] = this.columns[col_index]; this.columns[col_index] = temp; for(var i = 0; i &lt; this.rows.length; i++) { temp = this.rows[i][col_index + 1]; this.rows[i][col_index + 1] = this.rows[i][col_index]; this.rows[i][col_index] = temp; } this.refresh(); }, move_row_up: function(row_index) { if(row_index == 0) { return; } var temp = this.rows[row_index - 1]; this.rows[row_index - 1] = this.rows[row_index]; this.rows[row_index] = temp; this.refresh(); }, move_row_down: function(row_index) { if(row_index == this.rows.length - 1) { return; } var temp = this.rows[row_index + 1]; this.rows[row_index + 1] = this.rows[row_index]; this.rows[row_index] = temp; this.refresh(); } } }); </code></pre> <p><strong>html:</strong></p> <pre><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,chrome=1" /&gt; &lt;title&gt;Datatables admin&lt;/title&gt; &lt;meta name="description" content="Datatables administration panel" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; &lt;link rel="stylesheet" href="styles.css" /&gt; &lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous" /&gt; &lt;link rel="stylesheet" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" /&gt; &lt;/head&gt; &lt;body class="dta"&gt; &lt;div id="datatables-admin"&gt; &lt;h1&gt;Datatables admin&lt;/h1&gt; &lt;table id="editor"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th v-for="(column, index_col) in columns" :key="index_col"&gt; &lt;i class="fas fa-long-arrow-alt-left fa-2x dta-btn move-col-left" title="Move column to left" v-on:click="move_col_to_left(index_col)"&gt;&lt;/i&gt; &lt;i class="fas fa-long-arrow-alt-right fa-2x dta-btn move-col-right" title="Move column to right" v-on:click="move_col_to_right(index_col)"&gt;&lt;/i&gt; &lt;i class="fas fa-plus fa-2x dta-btn add-col" title="Add a column after this one" v-on:click="add_col(index_col + 1)"&gt;&lt;/i&gt; &lt;i class="fas fa-times fa-2x dta-btn delete-col" title="Delete this column" v-on:click="delete_col(index_col)"&gt;&lt;/i&gt; &lt;br /&gt; &lt;editable :content="columns[index_col]" v-on:update="update_col($event, index_col)"&gt;&lt;/editable&gt; &lt;/th&gt; &lt;th&gt; &lt;i class="fas fa-plus fa-2x dta-btn add-col" title="Add a column" v-on:click="add_col(0)"&gt;&lt;/i&gt; &lt;i class="fas fa-plus fa-2x dta-btn add-row" title="Add a row" v-on:click="add_row(0)"&gt;&lt;/i&gt; &lt;i class="fas fa-times fa-2x dta-btn delete-all-cols" title="Delete all columns" v-on:click="delete_all_cols"&gt;&lt;/i&gt; &lt;i class="fas fa-times fa-2x dta-btn delete-all-rows" title="Delete all rows" v-on:click="delete_all_rows"&gt;&lt;/i&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr v-for="(row, index_row) in rows" :key="index_row"&gt; &lt;td v-for="(column, index_col) in columns" :key="index_col"&gt; &lt;editable :content="rows[index_row][index_col]" v-on:update="update_row($event, index_row, index_col)"&gt;&lt;/editable&gt; &lt;td&gt; &lt;i class="fas fa-long-arrow-alt-up fa-2x dta-btn move-row-up" v-on:click="move_row_up(index_row)" title="Move row up"&gt;&lt;/i&gt; &lt;i class="fas fa-long-arrow-alt-down fa-2x dta-btn move-row-down" v-on:click="move_row_down(index_row)" title="Move row down"&gt;&lt;/i&gt; &lt;i class="fas fa-plus fa-2x dta-btn add-row" title="Add a row under this one" v-on:click="add_row(index_row + 1)"&gt;&lt;/i&gt; &lt;i class="fas fa-times fa-2x dta-btn delete-row" title="Delete this row" v-on:click="delete_row(index_row)"&gt;&lt;/i&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;table-preview&gt;&lt;/table-preview&gt; &lt;/div&gt; &lt;script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt;&lt;!-- dev --&gt; &lt;!-- &lt;script src="https://cdn.jsdelivr.net/npm/vue"&gt;&lt;/script&gt; --&gt; &lt;script src="datatables-admin.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Styles:</strong></p> <pre><code>/* https://coolors.co/96adc8-d7ffab-fcff6c-d89d6a-6d454c #96adc8 #d7ffab #fcff6c #d89d6a #6d454c */ @import url('https://fonts.googleapis.com/css?family=Open+Sans|Tangerine'); body.dta { font-family: 'Open Sans', sans-serif; background: #6d454c; color: #6d454c; } body.dta div#datatables-admin { background: #EEEEEE; padding: 20px; margin: 20px; } body.dta div#datatables-admin h1 { font-family: 'Tangerine', cursive; color: #d89d6a; text-align: center; font-size: 86px; font-weight: 500; margin: 20px; } body.dta div#datatables-admin table#editor { background: #CCCCCC; padding: 10px; border-spacing: 5px; color: #111111; margin: auto; } body.dta div#datatables-admin table#editor tr, body.dta div#datatables-admin table#editor td, body.dta div#datatables-admin table#editor th { background: #FFFFFF; padding: 5px; margin: 5px; text-align: center; } body.dta div#datatables-admin table#editor th { user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -o-user-select: none; } body.dta div#datatables-admin .dta-btn { color: #96adc8; user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -o-user-select: none; } body.dta div#datatables-admin .dta-btn:hover { color: #d89d6a; cursor: pointer; } body.dta div#datatables-admin div.table-preview-container { text-align: center; margin-top: 40px; } body.dta div#datatables-admin table.table-render-preview { margin: auto; } body.dta div#datatables-admin button.render-table { margin-bottom: 40px; padding: 10px; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T16:37:09.783", "Id": "394968", "Score": "1", "body": "Welcome to Code Review! Unfortunately we can't review this because you explained a bug scenario. Please read [What topics can I ask about here?](https://codereview.stackexchange....
[ { "body": "<h1>General feedback</h1>\n\n<p>Whenever I see jQuery and VueJS used together, I question whether they both need to be used. For example, many of the jQuery selection can be converted to using <a href=\"https://vuejs.org/v2/api/#ref\" rel=\"nofollow noreferrer\"><code>$refs</code></a> or perhaps some...
{ "AcceptedAnswerId": "205405", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T09:22:11.883", "Id": "204757", "Score": "2", "Tags": [ "javascript", "ecmascript-6", "vue.js", "jquery-datatables" ], "Title": "Editable table admin panel using Vuejs & Datatables" }
204757
<p>The program we are working at has the following function:</p> <pre><code>function loadItem(arrayValues,arrayNames) { var j=document.getElementById('itemSelect').options.length; for(var i=0;i&lt;arrayValues.length;i++) { if(!existsElement(document.getElementById('itemSelect'),arrayValues[i])) { document.getElementById('itemSelect').options[j]=new Option(arrayValues[i]+" - "+arrayNames[i],arrayValues[i],null); j++; } } } </code></pre> <p>This fills a list that is later used to filter a search.</p> <p>It was originally designed for small arrays (up to 25 elements) and it worked perfectly.</p> <p>Now, I'm trying to use it to fill with the whole contents of a SQL table (about 9500 elements), I take the data from the DB with Java, transfer it to Javascript via AJAX and parse that List into two arrays that can be used with this function. That takes about a second, but then this function takes about 20 seconds to complete.</p> <p>Why is it that slow, and what can I do to improve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T10:45:11.387", "Id": "394907", "Score": "2", "body": "Please reveal more details about how this method is used and what else your page is doing etc. Maybe there are some automatic event handlers... who knows. We need more info." }...
[ { "body": "<p>DOM operations are costly, so use variables.</p>\n\n<pre><code>var is=document.getElementById('itemSelect');\nfor(var i=0;i&lt;arrayValues.length;i++) {\n if(!existsElement(is,arrayValues[i])) {\n is.options.push(new Option(arrayValues[i]+\" - \"+arrayNames[i],arrayValues[i],null));\n ...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T10:24:56.657", "Id": "204759", "Score": "1", "Tags": [ "javascript", "performance" ], "Title": "Loading items into array from SQL Server" }
204759