body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>As practice, I have written a prime number sieve in Standard ML.</p> <p>It works in a pretty straightforward way:</p> <ol> <li>The list of known primes starts with just 2.</li> <li>Starting with 3, check whether each odd integer is relatively prime to all numbers in the list of known primes (i.e. is not divisible by them) <ul> <li>If it's relatively prime, add it to the list of known primes.</li> <li>If it's not, check the next odd integer.</li> </ul></li> <li>Repeat step 2 until the list has however many primes we're looking for.</li> <li>Reverse the list so that the primes are in ascending order.</li> </ol> <p>Here's my code:</p> <pre><code>fun primes 0 = [] | primes n = let fun relativelyPrime x = List.all (fn p =&gt; (x mod p &lt;&gt; 0)) fun buildPrimes ps x = if length ps &gt;= n then ps else if relativelyPrime x ps then buildPrimes (x::ps) (x + 2) else buildPrimes ps (x + 2) in rev (buildPrimes [2] 3) end </code></pre> <p>I'm still fairly new to Standard ML, so I doubt the above code is optimal or entirely idiomatic. Are there any improvements I could have made if I knew more about the language?</p> <p>(Note: I realize that negative numbers will return <code>[2]</code>. I could raise an exception, but that's not the point of this question.)</p>
[]
[ { "body": "<blockquote>\n<pre><code> fun buildPrimes ps x =\n if length ps &gt;= n then ps\n</code></pre>\n</blockquote>\n\n<p>Don't forget that <code>length</code> is expensive. It's definitely worth using an extra accumulator variable to track either the length or the number of primes left to fi...
{ "AcceptedAnswerId": "199863", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T15:28:02.117", "Id": "199840", "Score": "3", "Tags": [ "primes", "sml" ], "Title": "Prime number sieve in Standard ML" }
199840
<p>As I'm learning to program in C, I'm making my way through K&amp;R. </p> <p>The goal of the exercise is to add a option to the program so that the sorting does not depend on upper or lower-case letters. </p> <p>What are your opinions on my use of function pointers in this exercise? Do you see any obvious beginner traps in the code? </p> <pre><code>#include "main.h" char *pointersToLines[MAX_NO_OF_LINES]; int (*compareFunctionPointers[3])(void *, void *); int main(int argc, char *argv[]) { // Store pointers to the diffrent types of // compare functions in a array of // function pointers. compareFunctionPointers[COMPARE_DEFAULT] = &amp;strcmp; compareFunctionPointers[COMPARE_FOLDED] = &amp;strcmpFold; compareFunctionPointers[COMPARE_NUMERICLY] = &amp;numcmp; int numberOfLines; int sortDecreasing = 0; // 1 if the input is to be sorted in a decreasing order int compareFunction = COMPARE_DEFAULT; // Index for the compare-function // Parse the command line arguments if (argc &gt; 1) { for (int i = 1; *(argv + i); i++) { char *c = *(argv + i); if(strcmp(c, "-n") == 0) compareFunction = COMPARE_NUMERICLY; if(strcmp(c, "-r") == 0) sortDecreseingly = 1; if(strcmp(c, "-f")) compareFunction = COMPARE_FOLDED; } } if ((numberOfLines = readLines(pointersToLines, MAX_NO_OF_LINES)) &gt;= 0) { qsort1((void **)pointersToLines, 0, numberOfLines - 1, (int (*)(void *, void *))compareFunctionPointers[compareFunction], sortDecreasing); writeLines(pointersToLines, numberOfLines); return 0; } } </code></pre> <h3>Sorting Function</h3> <pre><code>void qsort1(void *v[], int left, int right, int (*comp)(void *, void *), int increesingOrDecresing) { int last, compare; //Base case if (left &gt;= right) { return; } swap(v, left, (right + left) / 2); last = left; for (int i = left + 1; i &lt;= right; i++) { compare = (increesingOrDecresing) ? -(*comp)(v[i], v[left]) : (*comp)(v[i], v[left]); if (compare &lt; 0) swap(v, ++last, i); } swap(v, last, left); qsort1(v, left, last - 1, comp, increesingOrDecresing); qsort1(v, last + 1, right, comp, increesingOrDecresing); } </code></pre> <p><strong>Compare functions</strong></p> <pre><code>int strcmpFold(char *s1, char *s2) { while (toupper(*s1) == toupper(*s2)) { s1++; s2++; } if (toupper(*s1) &lt; toupper(*s2)) return -1; else if (toupper(*s1) &gt; toupper(*s2)) return 1; else return 0; } int numcmp(char *s1, char *s2) { double v1, v2; v1 = atof(s1); v2 = atof(s2); if (v1 &lt; v2) return -1; else if (v1 &gt; v2) return 1; else return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T18:07:35.350", "Id": "384590", "Score": "0", "body": "I left them out since i did not really find them that important. Just simple compare functions similar to strcmp" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate...
[ { "body": "<p>I'd use a <code>typedef</code> for a pointer to your compare functions:</p>\n\n<pre><code>typedef int (*cmpfnc)(void *,void *);\n</code></pre>\n\n<p>This simplifies things and eliminates the ugly cast used in <code>main</code>'s call to <code>qsort1</code></p>\n\n<p>I'd remove the <code>&amp;</cod...
{ "AcceptedAnswerId": "199893", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T16:34:13.597", "Id": "199846", "Score": "1", "Tags": [ "c", "pointers" ], "Title": "K&R Exercise 5-15: sorting with extra options" }
199846
<p>I've not used this site before, I would like to get opinions on the code I've completed for my first 'program' in Python. I would like to understand how 'good' it is and where it can be improved, anything that says "you're clearly a beginner and haven't learned xxx" would be helpful.</p> <p>Background to project: My payslips are in a weird format with info dotted around all over a spreadsheet and have slight variations in positioning month on month. For example the value of a field might not be in the adjacent cell it might be below it for one field and to the right for another (although this relative positioning is consistent month on month) I combined manually all the months into one Excel and wanted to structure the data so I could eventually run calculations on it to ensure it was correct and my taxes were correct (still need to do that part).</p> <pre><code># -*- coding: utf-8 -*- import openpyxl def get_data(ws): data = [] for y in range(1,ws.max_row + 1): rows = [] for x in range(1,ws.max_column + 1): rows.append(ws.cell(column = x, row = y).value) data.append(rows) return data def search_data(data, criteria): location = [] for row in range(len(data)): for column in range(len(data[row])): if data[row][column] == criteria: location.append([row,column]) if len(location) == 0: print('Not present on sheet') return None return location def offset(location,rows,columns): location[0] = location[0] + rows location[1] = location[1] + columns return location def get_table(data, startloc, columns=None): count = 1 rows = 1 table = [] temprow = startloc[0] tempcol = startloc[1] while count != 0: if data[temprow][tempcol] != None: temprow = temprow + 1 if temprow == len(data): break else: count = 0 rows = temprow - startloc[0] if columns == None: temprow = startloc[0] tempcol = startloc[1] count = 1 while count != 0: if data[temprow][tempcol] != None: tempcol = tempcol + 1 if tempcol == len(data[temprow]): break else: count = 0 columns = tempcol - startloc[1] for y in range(rows): table_rows = [] for x in range(columns): table_rows.append(data[startloc[0]+y][startloc[1]+x]) table.append(table_rows) return table def get_value(data, location): return data[location[0]][location[1]] def get_tax_info(ws): data = get_data(ws) tax_info = [] #gets individual values tax_period = get_value(data,offset(search_data(data,'Calendar Month')[0],0,1)) tax_period_ending = get_value(data,offset(search_data(data,'Calendar Month')[0],0,2)) tax_code = get_value(data,offset(search_data(data, 'Tax Code')[0],1,0)) tax_basis = get_value(data,offset(search_data(data, 'Tax Basis')[0],1,0)) NI_category = get_value(data,offset(search_data(data,'NI Category')[0],1,0)) total_payments = get_value(data,offset(search_data(data,'Total Payments')[0],1,0)) net_pay = get_value(data,offset(search_data(data,'Net Pay')[0],1,0)) #gets tables payments = get_table(data,offset(search_data(data,'Payments')[0],4,0)) deductions = get_table(data,offset(search_data(data,'Deductions')[0],4,0)) balances = get_table(data,offset(search_data(data,'Balances')[0],4,0)) #combine tax_info.extend([tax_period, tax_period_ending, tax_code, tax_basis, NI_category, total_payments, net_pay]) tax_info.append(payments) tax_info.append(deductions) tax_info.append(balances) return tax_info class payslip: def __init__(self, tax_period, tax_period_ending, tax_code, tax_basis, NI_category, total_payments, net_pay, payments, deductions, balances): 'Creates a payslip object with all the fields of the payslip' self.tax_period_ending = tax_period_ending self.tax_code = tax_code self.tax_basis = tax_basis self.NI_category = NI_category self.total_payments = total_payments self.net_pay = net_pay self.payments = payments self.deductions = deductions self.balances = balances wb = openpyxl.load_workbook('.../Payslips.xlsx') sheet_names = wb.sheetnames payslips = [] for i in range(0,len(sheet_names)): each = sheet_names[i] ws = wb[each] tax_info = get_tax_info(ws) payslips.append(payslip(tax_info[0], tax_info[1], tax_info[2], tax_info[3], tax_info[4], tax_info[5], tax_info[6], tax_info[7],tax_info[8],tax_info[9])) wb2 = openpyxl.Workbook() ws2 = wb2.active ws2.title = 'Payslips Summary' ws2['A1'],ws2['B1'],ws2['C1'],ws2['D1'],ws2['E1'], ws2['F1'] = 'tax_period_ending', 'total_payments', 'net_pay', 'tax_code', 'NI_category', 'tax_basis' for i in range(0,len(payslips)): ws2.cell(row=i+2, column=1).value = payslips[i].tax_period_ending ws2.cell(row=i+2, column=2).value = payslips[i].total_payments ws2.cell(row=i+2, column=3).value = payslips[i].net_pay ws2.cell(row=i+2, column=4).value = payslips[i].tax_code ws2.cell(row=i+2, column=5).value = payslips[i].NI_category ws2.cell(row=i+2, column=6).value = payslips[i].tax_basis wb2.save('Payslips_Summary.xlsx') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T18:12:50.167", "Id": "384592", "Score": "0", "body": "Is this Python 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T19:03:05.097", "Id": "384605", "Score": "0", "body": "Yes it should ...
[ { "body": "<blockquote>\n<pre><code>for x in range(1,ws.max_column + 1):\n rows.append(ws.cell(column = x, row = y).value)\n</code></pre>\n</blockquote>\n<p>One of the biggest savers in overhead is <a href=\"https://openpyxl.readthedocs.io/en/stable/tutorial.html#accessing-many-cells\" rel=\"nofollow norefer...
{ "AcceptedAnswerId": "199854", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T17:55:53.973", "Id": "199849", "Score": "1", "Tags": [ "python", "python-3.x", "excel" ], "Title": "Read unstructured Excel payslip and export to structured Excel table" }
199849
<p>For practice JavaScript I created simple To-do app.<br /> This app can add TODOs and track the number of total TODOs as well as the number of unchecked TODOs.<br /> For this I written 4 functions:</p> <ul> <li>for add newTodo - newTodo(), where I add new todo to todos array</li> <li>for render list of todo - drawTodoList(), where I also add event listener to each checkbox item</li> <li>confirmCheck() for change state of todo checked property</li> <li>countItem() for counting all items and unchecked items</li> </ul> <h2>My questions:</h2> <ul> <li>was it right to use innerHTML to add li items?</li> <li>adding event listener to all checkboxes in my case takes 4 line (in end drawTodoList). How can I short this?</li> <li>how can I improve my function countItem()?</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const todos = [] let newTodoId = 0 let checkboxes let checkboxArray const classNames = { TODO_ITEM: 'todo-container', TODO_CHECKBOX: 'todo-checkbox', TODO_TEXT: 'todo-text', TODO_DELETE: 'todo-delete', } const list = document.getElementById('todo-list') const itemCountSpan = document.getElementById('item-count') const uncheckedCountSpan = document.getElementById('unchecked-count') function newTodo() { let getTodo = prompt("Add new to-do", "") if(getTodo == null || getTodo == "") { console.log("you don't add new to-do") } else { todos.push({ id: newTodoId ++, text: getTodo, isChecked: false, }) drawTodoList() } } function drawTodoList() { const liItem = todos.map((todo) =&gt; { if (!todo.isChecked) { return `&lt;li id=${todo.id} class=${classNames.TODO_ITEM}&gt; &lt;input type='checkbox' class=${classNames.TODO_CHECKBOX}&gt;${todo.text}&lt;/li&gt;` } else { return `&lt;li id=${todo.id} class=${classNames.TODO_ITEM}&gt; &lt;input type='checkbox' class=${classNames.TODO_CHECKBOX} checked&gt;${todo.text}&lt;/li&gt;` } }) list.innerHTML = liItem.join('') checkboxes = document.querySelectorAll('input[type=checkbox]') checkboxArray = Array.from(checkboxes) checkboxArray.forEach(function(checkbox) { checkbox.addEventListener('change', confirmCheck) }) countItem() } function confirmCheck() { let checkedToDo = todos.find(todo =&gt; { return todo.id == this.parentElement.id }) checkedToDo.isChecked = !checkedToDo.isChecked countItem() } function countItem() { let itemCount = document.querySelectorAll('input[type="checkbox"]').length let checkedCount = document.querySelectorAll('input[type="checkbox"]:checked').length let uncheckedCount = itemCount - checkedCount itemCountSpan.innerHTML = itemCount uncheckedCountSpan.innerHTML = uncheckedCount }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.center { align-self: center; } .flow-right { display: flex; justify-content: space-around; } .container { max-width: 800px; margin: 0 auto; padding: 10px; display: flex; flex-direction: column; background-color: white; height: 100vh; } .title, .controls, .button { flex: none; } .button { padding: 10px 20px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;TODO App&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="./styles.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container center"&gt; &lt;h1 class="center title"&gt;My TODO App&lt;/h1&gt; &lt;div class="flow-right controls"&gt; &lt;span&gt;Item count: &lt;span id="item-count"&gt;0&lt;/span&gt;&lt;/span&gt; &lt;span&gt;Unchecked count: &lt;span id="unchecked-count"&gt;0&lt;/span&gt;&lt;/span&gt; &lt;/div&gt; &lt;button class="button center" onClick="newTodo()"&gt;New TODO&lt;/button&gt; &lt;ul id="todo-list" class="todo-list"&gt;&lt;/ul&gt; &lt;/div&gt; &lt;script src="./script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>Adding to the DOM</h2>\n<p>There is no one right or wrong way to add to the DOM, each has its pros and cons.</p>\n<h3>Some options</h3>\n<ol>\n<li>Markup direct to the page via <code>element.innerHTML</code> (as you have done).</li>\n<li>Using the <a href=\"https://developer.mozilla.org/en-US/doc...
{ "AcceptedAnswerId": "200016", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T19:02:20.603", "Id": "199852", "Score": "1", "Tags": [ "javascript", "dom", "to-do-list" ], "Title": "To-do list with counting of checked items" }
199852
<p>Given the following instructions I have created a function that achieves the requirements. I feel my function is a bit too complex, though it does what it's supposed to. The difficult part for myself was avoiding the equality operators. The only way I could think to solve this is with a bit of math and a comparison operator. How can I simplify this function and save some editing time?</p> <blockquote> <p>Write a function <code>onlyOne</code> that accepts three arguments of any type.</p> <p><code>onlyOne</code> should return true only if exactly one of the three arguments are truthy. Otherwise, it should return false.</p> <p>Do not use the equality operators (<code>==</code> and <code>===</code>) in your solution.</p> </blockquote> <p>My function:</p> <pre><code>function onlyOne(input1, input2, input3){ output = false; let truthy = 0; let falsey = 0; if (!!input1) { truthy++; } else falsey++; if (!!input2) { truthy++; } else falsey++; if (!!input3) { truthy++; } else falsey++; if (falsey &gt; truthy) { output = true; } if (falsey &gt; 2) { output = false; } return output; } </code></pre> <p>(originally asked on StackOverflow and was directed here.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T19:40:59.050", "Id": "384611", "Score": "0", "body": "Welcome to Code Review. Couldn't you have your function use logical OR and just `return input1 || input2 || input3` ?" }, { "ContentLicense": "CC BY-SA 4.0", "Creatio...
[ { "body": "<p>I'd prefer one of these two versions for readability. They seem easy enough to reason about, and don't hide the logic for choosing a result behind some counter variables, whose state the reader would need to keep track of.</p>\n\n<p>Just keep it simple.</p>\n\n<pre><code>function onlyOne(a, b, c){...
{ "AcceptedAnswerId": "199864", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T19:31:49.797", "Id": "199853", "Score": "16", "Tags": [ "javascript" ], "Title": "Function to test if exactly one of three parameters is truthy, without using equality operators" }
199853
<p>I have managed to write this piece of code but as I am using it on big data sets it ends up being quite slow. I am pretty sure it would be possible to optimize it but I am very knew to coding and I don't really know where to start.. I think getting rid of the for loop would be one way but honestly I'm lost. A little bit of help would be greatly appreciated !</p> <p>Basically, the point is to look if one row of the 'data' dataframe match one row of the 'ref' dataframe. And I use np.isclose in order to allow for small differences in the value as I know my 'data' values can be slightly different than the 'ref' values.</p> <p>Also, because my rows can have a lot of NaN values in them, I first use np.isnan to get the index of where is my last 'real' value in the row and then only do the row comparison with the 'actual' values. I thought it would speed things up but I'm not very sure it did... </p> <pre><code>match = [] checklist = set() for read in data.itertuples(): for ref in ref.itertuples(): x = np.isnan(read[3:]).argmax(axis=0) if x == 2: if np.isclose(read[4:6],ref[7:9],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x: if not read[1] in checklist: match.append([read[1], ref[5]]) checklist.add(read[1]) if x &gt; 2: read_pos = 3+x-1 ref_pos = 6+x-1 if np.isclose(read[4:read_pos],ref[7:ref_pos],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x: if not read[1] in checklist: match.append([read[1], ref[5]]) checklist.add(read[1]) if read[1] not in checklist: match.append([read[1], "not found"]) checklist.add(read[1]) </code></pre> <p>Thanks in advance !</p> <p><strong>EDIT:</strong></p> <p>To download samples of data and ref tables: <a href="https://we.tl/RF6lxDZBjt" rel="nofollow noreferrer">https://we.tl/RF6lxDZBjt</a></p> <p>Short example of the dataframes:</p> <pre><code>ref = pd.DataFrame({'name':['a-1','a-2','b-1'], 'start 1':[100,100,100], 'end 1':[200,200,500], 'start 2':[300,np.NaN,600], 'end 2':[400,np.NaN, 700]}, columns=['name', 'start 1', 'end 1', 'start 2', 'end 2'], dtype='float64') name start 1 end 1 start 2 end 2 0 a-1 100.0 200.0 300.0 400.0 1 a-2 100.0 200.0 NaN NaN 2 b-1 100.0 500.0 600.0 700.0 data = pd.DataFrame({'name':['read 1','read 2','read 3','read 4', 'read 5'], 'start 1':[100,102,100,103,600], 'end 1':[198,504,500,200, 702], 'start 2':[np.NaN,600,650,601, np.NaN], 'end 2':[np.NaN,699, 700,702, np.NaN]}, columns=['name', 'start 1', 'end 1', 'start 2', 'end 2'], dtype='float64') read start 1 end 1 start 2 end 2 0 read 1 100.0 200.0 300.0 400.0 1 read 2 100.0 200.0 NaN NaN 2 read 3 100.0 500.0 600.0 700.0 3 read 4 300.0 400.0 600.0 700.0 4 read 5 600.0 702.0 NaN NaN </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T10:05:30.683", "Id": "384852", "Score": "0", "body": "@Graipher Did you happen to have time to look at it ? If not, I totally understand ! If you even have a small idea of things that I could try I'm willing to try it myself ! I tri...
[ { "body": "<p>Invariants</p>\n\n<pre><code>for read in data.itertuples():\n for ref in ref.itertuples():\n x = np.isnan(read[3:]).argmax(axis=0)\n</code></pre>\n\n<p><code>x</code> doesn't change in the inner loop, so you can move it out of the inner loop, and not execute it repeatedly.</p>\n\n<pre><c...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T20:47:45.507", "Id": "199860", "Score": "3", "Tags": [ "python", "numpy", "pandas" ], "Title": "Matching rows between two dataframes" }
199860
<p>I am a beginner and have created this bash script that helps me with creating bash scripts. </p> <p>The script shows no issues on shellcheck.net </p> <p>The code can be found here. <a href="https://github.com/plutesci/Iwanttobash/blob/master/Icode.bash" rel="nofollow noreferrer">https://github.com/plutesci/Iwanttobash/blob/master/Icode.bash</a></p> <p>I would like some feedback from more experienced users. Any suggestions or thoughts about this.</p> <pre><code>#!/bin/bash # This Program is to Show user the commands and or to create a bash script # to execute this program type at terminal ./ICode.bash # I am attempting to have the program open the named file with the header # shebang at the top #!/bin/bash as it is not there you will need to add it. # created by plutesci for self or public use. clear # Banner shows a banner to install should it not show on Ubuntu is. # sudo apt-get install sysvbanner # banner "Icode" # figlet is a banner aswell to install that just type in your terminal # sudo apt-get install figlet figlet "Icode" echo Showing a way to use the command line steps to start a Hello World program echo Where you see test.bash, Please rename test.bash echo Follow Steps Below... echo #################### echo "echo '#!/bin/bash' &gt; test.bash " #change test echo "'echo Hello World' &gt;&gt; test.bash " # change test.bash echo "chmod 755 test.bash" # change test.bash echo "nano test.bash" # change test.bash echo "Exit Ctrl c" echo ################### #echo '#!/bin/bash' &gt;&gt; "$text.bash" # I want to add an option to ask user if they want to start a new bash \ # program yes \ no? # if yes\Yes query user for new name, What to call this bash ? ...... # I am happy with the the selection part but would like it going into a menu # afterwards with press 9 return to previous menu ######## Things to improve on. # when playing i found a program called openvt, It would be great to have the # bash program open virtual termin and run the output echo -n "Please Enter a Filename For Your New Bash Script &gt; " read -r text echo "Your New Bash Script is named: $text" # chmod +x $text.bash # I need to figure out how to add .bash to the $text varable selection= until [ "$selection" = "0" ]; do echo " ICODE MENU 1 - Start a new Bash Script 2 - Make it Executable 3 - Run Bash Program 4 - Continue working on script 5 - Start python idle 6 - Open a new shell 7 - Create Automatic Shell scripts 8 - Delete the script 9 - Help 0 - Exit Program " echo -n "Enter selection: " read -r selection echo "" case $selection in 1 ) echo "#!/bin/bash" &gt; "$text.bash" ; nano "$text.bash" ;; 2 ) chmod 755 "$text.bash" ;; 3 ) gnome-terminal ; echo "./$text.bash" ;; 4 ) nano "$text.bash" ;; 5 ) idle ;; 6 ) gnome-terminal ;; 7 ) nano ;; # would be something like grep a special crafted document 8 ) echo "#!/bin/bash" &gt; "$text.bash" ;; 9 ) cat icodehelp ;; 0 ) exit ;; * ) echo "Please enter 1, 2, 3, 4, 5, 6, 7, 8, 9, or 0" esac done # Things I would like to add to the program would be a auto statment maker # and auto create bash programs like open the randomly grep for certain # keywords, and random cut from a libary of scripts 10 - 100 scripts # run it in a virtual terminal, looking for errors and print out example # 3 out of 100 run with no errors, would you like to view these? # 17 out of 100 return a slight error, would you like to inspec these. # 83% percent should be removed. something like that just visualising it out # My first bash application would like any help, still trying to learn how # github works </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T13:11:04.703", "Id": "384771", "Score": "0", "body": "Changing the code under review is not a good thing on this site. Since noone answered yet it seems to be allowed, but generally you should open a new question with a new version...
[ { "body": "<h1>Good things</h1>\n\n<ul>\n<li>lots of comments are good.</li>\n<li><code>clear</code> keeps things clean when you start</li>\n<li>This is an interesting way to learn shell scripting. My friends would call it \"very meta\" which is high praise indeed.</li>\n<li>I usually tell people they should h...
{ "AcceptedAnswerId": "199918", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T21:47:35.127", "Id": "199865", "Score": "3", "Tags": [ "beginner", "bash" ], "Title": "Bash script creator app" }
199865
<p>I have a huge array that I want to group by by category and subcategory. A Book is contained in a shelve. A Shelve is contained in a Library. The output is a list of Library. I cannot change my Book class, but I am free to organize the Shelve and the Library class.How can I improve the grouping? Current running time is O(n) and I don't want to loose perf. I am more looking for a cleaner way to achieve the same result. How can I improve this code? To me, it seems a bit to <em>long</em> for a simple problem and I think I am missing something.</p> <p>I don't control this one. I can add code but not remove a property:</p> <pre><code>class Book { public int LibraryId {get;set;} public string LibraryName {get;set;} public int ShelveId {get;set;} public string ShelveName {get;set;} public int Cost {get;set;} public int Price {get;set;} public string Name {get;set;} public string ForeName {get;set;} public string Stuff {get;set;} public Book(int libraryId, string libraryName, int shelveId, string shelveName , int cost, int price, string name, string foreName, string stuff) { LibraryId = libraryId; LibraryName = libraryName; ShelveId = shelveId; ShelveName = shelveName; Cost = cost; Price = price; Name = name; ForeName = foreName; Stuff = stuff; } } </code></pre> <p>Here we can do whatever we want:</p> <pre><code>class Library { public int Id {get;set;} public string Name {get;set;} public int Cost {get;set;} public int Price {get;set;} public List&lt;Shelve&gt; Shelves {get;set;} public Library (Shelve shelve) { Id = shelve.Books[0].LibraryId; Name = shelve.Books[0].LibraryName; Cost = shelve.Cost; Price = shelve.Price; Shelves = new List&lt;Shelve&gt; {shelve}; } } class Shelve { public int Id {get;set;} public string Name {get;set;} public int Cost {get;set;} public int Price {get;set;} public List&lt;Book&gt; Books {get;set;} public Shelve (Book book) { Id = book.ShelveId; Name = book.ShelveName; Cost = book.Cost; Price = book.Price; Books = new List&lt;Book&gt; {book}; } } </code></pre> <p>The table is a SQL table with around 5000 rows right know. With real data is quantity is unknown but should be higher:. The table is already ordered by Library then by Shelve:</p> <pre><code>public static void Main() { var table = new[] { new Book (1, "Green", 42, "A", 10, 1, "Gra", "Bar", "etc."), new Book (1, "Green", 43, "B", 21, 2, "Grb", "Bar", "etc."), new Book (2, "Blue", 652, "C", 10, 1, "Blc", "Bar", "etc."), new Book (2, "Blue", 652, "C", 01, 7, "Bl2", "Bar", "etc."), new Book (2, "Blue", 123, "D", 12, 4, "Bld", "Bar", "etc."), new Book (8, "White", 94, "E", 14, 9, "Foo", "Bar", "etc."), new Book (9, "Grey", 142, "F", 11, 6, "Foo", "Bar", "etc."), new Book (9, "Grey", 142, "F", 12, 2, "Bar", "Bar", "etc.") }; </code></pre> <p>Here we walk the table (<strong>This is the part I would like to improve</strong>):</p> <pre><code> var libraries = new List&lt;Library&gt; { new Library (new Shelve(table[0])) }; foreach (var item in table.Skip(1)) { if (item.LibraryId != libraries.Last().Id) { libraries.Add(new Library(new Shelve(item))); continue; } if (item.ShelveId != libraries.Last().Shelves.Last().Id) { libraries.Last().Cost += item.Cost; libraries.Last().Price += item.Price; libraries.Last().Shelves.Add(new Shelve(item)); continue; } libraries.Last().Shelves.Last().Cost += item.Cost; libraries.Last().Cost += item.Cost; libraries.Last().Shelves.Last().Price += item.Price; libraries.Last().Price += item.Price; libraries.Last().Shelves.Last().Books.Add(item); } var totalCost = libraries.Sum(x =&gt; x.Cost); var totalPrice = libraries.Sum(x =&gt; x.Price); </code></pre> <p>I dont know how to use xUnit.Net or NUnit on .NETFiddle so...</p> <pre><code> Console.WriteLine(libraries.Count() == table.Select(x =&gt; x.LibraryId).Distinct().Count()); Console.WriteLine(total == 91); Console.WriteLine(libraries[0].Name == "Green"); Console.WriteLine(libraries[0].Shelves.Count() == 2); Console.WriteLine(libraries[0].Shelves[0].Name == "A"); Console.WriteLine(libraries[0].Shelves[0].Books.Count() == 1); Console.WriteLine(libraries[0].Shelves[0].Books[0].Name == "Gra"); Console.WriteLine(libraries[0].Shelves[1].Name == "B"); Console.WriteLine(libraries[0].Shelves[1].Books.Count() == 1); Console.WriteLine(libraries[0].Shelves[1].Books[0].Name == "Grb"); Console.WriteLine(libraries[0].Shelves[0].Books.Sum(x =&gt; x.Cost) == 10); Console.WriteLine(libraries[0].Shelves[1].Books.Sum(x =&gt; x.Cost) == 21); Console.WriteLine(libraries[0].Shelves[0].Cost == 10); Console.WriteLine(libraries[0].Shelves[1].Cost == 21); Console.WriteLine(libraries[0].Shelves.Sum(x =&gt; x.Cost) == 31); Console.WriteLine(libraries[0].Cost == 31); Console.WriteLine(libraries[1].Name == "Blue"); Console.WriteLine(libraries[1].Shelves.Count() == 2); Console.WriteLine(libraries[1].Shelves[0].Name == "C"); Console.WriteLine(libraries[1].Shelves[0].Books.Count() == 2); Console.WriteLine(libraries[1].Shelves[0].Books[0].Name == "Blc"); Console.WriteLine(libraries[1].Shelves[0].Name == "C"); Console.WriteLine(libraries[1].Shelves[0].Books[1].Name == "Bl2"); Console.WriteLine(libraries[1].Shelves[1].Name == "D"); Console.WriteLine(libraries[1].Shelves[1].Books.Count() == 1); Console.WriteLine(libraries[1].Shelves[1].Books[0].Name == "Bld"); Console.WriteLine(libraries[1].Shelves[0].Books.Sum(x =&gt; x.Cost) == 11); Console.WriteLine(libraries[1].Shelves[1].Books.Sum(x =&gt; x.Cost) == 12); Console.WriteLine(libraries[1].Shelves[0].Cost == 11); Console.WriteLine(libraries[1].Shelves[1].Cost == 12); Console.WriteLine(libraries[1].Shelves.Sum(x =&gt; x.Cost) == 23); Console.WriteLine(libraries[1].Cost == 23); Console.WriteLine(libraries[2].Name == "White"); Console.WriteLine(libraries[2].Shelves.Count() == 1); Console.WriteLine(libraries[2].Shelves[0].Name == "E"); Console.WriteLine(libraries[2].Shelves[0].Books.Count() == 1); Console.WriteLine(libraries[2].Shelves[0].Books[0].Name == "Foo"); Console.WriteLine(libraries[2].Shelves[0].Books.Sum(x =&gt; x.Cost) == 14); Console.WriteLine(libraries[2].Shelves[0].Cost == 14); Console.WriteLine(libraries[2].Shelves.Sum(x =&gt; x.Cost) == 14); Console.WriteLine(libraries[2].Cost == 14); Console.WriteLine(libraries[3].Name == "Grey"); Console.WriteLine(libraries[3].Shelves.Count() == 1); Console.WriteLine(libraries[3].Shelves[0].Name == "F"); Console.WriteLine(libraries[3].Shelves[0].Books.Count() == 2); Console.WriteLine(libraries[3].Shelves[0].Books[0].Name == "Foo"); Console.WriteLine(libraries[3].Shelves[0].Books[1].Name == "Bar"); Console.WriteLine(libraries[3].Shelves[0].Books.Sum(x =&gt; x.Cost) == 23); Console.WriteLine(libraries[3].Shelves[0].Cost == 23); Console.WriteLine(libraries[3].Shelves.Sum(x =&gt; x.Cost) == 23); Console.WriteLine(libraries[3].Cost == 23); } </code></pre> <p><a href="https://dotnetfiddle.net/diow2O" rel="nofollow noreferrer">Try It Online!</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T05:26:07.633", "Id": "384685", "Score": "0", "body": "How can I improve the quality of the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T06:13:51.353", "Id": "384688", "Score": "1"...
[ { "body": "<p>Another option is to do away with the extra classes since each book has the information needed. A nested <code>groupby</code> query will give you the exact groupings that you want:</p>\n\n<pre><code>var libraryGroups = (from Book b in table\n group b by b.LibraryId into libraries\n ...
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-19T23:29:11.770", "Id": "199869", "Score": "0", "Tags": [ "c#", "algorithm" ], "Title": "This code transforms raw data in a table into nested objects" }
199869
<p>This is the <code>main.py</code> script that does most of the work of Adding movies (<code>Movie</code> objects) as well as modifying and removing:</p> <pre><code>from flask import Flask, render_template, request, flash, url_for, redirect import sqlite3 from datetime import date from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from movie import Movie app = Flask(__name__) app.secret_key = "LOL" Base = declarative_base() engine = create_engine('sqlite:///adatabase.db', connect_args={'check_same_thread': False}, echo=True) Base.metadata.create_all(engine) Base.metadata.bind = engine Session = (sessionmaker(bind=engine)) #scoped_session Base.metadata.create_all(engine) session = Session() @app.route('/') @app.route('/home') def home(): return render_template('home.html') @app.route('/form', methods = ['POST','GET']) def form(): try: if request.method == 'POST': title = request.form['title'] release_date = request.form['release_date'] print(release_date) session.add(Movie(title,date(int(release_date.split('-')[0]),int(release_date.split('-')[1]),int(release_date.split('-')[2])))) session.commit() session.close() return redirect(url_for('table')) except: flash("An error occured while writing to database") return redirect(url_for('home')) return render_template('form.html', title = "Form") @app.route('/table') def table(): con = sqlite3.connect('adatabase.db') con.row_factory = sqlite3.Row cur = con.cursor() cur.execute('select * from movies') movies = cur.fetchall() return render_template('table.html',movies = movies, title = "Movies") @app.route('/delete/&lt;int:post_id&gt;') def delete(post_id): query = session.query(Movie).filter(Movie.id == post_id).first() session.delete(query) session.commit() session.close() return redirect(url_for('table')) @app.route('/modify/&lt;int:post_id&gt;', methods = ['POST','GET']) def modify(post_id): query = session.query(Movie).filter(Movie.id == post_id).first() if request.method == 'POST': title = request.form['title'] release_date = request.form['release_date'] session.delete(query) session.add(Movie(title,date(int(release_date.split('-')[0]),int(release_date.split('-')[1]),int(release_date.split('-')[2])))) session.commit() session.close() return redirect(url_for('table')) return render_template('edit.html',num = post_id,title = query.title,date = query.release_date) if __name__ == '__main__': app.run(debug = True) </code></pre> <p>I have a <code>Movie</code> class defined in another script <code>movie.py</code>:</p> <pre><code>from sqlalchemy import Column, String, Integer, Date, Table, ForeignKey from sqlalchemy.orm import relationship from base import Base movies_actors_association = Table( 'movies_actors', Base.metadata, Column('movie_id', Integer, ForeignKey('movies.id')), Column('actor_id', Integer, ForeignKey('actors.id')) ) class Movie(Base): __tablename__ = 'movies' id = Column(Integer, primary_key=True) title = Column(String) release_date = Column(Date) actors = relationship('Actor',secondary=movies_actors_association) def __init__(self,title,release_date): self.title = title self.release_date = release_date def __repr__(self): return self.title </code></pre> <p>Finally, I have 5 HTML files that I think would just clutter up the post (if it isn't already) that are just <code>home</code>, <code>form</code>, <code>table</code>, <code>edit</code>, and <code>base</code> (the one that all of them extend, containing hyperlinks to all other pages).</p> <p>The library works great. I was having an <code>SQLAlchemy check_same_thread</code> issue but I've added <code>connect_args={'check_same_thread': False}, echo=True)</code> to the <code>engine=create_engine()</code> and now it runs smoothly.</p> <p>I know that I should probably have several files in which I do databases, classes, page switching and such but I'm not sure about the exact structure. It also feels like I'm missing some things as some example code I've seen uses <code>db = SQLAlchemy(app)</code> but others just use the session and engine.</p>
[]
[ { "body": "<h1>Document with docstrings.</h1>\n\n<p>Your functions and ORM models are currently not providing any useful documentation regarding their respective function within your program.</p>\n\n<h1>Don't initialize the database on module level:</h1>\n\n<p>You should put that into a function:</p>\n\n<pre><c...
{ "AcceptedAnswerId": "200202", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T00:22:22.200", "Id": "199872", "Score": "7", "Tags": [ "python", "python-3.x", "flask", "sqlalchemy" ], "Title": "A simple library using Flask and SQLAlchemy" }
199872
<p>I am trying to generate predictions using the function below in combination with sapply. My actual datasets are very large, I am attempting to make 1.5 million predictions with this function and it is currently taking about 10 seconds per prediction which is... prohibitive to say the least.</p> <pre><code>mean_rating &lt;- function(df){ #mean_rating &lt;- function(query_user,query_movie){ user&lt;-df$user movie&lt;-df$movie u_row&lt;-which(U_lookup == user)[1] m_row&lt;-which(M_lookup==movie) knn_match&lt;- knn_txt[u_row,] knn_match&lt;-as.numeric(unlist(knn_match)) dfm_mov&lt;- dfm[,m_row] dfm_test&lt;- dfm_mov[knn_match] c&lt;-mean(dfm_test[dfm_test!=0]) c1&lt;-mean(dfm_mov[dfm_mov!=0]) ifelse(c!="NaN",c,c1) } test&lt;-sapply(1:nrow(probe), function(x) mean_rating(probe[x,])) </code></pre> <p>The inputs to this function include the following. Sparse matrix dfm</p> <pre><code>library(Matrix) dput(dfm) new("dgTMatrix" , i = c(0L, 1L, 2L, 4L, 5L, 6L, 8L, 0L, 1L, 2L, 3L, 4L, 6L, 7L, 8L, 0L, 2L, 3L, 6L, 7L, 8L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 3L, 4L, 6L, 7L, 8L, 9L, 0L, 2L, 3L, 5L, 6L, 7L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 9L) , j = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L) , Dim = c(10L, 10L) , Dimnames = list(NULL, NULL) , x = c(4, 3, 1, 2, 3, 1, 2, 1, 3, 3, 2, 3, 3, 3, 4, 2, 1, 2, 3, 2, 1, 4, 1, 2, 2, 3, 2, 3, 4, 1, 4, 1, 3, 4, 3, 2, 2, 2, 4, 1, 2, 2, 1, 2, 3, 1, 1, 1, 4, 1, 1, 2, 1, 1, 1, 4, 3, 3, 2, 1, 2, 2, 1, 1, 3, 3, 4, 1, 2, 4, 2, 4, 1, 2, 2, 3, 4, 2, 1, 2, 4) , factors = list() ) </code></pre> <p>My probe dataset, these are the user movie combinations I am trying to predict for.</p> <pre><code>dput(probe) structure(list(X = c(1145185L, 951920L, 1137277L, 180365L, 353195L ), movie = c(1L, 100L, 10000L, 10002L, 10004L), user = c(10L, 1000004L, 1000033L, 1000035L, 1000053L), Rating = c(4L, 4L, 3L, 5L, 4L)), .Names = c("X", "movie", "user", "Rating"), row.names = c("1145185", "951920", "1137277", "180365", "353195"), class = "data.frame") </code></pre> <p>My U_lookup table, this is where I convert from the actual id of a user to the row number of the matrix they are in.</p> <pre><code>dput(U_lookup[1:10,]) c(10L, 100000L, 1000004L, 1000027L, 1000033L, 1000035L, 1000038L, 1000051L, 1000053L, 1000057L) </code></pre> <p>My M_lookup table, this is where I convert from the actual id of a movie to the row number of the matrix they are in.</p> <pre><code>dput(M_lookup[1:10,]) c(1L, 10L, 100L, 1000L, 10000L, 10001L, 10002L, 10003L, 10004L, 10005L) </code></pre> <p>knn_txt is where I'm storing all the users nearest neighbors. Dfm and knn_text would have the same user in every row. I.e., row 1 in dfm would equate to the same user that is in row 1 of knn_text.</p> <pre><code>dput(knn_txt) structure(list(V1 = c(1, 2, 1, 7, 5, 3, 2, 9, 1, 3), V2 = c(7, 9, 5, 5, 3, 4, 2, 7, 4, 9), V3 = c(2, 9, 6, 3, 8, 9, 4, 7, 1, 6)), .Names = c("V1", "V2", "V3"), row.names = c(NA, -10L), class = "data.frame") </code></pre> <p>Edit: As I have done some more testing myself it does seem like a lot of the time savings could come from more efficiently subsetting my large sparse matrix, dfm. I am planning on trying some different formats of the matrix, in addition to maybe looking at looping rather than using sapply (just because then I could say for user i, if user i=i-1 then I don't need to re-subset the matrix).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T11:13:38.527", "Id": "384745", "Score": "0", "body": "the code can not bee run + create larger data using `sample` or something similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T13:45:32.733", ...
[ { "body": "<p>So after a lot of testing I found something that significantly reduces calculation time. Converting the format of my dfm to a different sparse format saves significant time when subsetting my main matrix (dfm).</p>\n\n<pre><code>dfm&lt;-as(dfm,\"dgCMatrix\")\n</code></pre>\n\n<p>This took my calcu...
{ "AcceptedAnswerId": "199995", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T00:35:54.763", "Id": "199873", "Score": "0", "Tags": [ "performance", "matrix", "r" ], "Title": "R Function to Generate Predictions from Ratings and Save Results" }
199873
<p>I've just found out there is <code>sendfile()</code>. In the man page of <a href="http://man7.org/linux/man-pages/man2/sendfile.2.html" rel="nofollow noreferrer"><code>sendfile()</code></a>, it says:</p> <blockquote> <p><code>sendfile()</code> is more efficient than the combination of <code>read(2)</code> and <code>write(2)</code>.</p> </blockquote> <p>So, I wrote a function to copy a file using <code>sendfile()</code>.</p> <p>Is really my code more efficient than the combination of <code>read(2)</code> and <code>write(2)</code>?</p> <pre><code>/* leftsize is initialized with total size of source file. */ fd_src = open(src_fname, O_RDONLY); if (fd_src&lt;0){ printf("open failed(%s)\n", src_fname); return -1; } fd_dest = creat(dest_fname, 0666); if (fd_dest&lt;0){ printf("create failed(%s)\n", dest_fname); return -1; } while (leftsize &gt; 0) { n = sendfile(fd_dest, fd_src, NULL, max_size); if (n&lt;0) { printf("sendfile failed. ret:%d errno:%d\n", n, errno); } leftsize -= n; } </code></pre>
[]
[ { "body": "<p>The first paragraph of the man page says it all:</p>\n\n<blockquote>\n <p><code>sendfile()</code> copies data between one file descriptor and another.\n Because this copying is done within the kernel, <code>sendfile()</code> is more\n efficient than the combination of <code>read(2...
{ "AcceptedAnswerId": "199878", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T01:07:49.510", "Id": "199876", "Score": "0", "Tags": [ "beginner", "c" ], "Title": "Function to copy a file using sendfile" }
199876
<blockquote> <p><strong>Challenge</strong></p> <p>Using the C++ language, have the function <code>PentagonalNumber(num)</code> read <code>num</code> which will be a positive integer and determine how many dots exist in a pentagonal shape around a center dot on the Nth iteration. For example, in the image below you can see that on the first iteration there is only a single dot, on the second iteration there are 6 dots, on the third there are 16 dots, and on the fourth there are 31 dots. </p> <p><img src="https://i.stack.imgur.com/YWlKr.png" width="350"/></p> <p>Your program should return the number of dots that exist in the whole pentagon on the Nth iteration. </p> <p><strong>Sample Test Cases</strong></p> <pre><code>Input:2 Output:6 Input:5 Output:51 </code></pre> </blockquote> <p>I found it weird that <a href="https://www.coderbyte.com/editor/guest:Pentagonal%20Number:Cpp" rel="noreferrer">Coderbyte called this a hard challenge</a>. It works, but is this the right approach?</p> <p><strong>Header File</strong></p> <pre><code>#ifndef PentagonalNum_hpp #define PentagonalNum_hpp #include &lt;stdio.h&gt; class PentagonalNum { public: PentagonalNum(int N); unsigned long long int num_Of_Dots(); private: int iteration; }; #endif /* PentagonalNum_hpp */ </code></pre> <p><strong>CPP File</strong></p> <pre><code>#include "PentagonalNum.hpp" PentagonalNum::PentagonalNum(int N) : iteration(N) { } unsigned long long int PentagonalNum::num_Of_Dots() { int result = 1; int num = 5; for (int i = 1; i &lt; iteration; ++i) { result += num; num += 5; } return result; } </code></pre>
[]
[ { "body": "<p>It seems a little peculiar to use a class to solve this problem. It's not like there's any need to maintain state. All you're doing, in the end, is making it more difficult to use - instead of:</p>\n\n<pre><code>auto result = pentagonal_number(n);\n</code></pre>\n\n<p>you have to write:</p>\n\n<pr...
{ "AcceptedAnswerId": "199881", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T01:53:59.887", "Id": "199877", "Score": "8", "Tags": [ "c++" ], "Title": "Demonstration of Pentagonal Number" }
199877
<p>I decided to try and recreate Microsoft's REG.exe query functionality."Reg.exe" is Microsoft's Console Registry Tool. </p> <p>I used Microsoft's documentation of "<a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/reg-query" rel="nofollow noreferrer">reg query</a>" to recreate it's functionality within C++.</p> <p>I thought that it would be a great way to test myself and help to get a better grasp of Microsoft API's as well as better my programming skills.</p> <p>I know it is not the best code. But if you could please provide constructive criticism as well as explain what you would do differently.</p> <p><strong>Main.cpp</strong></p> <pre><code>/* Main.cpp */ #include &lt;iostream&gt; #include "AquireInput.h" #include "Error.h" #include "Help.h" #include "RegAdd.h" #include "RegQuery.h" int wmain(int argc, wchar_t* argv[]) { RegBlock aVal; int result = getInput(argc, argv, aVal); switch (result) { case REG_ADD: add(aVal); break; case REG_QUERY: query(aVal); break; case REG_DELETE: break; case REG_HELP_GENERAL: case REG_HELP_ADD: case REG_HELP_QUERY: case REG_HELP_DELETE: help(result); break; default: error(result); break; } return 0; } </code></pre> <p><strong>AquireInput.h</strong></p> <pre><code>#pragma once #include &lt;windows.h&gt; #include &lt;iostream&gt; #include "Error.h" #include &lt;map&gt; // Switch macro's #define REG_ADD (1) #define REG_QUERY (2) #define REG_DELETE (3) struct RegBlock { std::wstring lHkey = L""; std::wstring lHkeyPath = L""; std::wstring lValueName = L""; std::wstring lDataType = L""; std::wstring lData = L""; bool lViewed[12] = { false }; std::map&lt;std::string, bool&gt; lOptions = { { "/k",false }, { "/d",false }, { "/s",false }, { "/c",false }, { "/e",false }, { "/z",false }, { "/f",false } }; }; int getInput(int argc, wchar_t* argv[], RegBlock&amp; aVal); </code></pre> <p><strong>AquireInput.cpp</strong></p> <pre><code>/* AquireInput.cpp */ #include &lt;queue&gt; #include "AquireInput.h" #include "Help.h" // Parameter handles #define V (0) #define VE (1) #define T (2) #define D (3) #define F (4) #define S (5) #define K (6) #define C (7) #define E (8) #define Z (9) #define VA (10) uint8_t checkIdentifer(std::wstring &amp;arg, bool viewed[]) { if (arg == L"/v" &amp;&amp; !viewed[V]) { viewed[VE] = true; // Deactivate value empty arg return V; } if (arg == L"/ve" &amp;&amp; !viewed[VE]) { viewed[V] = true; // Deactivate value specify arg return VE; } if (arg == L"/k" &amp;&amp; !viewed[K]) { viewed[D] = true; // Deactivate data search arg return K; } if (arg == L"/d" &amp;&amp; !viewed[D]) { viewed[K] = true; // Deactivate key value search arg return D; } if (arg == L"/t" &amp;&amp; !viewed[T]) return T; if (arg == L"/f" &amp;&amp; !viewed[F]) return F; if (arg == L"/s" &amp;&amp; !viewed[S]) return S; if (arg == L"/c" &amp;&amp; !viewed[C]) return C; if (arg == L"/e" &amp;&amp; !viewed[E]) return E; if (arg == L"/z" &amp;&amp; !viewed[Z]) return Z; return L'x'; } bool validDataType(std::wstring &amp;aDataType) { if (getDataTypeMacro(aDataType) != NULL) return true; return false; } bool validKeyName(std::wstring s) { // Test if a minimum string length has been met if (s.size() &lt; 3) return false; if (s.size() == 3) { if (s.substr(0, 3) == L"HKU") return true; return false; } else { std::wstring lHkey = s.substr(0, 4); if (lHkey == L"HKCR") return true; if (lHkey == L"HKCC") return true; if (lHkey == L"HKCU") return true; if (lHkey == L"HKLM") return true; if (lHkey.substr(0, 3) == L"HKU") return true; return false; } } bool setHKey(std::wstring &amp;s, RegBlock &amp;aVal) { // Test if a minimum string length has been met if (s.size() &lt; 3) return false; // Addresses case in which user only input 'ADD HKU' if (s.size() == 3) { if (s.substr(0, 3) == L"HKU") { aVal.lHkey = L"HKU"; } return true; } else { std::wstring lHkey = s.substr(0, 4); // Test if a lHkeyPath has been inputted if (s.size() &gt; 4) { aVal.lHkeyPath = s.substr(5); } if (lHkey == L"HKCR") aVal.lHkey = L"HKCR"; if (lHkey == L"HKCC") aVal.lHkey = L"HKCC"; if (lHkey == L"HKCU") aVal.lHkey = L"HKCU"; if (lHkey == L"HKLM") aVal.lHkey = L"HKLM"; if (lHkey.substr(0, 3) == L"HKU") { aVal.lHkey = L"HKU"; if (s.size() &gt; 4) { aVal.lHkeyPath = s.substr(4); } } return true; } } int getInput(int argc, wchar_t* argv[], RegBlock&amp; aVal) { std::queue&lt;std::wstring&gt; lQueue; // Add argv values to lQueue for (int i = 1; i &lt; argc; i++) { lQueue.push(argv[i]); } if (lQueue.empty()) return MISSING_CORE_PARAMETER; // Get action (ADD,DELETE,QUERY..ect); std::wstring lCurrentVal = lQueue.front(); lQueue.pop(); // Guard against repeat parameter/sytax e.g /v Hello /ve /f /f bool lViewed[12] = { false }; if (lCurrentVal == L"ADD") { if (lQueue.empty()) return MISSING_CORE_PARAMETER; lCurrentVal = lQueue.front(); // Check if ADD HELP was requested if (lCurrentVal == L"/?") return REG_HELP_ADD; // Check &amp; Set HKEY value if (!validKeyName(lCurrentVal)) return NON_VALID_HKEY; setHKey(lCurrentVal, aVal); lQueue.pop(); // Check validity of parameter while (lQueue.size()) { lCurrentVal = lQueue.front(); lQueue.pop(); switch (checkIdentifer(lCurrentVal, lViewed)) { case V: lViewed[V] = true; aVal.lValueName = lQueue.front(); lQueue.pop(); break; case VE: lViewed[VE] = true; break; case T: lViewed[T] = true; lCurrentVal = lQueue.front(); if (!validDataType(lCurrentVal)) return NON_VALID_DATA_TYPE; aVal.lDataType = lCurrentVal; lQueue.pop(); break; case D: lViewed[D] = true; aVal.lData = lQueue.front(); lQueue.pop(); break; case F: lViewed[F] = true; aVal.lOptions["/f"] = true; break; default: return UNKNOWN_PARAMETER; } } return REG_ADD; } if (lCurrentVal == L"QUERY") { if (lQueue.empty()) return MISSING_CORE_PARAMETER; lCurrentVal = lQueue.front(); // Check if ADD HELP was requested if (lCurrentVal == L"/?") return REG_HELP_QUERY; // Check &amp; Set HKEY value if (!validKeyName(lCurrentVal)) return NON_VALID_HKEY; setHKey(lCurrentVal, aVal); lQueue.pop(); // Check validity of parameter while (lQueue.size()) { lCurrentVal = lQueue.front(); lQueue.pop(); switch (checkIdentifer(lCurrentVal, lViewed)) { case V: lViewed[V] = true; aVal.lValueName = lQueue.front(); lQueue.pop(); break; case VE: lViewed[VE] = true; break; case S: lViewed[S] = true; aVal.lOptions["/s"] = true; break; case F: lViewed[F] = true; aVal.lOptions["/f"] = true; aVal.lData = lQueue.front(); lQueue.pop(); break; case K: lViewed[K] = true; aVal.lOptions["/k"] = true; break; case D: lViewed[D] = true; aVal.lOptions["/d"] = true; break; case C: lViewed[C] = true; aVal.lOptions["/c"] = true; break; case E: lViewed[E] = true; aVal.lOptions["/e"] = true; break; case T: lViewed[T] = true; lCurrentVal = lQueue.front(); if (!validDataType(lCurrentVal)) return NON_VALID_DATA_TYPE; aVal.lDataType = lCurrentVal; lQueue.pop(); break; case Z: lViewed[Z] = true; aVal.lOptions["/z"] = true; break; default: return UNKNOWN_PARAMETER; } } // Make sure that search options are not enabled without first specifing a search criteria if (lViewed[K] || lViewed[D] || lViewed[C] || lViewed[E] || lViewed[T]) { if (!lViewed[F]) return UNKNOWN_PARAMETER; } return REG_QUERY; } if (lCurrentVal == L"DELETE") { return REG_DELETE; } if (lCurrentVal == L"/?") { return REG_HELP_GENERAL; } return UNKNOWN_ACTION; } </code></pre> <p><strong>RegQuery.h</strong></p> <pre><code>#pragma once #include "AquireInput.h" bool query(RegBlock &amp;aVal); </code></pre> <p><strong>RegQuery.cpp</strong></p> <pre><code>/* RegQuery.cpp */ #include "RegQuery.h" #include &lt;queue&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;io.h&gt; #include &lt;fcntl.h&gt; #include &lt;algorithm&gt; #include &lt;fstream&gt; #define MAX_KEY_LENGTH 255 #define MAX_VALUE_NAME 32786 #define MAX_DATA_VALUE 2000000 std::wstring NULLWST = L""; // Placeholder null value inline unsigned hexValidInt(int aVal) { if (aVal &lt; 0) { aVal += 256; return aVal; } return aVal; } template &lt;typename I&gt; std::string n2hexstr(I w, size_t hex_len = 2) { static const char* digits = "0123456789ABCDEF"; std::string rc(hex_len, '0'); for (size_t i = 0, j = (hex_len - 1) * 4; i &lt; hex_len; ++i, j -= 4) { rc[i] = digits[(w &gt;&gt; j) &amp; 0x0f]; } // Corrects the order of the hex numbers e.g 34FE is corrected to FE34 std::swap_ranges(std::begin(rc)+2, std::end(rc), std::begin(rc)); return rc; } inline unsigned int convertData(DWORD &amp;aRegType, DWORD &amp;aDataLength, wchar_t *aData, std::wstring &amp;aDataResult) { std::wstring lDataResult; if (aRegType == REG_DWORD || aRegType == REG_QWORD || aRegType == REG_DWORD_LITTLE_ENDIAN || aRegType == REG_QWORD_LITTLE_ENDIAN || aRegType == REG_DWORD_BIG_ENDIAN) { // Reverse loop for (int i = (aDataLength * 0.5) - 1; i &gt;= 0; i--) { if (aData[i] == 0) continue; lDataResult += convertToWstr(n2hexstr(hexValidInt(aData[i]),2)); } } if (aRegType == REG_BINARY || aRegType == REG_NONE) { for (int i = 0; i &lt; (aDataLength * 0.5); i++) { lDataResult += convertToWstr(n2hexstr(hexValidInt(aData[i]),4)); } } if (aRegType == REG_SZ || aRegType == REG_MULTI_SZ) { int lEnd = (aDataLength * 0.5) - 1; // Avoid adding trailing zero if (aRegType == REG_MULTI_SZ) { lEnd = (aDataLength * 0.5) - 2; } for (int i = 0; i &lt; lEnd; i++) { if (aData[i] == 0) { lDataResult += L"\\0"; continue; } lDataResult += aData[i]; } } aDataResult = lDataResult; return 0; } struct RegValue { std::wstring lValueName; unsigned int lRegType; std::wstring lDataValue; }; inline std::wstring constructKeyPath(std::wstring &amp;aHkeyPath, std::wstring &amp;aSubKey) { std::wstring lSlash = L"\\"; std::wstring lFullPath; if (aSubKey == L"") { lFullPath = aHkeyPath; } else { lFullPath = aHkeyPath + lSlash + aSubKey; } return lFullPath; } inline unsigned int getValueNameList(HKEY hKey, std::wstring &amp;aHkeyPath, std::wstring &amp;aSubKey, std::queue&lt;std::wstring&gt; &amp;aValueList) { std::wstring lFullPath = constructKeyPath(aHkeyPath, aSubKey); LPCTSTR lpSubKey = lFullPath.c_str(); int lResult = RegOpenKeyEx( hKey, lpSubKey, 0, //add var KEY_QUERY_VALUE, //add var &amp;hKey ); if (lResult != ERROR_SUCCESS) { return lResult; } // Variables related to RegEnumValue LPDWORD lpReserved = NULL; LPDWORD lpType = NULL; LPBYTE lpData = NULL; LPDWORD lpcbData = NULL; DWORD dwIndex = 0; // Avoid adding lpValueName initial value bool lSkip = true; while (lResult != ERROR_NO_MORE_ITEMS) { wchar_t lpValueName[MAX_VALUE_NAME]; DWORD lpcchValueName = MAX_VALUE_NAME; // Add the list of value names to a vector list if (!lSkip) { aValueList.push(lpValueName); } else { lSkip = false; } lResult = RegEnumValue( hKey, dwIndex, lpValueName, &amp;lpcchValueName, lpReserved, lpType, lpData, lpcbData ); dwIndex++; // Return an error if lResult is not an acceptable error if (lResult != ERROR_SUCCESS &amp;&amp; lResult != ERROR_NO_MORE_ITEMS) { RegCloseKey(hKey); return lResult; } } //Close key RegCloseKey(hKey); return lResult = 0; } inline unsigned int getSubKeyList(HKEY hKey, std::wstring &amp;aHkeyPath, std::wstring &amp;aSubKey, std::deque&lt;std::wstring&gt; &amp;aSubKeyList) { std::wstring lFullPath = constructKeyPath(aHkeyPath, aSubKey); LPCTSTR lpSubKey = lFullPath.c_str(); DWORD i, lResult; lResult = RegOpenKeyEx( hKey, lpSubKey, 0, KEY_READ, &amp;hKey ); TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name DWORD cbName; // size of name string TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name DWORD cchClassName = MAX_PATH; // size of class string DWORD cSubKeys = 0; // number of subkeys DWORD cbMaxSubKey; // longest subkey size DWORD cchMaxClass; // longest class string DWORD cValues; // number of values for key DWORD cchMaxValue; // longest value name DWORD cbMaxValueData; // longest value data DWORD cbSecurityDescriptor; // size of security descriptor FILETIME ftLastWriteTime; // last write time TCHAR achValue[MAX_VALUE_NAME]; DWORD cchValue = MAX_VALUE_NAME; // Get the class name and the value count. lResult = RegQueryInfoKey( hKey, // key handle achClass, // buffer for class name &amp;cchClassName, // size of class string NULL, // reserved &amp;cSubKeys, // number of subkeys &amp;cbMaxSubKey, // longest subkey size &amp;cchMaxClass, // longest class string &amp;cValues, // number of values for this key &amp;cchMaxValue, // longest value name &amp;cbMaxValueData, // longest value data &amp;cbSecurityDescriptor, // security descriptor &amp;ftLastWriteTime); // last write time // Enumerate the subkeys, until RegEnumKeyEx fails. if (cSubKeys) { for (i = 0; i&lt;cSubKeys; i++) { cbName = MAX_KEY_LENGTH; lResult = RegEnumKeyEx(hKey, i, achKey, &amp;cbName, NULL, NULL, NULL, &amp;ftLastWriteTime); if (lResult == ERROR_SUCCESS) { // Attach parent key to child sub keys // e.g: key01/subkey01 std::wstring lRelativePath = achKey; if (aSubKey != L"") { lRelativePath = aSubKey + L"\\" + achKey; } aSubKeyList.push_back(lRelativePath); } } } //Close key RegCloseKey(hKey); return lResult; } inline unsigned int getValueData(HKEY aHkey, std::wstring &amp;aHkeyPath, std::wstring &amp;aSubKey, std::wstring &amp;aValueName, RegValue &amp;aValueData) { std::wstring lFullPath = constructKeyPath(aHkeyPath, aSubKey); LPCTSTR lSubKey = lFullPath.c_str(); LPCTSTR lValueName = aValueName.c_str(); DWORD dwFlags = RRF_RT_ANY; DWORD pdwType; wchar_t *pvData = new wchar_t[MAX_DATA_VALUE]; DWORD pcbData = MAX_DATA_VALUE; int lResult = RegGetValue( aHkey, lSubKey, lValueName, dwFlags, &amp;pdwType, pvData, &amp;pcbData ); // Check if lResult is okay if (lResult != ERROR_SUCCESS) { delete[] pvData; return lResult; } if (pcbData &gt;= MAX_DATA_VALUE) { std::cout &lt;&lt; "Data Value Exceeded! Registery data value &gt; 2MB!" &lt;&lt; std::endl; return lResult; } // Convert data values &amp; Store results std::wstring lDataValue; convertData(pdwType, pcbData, pvData, lDataValue); aValueData.lDataValue = lDataValue; aValueData.lValueName = lValueName; aValueData.lRegType = pdwType; delete[] pvData; return lResult; } /* Show related functions */ inline std::wstring getHkeyStringName(HKEY aHkey) { if (aHkey == HKEY_CLASSES_ROOT) return L"HKEY_CLASSES_ROOT\\"; if (aHkey == HKEY_CURRENT_CONFIG) return L"HKEY_CURRENT_CONFIG\\"; if (aHkey == HKEY_CURRENT_USER) return L"HKEY_CURRENT_USER\\"; if (aHkey == HKEY_LOCAL_MACHINE) return L"HKEY_LOCAL_MACHINE\\"; if (aHkey == HKEY_USERS) return L"HKEY_USERS\\"; return L"NULL"; } inline std::wstring getDataTypeStringName(unsigned int &amp;aDataType) { if (aDataType == REG_SZ) return L"REG_SZ"; if (aDataType == REG_MULTI_SZ) return L"REG_MULTI_SZ"; if (aDataType == REG_EXPAND_SZ) return L"REG_EXPAND_SZ"; if (aDataType == REG_DWORD) return L"REG_DWORD"; if (aDataType == REG_DWORD_BIG_ENDIAN) return L"REG_DWORD_BIG_ENDIAN"; if (aDataType == REG_DWORD_LITTLE_ENDIAN) return L"REG_DWORD_LITTLE_ENDIAN"; if (aDataType == REG_QWORD) return L"REG_QWORD"; if (aDataType == REG_QWORD_LITTLE_ENDIAN) return L"REG_QWORD_LITTLE_ENDIAN"; if (aDataType == REG_BINARY) return L"REG_BINARY"; if (aDataType == REG_NONE) return L"REG_NONE"; return L"NULL"; } unsigned int WriteToConsole(std::wstring &amp;aString) { int lResult = ERROR_SUCCESS; static HANDLE lConsoleAccess = GetStdHandle(STD_OUTPUT_HANDLE); lResult = WriteConsoleW( lConsoleAccess, aString.c_str(), aString.size(), NULL, NULL ); return lResult; } // Testing //#define __nonEnglishMode //#define __writeToDisk #if defined (__writeToDisk) std::wofstream file; #endif inline void show(HKEY aHkey, std::wstring &amp;aHkeyPath, std::wstring &amp;aSubKey, RegValue &amp;aValueData, bool aDisplayPath, bool aDisplayValue, bool aLastItem) { // Display Key Path HKEY/key/key..ect if (aDisplayPath) { std::wstring lSlash = L"\\"; std::wstring lFullPath; #if defined (__writeToDisk) file &lt;&lt; L"\n"; #endif // Only attach subkey to path name if it is supplied if (aSubKey == L"") { lFullPath = getHkeyStringName(aHkey) + aHkeyPath + L"\n"; } else { lFullPath = getHkeyStringName(aHkey) + aHkeyPath + lSlash + aSubKey + L"\n"; } //fwprintf(stdout, L"%s",lFullPath.c_str()); WriteToConsole(lFullPath); #if defined (__writeToDisk) file &lt;&lt; lFullPath; #endif } if (aDisplayValue) { // Show registry value name std::wstring lValueName = (aValueData.lValueName); if (lValueName == TEXT("")) lValueName = TEXT("(Default)"); // Show registry type std::wstring lDataType = getDataTypeStringName(aValueData.lRegType); std::wstring lDataValue; // Show registry data if (lDataType == L"REG_DWORD" || lDataType == L"REG_QWORD" || lDataType == L"REG_DWORD_LITTLE_ENDIAN" || lDataType == L"REG_QWORD_LITTLE_ENDIAN" || lDataType == L"REG_DWORD_BIG_ENDIAN") { lDataValue = L"0x0" + (aValueData.lDataValue); } else { lDataValue = (aValueData.lDataValue); } std::wstring lKeyValue = L" " + lValueName + L" " + lDataType + L" " + lDataValue + L"\n"; //fwprintf(stdout,L"%s",lKeyValue.c_str()); WriteToConsole(lKeyValue); #if defined (__writeToDisk) file &lt;&lt; lKeyValue; #endif } #if defined (__writeToDisk) if (file.fail()) { file.clear(); } #endif } DWORD getDataTypeFilterMacro(std::string &amp;aDataType) { if (aDataType == "REG_SZ") return RRF_RT_REG_SZ; if (aDataType == "REG_MULTI_SZ") return RRF_RT_REG_MULTI_SZ; if (aDataType == "REG_EXPAND_SZ") return RRF_RT_REG_EXPAND_SZ; if (aDataType == "REG_DWORD") return RRF_RT_DWORD; if (aDataType == "REG_DWORD_BIG_ENDIAN") return RRF_RT_DWORD; if (aDataType == "REG_DWORD_LITTLE_ENDIAN") return RRF_RT_DWORD; if (aDataType == "REG_QWORD") return RRF_RT_QWORD; if (aDataType == "REG_QWORD_LITTLE_ENDIAN") return RRF_RT_QWORD; if (aDataType == "REG_BINARY") return RRF_RT_REG_BINARY; if (aDataType == "REG_NONE") return RRF_RT_REG_NONE; return RRF_RT_ANY; } bool isMatch(RegValue &amp;aRegValueData, std::wstring &amp;aDataType, std::wstring &amp;aSearchItem, std::wstring &amp;aKeyName, bool lCaseSensitive = false, bool lExactMatch = false, bool aSearchKeyOnly = false, bool aSearchDataOnly = false) { bool lResult = false; std::wstring lSearchItem = aSearchItem; std::wstring lValueName = aRegValueData.lValueName; std::wstring lDataValue = aRegValueData.lDataValue; std::wstring lKeyName = aKeyName; // Convert to lowercase if (!lCaseSensitive || !lExactMatch) { std::transform(lSearchItem.begin(), lSearchItem.end(), lSearchItem.begin(), ::tolower); std::transform(lValueName.begin(), lValueName.end(), lValueName.begin(), ::tolower); std::transform(lDataValue.begin(), lDataValue.end(), lDataValue.begin(), ::tolower); std::transform(lKeyName.begin(), lKeyName.end(), lKeyName.begin(), ::tolower); } // Search Key Names if (aSearchKeyOnly) { // Split and store the last key // ...MyCo//Key1//Key3 -&gt;&gt; Key3 auto const pos = lKeyName.find_last_of('\\'); lKeyName = lKeyName.substr(pos + 1); if (lKeyName == lSearchItem) { return true; } return false; } // Search Data if (aSearchDataOnly) { if (lDataValue == lSearchItem) { return true; } return false; } // Search both key name and data value if (!aSearchKeyOnly &amp;&amp; !aSearchDataOnly) { if (lValueName == lSearchItem) { return true; } if (lDataValue == lSearchItem) { return true; } return false; } return false; } bool query(RegBlock &amp;aVal) { int lResult; #if defined (__writeToDisk) file.open("screen_output.txt", std::wofstream::app | std::wofstream::in); #endif // Variables related to Queries/Find HKEY hkey = getHkeyMacro(aVal.lHkey); std::wstring lHkeyPath = aVal.lHkeyPath; bool lValueNameEmpty = aVal.lValueName.empty(); bool lFind = aVal.lOptions["/f"]; bool lSearchRecursive = aVal.lOptions["/s"]; bool lFilterDataType = !(aVal.lDataType.empty()); bool lCaseSensitive = aVal.lOptions["/c"]; bool lExactMatch = aVal.lOptions["/e"]; bool lSearchKeyOnly = aVal.lOptions["/k"]; bool lSearchDataOnly = aVal.lOptions["/d"]; // Specify the search value to use, either the key name or search param input std::wstring lSearchItem = aVal.lData; if (!lValueNameEmpty) { lSearchItem = aVal.lValueName; } std::deque&lt;std::wstring&gt; lSubKeyList; std::queue&lt;std::wstring&gt; lValueList; // Get the list of value names if none is provided if (lValueNameEmpty) { lResult = getValueNameList(hkey, lHkeyPath, NULLWST, lValueList); if (lResult != ERROR_SUCCESS) { error(lResult); return false; } } else { std::wstring lValueName = aVal.lValueName; lValueList.push(lValueName); } // Get inital list of sub keys lResult = getSubKeyList(hkey, lHkeyPath, NULLWST, lSubKeyList); if (lResult != ERROR_SUCCESS) { error(lResult); return false; } RegValue lRegValueData; std::wstring lCurrentSubKey = NULLWST; std::wstring lCurrentValue = NULLWST; unsigned int lMatchTotal = 0; // Allows for the last subkey within the dequeue to be shown lSubKeyList.push_back(L"End"); bool lDisplayPath = false; bool lDisplayValue = true; bool lNewLine = false; bool lMatch = false; while (lSubKeyList.size()) { // Search and Display keys when searching in KEY ONLY mode if (lSearchKeyOnly) { lMatch = isMatch( lRegValueData, aVal.lDataType, lSearchItem, lCurrentSubKey, lCaseSensitive, lExactMatch, lSearchKeyOnly, lSearchDataOnly ); if (lMatch) { lDisplayPath = true; lDisplayValue = false; show(hkey, lHkeyPath, lCurrentSubKey, lRegValueData, lDisplayPath, lDisplayValue, false); lDisplayPath = false; lDisplayValue = true; lNewLine = true; lMatchTotal++; } } // Display the key path in the case of empty key &amp;&amp; list keys when not in recursive/search mode if (lValueList.size() == 0 &amp;&amp; !(lFilterDataType || lFind) &amp;&amp; lValueNameEmpty) { show(hkey, lHkeyPath, lCurrentSubKey, lRegValueData, true, false, false); } else { lDisplayPath = true; } while (lValueList.size() &amp;&amp; !lSearchKeyOnly) { lCurrentValue = lValueList.front(); lValueList.pop(); lResult = getValueData(hkey, lHkeyPath, lCurrentSubKey, lCurrentValue, lRegValueData); if (lResult != ERROR_SUCCESS) { error(lResult); return false; } if (lFind || lFilterDataType) { lMatch = isMatch( lRegValueData, aVal.lDataType, lSearchItem, lCurrentSubKey, lCaseSensitive, lExactMatch, lSearchKeyOnly, lSearchDataOnly ); if (lMatch) { if (lSearchKeyOnly) { lDisplayPath = true; lDisplayValue = false; } show(hkey, lHkeyPath, lCurrentSubKey, lRegValueData, lDisplayPath, lDisplayValue, false); lDisplayPath = false; lDisplayValue = true; lMatchTotal++; lNewLine = true; } } else { show(hkey, lHkeyPath, lCurrentSubKey, lRegValueData, lDisplayPath, lDisplayValue, false); lDisplayPath = false; } } if (lSearchRecursive &amp;&amp; !(lFilterDataType || lFind)) { lNewLine = true; } if (lNewLine) { fwprintf(stdout, L"\n"); lNewLine = false; } // Remove visted Sub-Key from deque lCurrentSubKey = lSubKeyList.front(); lSubKeyList.pop_front(); if (lSearchRecursive &amp;&amp; lCurrentSubKey != L"End") { // If the parent key contains sub-keys, add them to lSubKeyList, // in the order they were retrieved from RegEnumEx. std::deque&lt;std::wstring&gt; lTemp; lResult = getSubKeyList(hkey, lHkeyPath, lCurrentSubKey, lTemp); while (lTemp.size()) { lSubKeyList.push_front(lTemp.back()); lTemp.pop_back(); } // A non-error. Error: "Invalid Handle" // This error code just states that the current key being accessed // does not contain any sub-keys. if (lResult == 6) lResult = 0; if (lResult != ERROR_SUCCESS) { error(lResult); return false; } // Get the current keys value names if (!lSearchKeyOnly) { lResult = getValueNameList(hkey, lHkeyPath, lCurrentSubKey, lValueList); // Ignore key values that cannot be accessed. Error "Access Denied" // Keys cannot be accessed in regedit (admin), so this is a UAC issue. if (lResult == 5) lResult = 0; if (lResult != ERROR_SUCCESS) { error(lResult); return false; } } } } #if defined (__writeToDisk) file.close(); #endif if (lFind || lFilterDataType) { std::cout &lt;&lt; "End of search : " &lt;&lt; lMatchTotal &lt;&lt; " match(es) found." &lt;&lt; std::endl; } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T11:01:47.627", "Id": "384739", "Score": "0", "body": "It would be very helpful for reviewers if you added the missing header files (and possibly cpp files) to the question. Currently, it's hard to evaluate, since important informati...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T04:50:57.797", "Id": "199885", "Score": "4", "Tags": [ "c++", "beginner", "c++11", "windows", "winapi" ], "Title": "Recreated Microsoft's Console Registry Tool's query functionality in C++ (REG.exe)" }
199885
<p>For the purpose of defining a lot of Maximum Likelihood estimators, I think I need a metaclass.</p> <p>At the moment I have to copy/paste a lot of code for every new class definition and just substitute the corresponding scipy.stats functions.</p> <pre><code>from scipy.stats import fisk, t from statsmodels.base.model import GenericLikelihoodModel from inspect import signature class Fisk(GenericLikelihoodModel): """A maximum likelihood estimator for the fisk distribution. """ nparams = 3 def loglike(self, params): return fisk.logpdf(self.endog, *params).sum() def fit(self, **kwargs): if 'start_params' not in kwargs: # This is for performance and! convergence stability. # The scipy function provides better starting params. kwargs['start_params'] = fisk.fit(self.endog) res = super().fit(**kwargs) res.df_model = self.nparams res.df_resid = len(self.endog) - self.nparams return res class T(GenericLikelihoodModel): """A maximum likelihood estimator for the Student-T distribution. """ nparams = 3 def loglike(self, params): return t.logpdf(self.endog, *params).sum() def fit(self, **kwargs): if 'start_params' not in kwargs: # This is for performance and! convergence stability. # The scipy function provides better starting params. kwargs['start_params'] = t.fit(self.endog) res = super().fit(**kwargs) res.df_model = self.nparams res.df_resid = len(self.endog) - self.nparams return res </code></pre> <p>With a metaclass I automated this code definition </p> <pre><code>class ML_estimator(type): def __new__(cls, clsname, bases, dct, f): return super().__new__(cls, clsname, (GenericLikelihoodModel, ), dct) def __init__(cls, clsname, bases, dct, f): cls.nparams = len(signature(f.pdf).parameters) def loglike(self, params): return f.logpdf(self.endog, *params).sum() cls.loglike = loglike def fit(self, **kwargs): if 'start_params' not in kwargs: # This is for performance and! convergence stability. # The scipy function provides better starting params. kwargs['start_params'] = f.fit(self.endog) res = super(cls, self).fit(**kwargs) res.df_model = self.nparams res.df_resid = len(self.endog) - self.nparams return res cls.fit = fit class Fisk(metaclass=ML_estimator, f=fisk): pass class T(metaclass=ML_estimator, f=t): pass </code></pre> <p>Does this seem like a reasonable application of metaclasses? What improvements do you have?</p> <p>The ML-estimator can be tested with:</p> <pre><code>sample = fisk.rvs(c=1, size=1000) res = Fisk(sample).fit() res.summary() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T10:44:03.493", "Id": "384736", "Score": "1", "body": "Is `GenericLikelihoodModel` of your own doing or is it from a third-party library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T11:00:29.527", ...
[ { "body": "<p>Instead of constructing the object and then modifying its methods and attributes, you can directly add them in the <code>__new__</code> method of the metaclass:</p>\n\n<pre><code>class LikelihoodEstimator(type):\n def __new__(cls, name, bases, dct, f):\n def loglike(self, params):\n ...
{ "AcceptedAnswerId": "199907", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T10:19:05.793", "Id": "199899", "Score": "2", "Tags": [ "python", "object-oriented", "python-3.x", "template", "scipy" ], "Title": "Implement metaclass for Maximumlikelihood estimator" }
199899
<p>I have been working through the euler project and I have created the following code for <a href="https://projecteuler.net/problem=14" rel="nofollow noreferrer">Problem 14</a>, which asks which starting number, under 1 million, produces the longest Collatz Sequence chain.</p> <p>It takes a good minute to process. Can I make it faster?</p> <pre><code>class Collatz: def __init__(self): self.c = 1 def if_even(self, n): return int(n / 2) def if_odd(self, n): return int(n * 3 + 1) def decide(self, n): if (n &amp; 1) == 0: return self.if_even(n) elif (n &amp; 1) == 1: return self.if_odd(n) def iter_nums(self, n): if n == 1: return n self.c += 1 n = self.decide(n) self.iter_nums(n) largest = 0 # col = Collatz() # col.iter_nums(13) # print(col.c) for i in range(1000000, -1, -1): col = Collatz() col.iter_nums(i) if col.c &gt; largest: largest = i print(largest) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T13:15:35.643", "Id": "384774", "Score": "2", "body": "A few ideas: 1. don't create a new instance each time; 2. look into caching/memoization/dynamic programming; and 3. simplify the code to remove the redundant method calls, there'...
[ { "body": "<p><strong>Useless calls to <code>int</code></strong></p>\n\n<p>When <code>n</code> is an integer:</p>\n\n<ul>\n<li><p><code>n * 3 + 1</code> is an integer as well, you don't need to call <code>int</code></p></li>\n<li><p><code>int(n / 2)</code> can also be computed using the \"floored quotient\" wit...
{ "AcceptedAnswerId": "199934", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T11:38:51.240", "Id": "199909", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "collatz-sequence" ], "Title": "Euler Project 14 Longest Collatz Sequence" }
199909
<p>I have 3 tables on my database: <code>BusinessObject</code> and <code>CustomEvent</code>, and <code>EventType</code>. <code>BusinessObject</code> having a lot of columns, <code>CustomEvent</code> having the following:</p> <pre><code>Id EventTypeId DateEvent CommentEvent UserId BusinessObjectId </code></pre> <p>I want to get all the <code>BusinessObject</code> having two <code>CustomEvent</code> with EventTypeId in (10, 11) such has the difference between the two DateEvent are more than 1 second. From the 6 first month of this year.</p> <p>I came up with the following query but it's quite slow (~40 seconds). I assume there's a (lot of) ways to speed this up, but my SQL level is not good enough.</p> <p>Here's the query:</p> <pre><code>select bo.Id from BusinessObject bo where ( select top 1 DATEDIFF(second, (select top 1 DateEvent from CustomEvent where EventTypeId = 11 and BusinessObjectid = bo.BusinessObjectId), (select top 1 DateEvent from CustomEvent where EventTypeId = 10 and BusinessObjectid = bo.BusinessObjectId)) from CustomEvent ce inner join BusinessObject innerBO on ce.BusinessObjectId = bo.BusinessObjectId where EventTypeId = 11 and innerBO.CreationDate &lt; '20180701' and innerBO.CreationDate &gt; '20180101' and innerBO.BusinessObjectId = bo.BusinessObjectId ) &gt; 1 </code></pre> <p>FYI, the query returns 4.138 rows. Here's the tables volumes:</p> <p>BusinessObject => 302k lines</p> <p>CustomEvent => 4.326k lines</p> <p>How could I speed this up?</p>
[]
[ { "body": "<p>You need to work on below statement of your code. You are INNER joining two tables but not with both tables reference.</p>\n\n<pre><code>from CustomEvent ce inner join BusinessObject innerBO on ce.BusinessObjectId = bo.BusinessObjectId\n</code></pre>\n\n<p>Please mention your Query-result requirem...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T13:03:17.843", "Id": "199914", "Score": "2", "Tags": [ "performance", "sql", "sql-server" ], "Title": "Query to find instances of two types of events occurring more than one second apart" }
199914
<p>I wrote the following simple 1 producer - 1 consumer problem, in attempt to learn some C++11 threading / generics. </p> <pre><code>#include &lt;iostream&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;deque&gt; #include &lt;thread&gt; struct data { int x, y; std::string s; data() : s("test") { x = std::rand() % 1000000; y = std::rand() % 1000000; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const struct data d) { os &lt;&lt; d.x &lt;&lt; ", " &lt;&lt; d.y &lt;&lt; ", " &lt;&lt; d.s &lt;&lt; "\n"; } }; typedef struct data elem_t; template &lt;typename T&gt; class Buffer { public: Buffer(): m_size(1) {} Buffer(int s): m_size(s) {} void add(T x) { while (true) { std::unique_lock&lt;std::mutex&gt; locker(m_mtx); m_cond.wait(locker, [this](){return m_buffer.size() &lt; m_size;}); m_buffer.push_back(x); locker.unlock(); m_cond.notify_all(); return; } } T remove() { while (true) { std::unique_lock&lt;std::mutex&gt; locker(m_mtx); m_cond.wait(locker, [this](){return m_buffer.size() &gt; 0;}); T x = m_buffer.back(); m_buffer.pop_back(); locker.unlock(); m_cond.notify_all(); return x; } } private: std::mutex m_mtx; std::condition_variable m_cond; std::deque&lt;T&gt; m_buffer; unsigned int m_size; }; template &lt;typename T&gt; class Producer { public: Producer() : m_buf(nullptr) {} Producer(std::string&amp;&amp; id, Buffer&lt;T&gt; *buf) : m_id(id), m_buf(buf) {} void produce() { while (true) { T x = T(); m_buf-&gt;add(x); std::cout &lt;&lt; x; int sleep = std::rand() % 1000 + 10; std::this_thread::sleep_for(std::chrono::milliseconds(sleep)); } } private: Buffer&lt;T&gt; *m_buf; std::string m_id; }; template &lt;typename T = int&gt; class Consumer { public: Consumer() : m_buf(nullptr) {} Consumer(std::string&amp;&amp; id, Buffer&lt;T&gt; *buf) : m_id(id), m_buf(buf) {} void consume() { while(true) { T x = m_buf-&gt;remove(); std::cout &lt;&lt; x; int sleep = std::rand() % 1000 + 10; std::this_thread::sleep_for(std::chrono::milliseconds(sleep)); } } private: Buffer&lt;T&gt; *m_buf; std::string m_id; }; int main(int argc, char const *argv[]) { std::srand(std::time(nullptr)); Buffer&lt;elem_t&gt; *buffer = new Buffer&lt;elem_t&gt;(std::stoi(argv[1])); Producer&lt;elem_t&gt; *p = new Producer&lt;elem_t&gt;("prod", buffer); Consumer&lt;elem_t&gt; *c = new Consumer&lt;elem_t&gt;("cons", buffer); std::thread pt(&amp;Producer&lt;elem_t&gt;::produce, p); std::thread ct(&amp;Consumer&lt;elem_t&gt;::consume, c); pt.join(); ct.join(); return 0; } </code></pre> <p>The main concern I am having with this code is regarding genericity. I have a generic buffer <code>Buffer&lt;T&gt;</code> (which is basically a <code>std::deque&lt;T&gt;</code>) and the produced value: <code>T x = T();</code> </p> <p>For now, <code>T = struct data</code>, and everything works because of <code>data()</code>, but if <code>T = int</code>, for example, things start to get ugly.</p> <p>One idea I have is to define a <code>struct data</code> packing all the needed fields, and then remove templates from classes (i.e. <code>std::deque&lt;struct data&gt;</code> only).</p> <p>So, are templates an <em>overkill</em> here, and if not what is the / a <em>correct</em> way of expressing this code with them? Also, are there any other problems / code smells / things to improve?</p>
[]
[ { "body": "<h1><code>Buffer&lt;T&gt;</code></h1>\n\n<p>This class seems fine for the most part. Some small issues:</p>\n\n<ul>\n<li><p>The <code>while(true)</code> loops in <code>insert(T)</code> and <code>remove()</code> only ever run one iteration. Those loops can be replaced by their body.</p></li>\n<li><p><...
{ "AcceptedAnswerId": "199996", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T13:19:04.447", "Id": "199917", "Score": "6", "Tags": [ "c++", "c++11", "multithreading", "template", "producer-consumer" ], "Title": "Generic Producer-Consumer in C++11" }
199917
<p>I managed to make a many to many relationship work correctly using mysql, doctrine 2 and symfony 3.4.</p> <p>When a new element A that contains 0 to m element Bs is inserted, the B elements that already have the same content are reused, instead of creating new ones. </p> <p>This is not the default doctrine 2 behaviour in a ManyToMany context with <code>cascade={"persist", "remove"}</code>.</p> <hr> <p>The relationship uses an intermediate / join table, that contains id of table A and id of table B.</p> <p>What I did is after deserializing the element A that contains m B elements, I check for each element B if a similar already exist in database.</p> <p>If yes, I reuse it, if not I let doctrine cascade persist / insert new elements B.</p> <p>Pseudocode, inside element A repository.</p> <pre><code>function useExistingDatabaseElementsBForNewElementA($elementA) { $elementsBs = $elementA-&gt;getElementsBs() // use existing elements B if available in database foreach ($elementsBs as $B) { /** @var B $matchingB*/ $matchingB= $this-&gt;elementBRepository-&gt;findOneBy(['data' =&gt; $B-&gt;getData()]); if ($matchingB) { $elementA-&gt;removeElementB($B); $elementA-&gt;addElementB($matchingB); } } } </code></pre> <hr> <p>I do this in the element A repository, by calling the findOne method of the element B repository and checking the result.</p> <p>Is this is an acceptable / correct design choice / implementation.</p> <p>How can it be better, for example using doctrine 2 configuration / annotations instead of my custom method in the element A repository ?</p> <p>Could it be cleaner to implement it elsewhere or another way ?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T14:09:49.023", "Id": "199919", "Score": "2", "Tags": [ "php", "mysql", "database", "doctrine", "symfony3" ], "Title": "Many to many (n to m) relationship without insert duplication php" }
199919
<p>Windows only. So I am writing code to decompile a Windows compiled html help file (*.chm) and then tidy the files found within. Whilst, I have blogged some simple Python examples I now want to write Python code closer to production standards so I'd like a code review thanks. </p> <p>I will bring forth a series of classes , each of them will have a COM interface so they can be scripted from VBA. VBA is my main programming language and interoperability is non-negotiable.</p> <p>I have formatted code according to PEP8. I shortened strings etc.</p> <p>The code can be run as just a script to test its workings, this is how I developed it. The code needs admin rights to register the COM class (you can comment that out if it annoys)</p> <p>Code does the following </p> <ol> <li>Creates a working directory inside %Temp%</li> <li>Copies chm file to working directory inside %Temp%</li> <li>Creates a working subdirectory based of chm filename.</li> <li>Decompiles the chm using hh.exe depositing html files to subdirectory.</li> </ol> <p>Code was ported from VBA equivalent class but I think I moved all over to <code>os.path</code> where it mattered.</p> <p>Other future modules will be posted in future questions.</p> <pre><code>class HelpFileDecompiler(object): _reg_clsid_ = "{4B388A08-8CAB-4568-AF78-47032744A368}" _reg_progid_ = 'PythonInVBA.HelpFileDecompiler' _public_methods_ = ['DecompileHelpFileMain'] def DecompileHelpFileMain(self, sHelpFile): import os.path eg = ", e.g. 'c:\\foo.chm'" if not isinstance(sHelpFile, str): raise Exception("sHelpFile needs to be a string" + eg) if len(sHelpFile) == 0: raise Exception("sHelpFile needs to be a non-null string" + eg) if sHelpFile.lower()[-4:] != ".chm": raise Exception("sHelpFile needs to end with '.chm' " + eg) if not os.path.isfile(sHelpFile): raise Exception("sHelpFile " + sHelpFile + " not found") self.BuildTmpDirectory() sCopiedFile = self.CopyChmFileToTempAppPath(sHelpFile) self.DecompileHelpFile(sCopiedFile) def BuildTmpDirectory(self): import os import os.path sTempAppPath = os.path.join(os.environ['tmp'], 'HelpFileDecompiler') if not os.path.isdir(sTempAppPath): os.mkdir(sTempAppPath) def CopyChmFileToTempAppPath(self, sHelpFile): import shutil import os.path sDestFile = os.path.join(os.environ['tmp'], 'HelpFileDecompiler', os.path.basename(sHelpFile)) shutil.copyfile(sHelpFile, sDestFile) return sDestFile def DecompileHelpFile(self, sHelpFile): import win32api import subprocess import os.path if not os.path.isfile(sHelpFile): raise Exception("sHelpFile " + sHelpFile + " not found") sDecompiledFolder = os.path.join( os.environ['tmp'], 'HelpFileDecompiler', os.path.basename(sHelpFile).split(".")[0]) if not os.path.isdir(sDecompiledFolder): os.mkdir(sDecompiledFolder) sHELPEXE = "C:\Windows\hh.exe" if not os.path.isfile(sHELPEXE): raise Exception("sHELPEXE " + sHELPEXE + " not found") # Not allowed to quote arguments to HH.EXE # so we take the short path to eliminate spaces sHelpFileShort = win32api.GetShortPathName(sHelpFile) sDecompiledFolderShort = win32api.GetShortPathName(sDecompiledFolder) # so now we can run the decompiler subprocess.run([sHELPEXE, '-decompile', sDecompiledFolderShort, sHelpFileShort]) if __name__ == '__main__': print ("Registering COM servers...") import win32com.server.register win32com.server.register.UseCommandLine(HelpFileDecompiler) helpFile=("C:\\Program Files\\Microsoft Office 15\\root\\vfs\\" "ProgramFilesCommonX86\\Microsoft Shared\\VBA\\VBA7.1\\" "1033\\VBLR6.chm") test = HelpFileDecompiler() test.DecompileHelpFileMain(helpFile) </code></pre> <p>Test VBA code is below (but actually one can run from command line also) </p> <pre><code>Option Explicit Sub Test() Dim obj As Object Set obj = VBA.CreateObject("PythonInVBA.HelpFileDecompiler") obj.DecompileHelpFileMain "C:\Program Files\Microsoft Office 15\root\vfs\" &amp; _ "ProgramFilesCommonX86\Microsoft Shared\VBA\VBA7.1\" &amp; _ "1033\VBLR6.chm" End Sub </code></pre> <p>Notes: </p> <ol> <li>Because the VBA client has no type library I have done much argument checking in <code>DecompileHelpFileMain</code></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T16:40:59.557", "Id": "384806", "Score": "0", "body": "You have a comment stating _\"Not allowed to quote arguments to HH.EXE\"_. Why is that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T16:43:53.8...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T15:31:51.650", "Id": "199926", "Score": "2", "Tags": [ "python", "python-3.x", "windows", "com" ], "Title": "(COM Callable) Python class to decompile *.chm file with Microsoft HTML Help Executable" }
199926
<p>This is a follow-up of: <a href="https://codereview.stackexchange.com/questions/199777/text-based-game-hunt-the-wumpus">Text based game &quot;Hunt the Wumpus&quot;</a></p> <p>A follow up of this review was posted here: <a href="https://codereview.stackexchange.com/questions/200532/text-based-game-hunt-the-wumpus-version-3">Text based game “Hunt the Wumpus” Version 3</a></p> <p>I tried to incorporate the suggestions made in the first question into the code. However I still feel that there is maybe space for improvement.</p> <p>I completely changed how the dungeon is made. Now I just build the dodecahedron and fill it with random room numbers (like the original game).</p> <p>Please let me know how to make the code cleaner / better structured.</p> <p>In the raw string of the text the page highlights the code wrong. this seems to be a bug of the codereview page.</p> <p><b> wumpus.h </b></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;vector&gt; namespace wumpus { using Room_number = int; struct Room { std::array &lt;Room*, 3&gt; neighbors{ nullptr }; //pointer to 3 rooms next to this room Room_number room_number{ 0 }; bool has_wumpus{ false }; bool has_pit{ false }; bool has_bat{ false }; bool has_player{ false }; }; class Dungeon { public: Dungeon(); void indicate_hazards(); bool shoot_arrow(std::vector&lt;int&gt; tar_rooms); bool Dungeon::move_wumpus(); bool move_player(Room_number target_room); void debug(); //shows the status of the cave for debug purpose Room_number get_player_room_number() const { return player_room_number; } std::vector&lt;int&gt; get_neighbour_rooms() const { return std::vector&lt;int&gt;{ rooms[player_room_number - 1].neighbors[0]-&gt;room_number, rooms[player_room_number - 1].neighbors[1]-&gt;room_number, rooms[player_room_number - 1].neighbors[2]-&gt;room_number }; } private: static constexpr int count_of_pits = 3; static constexpr int count_of_bats = 3; int arrows = 5; std::array&lt;Room, 20&gt; rooms; Room_number wumpus_room_number; Room_number player_room_number; void connect_rooms_to_dodecahedron(); }; int get_random(int min, int max); void hunt_the_wumpus(); void instructions(); int select_room_to_move(Dungeon&amp; d1); std::vector&lt;int&gt; select_rooms_to_shoot(); } </code></pre> <p><b> wumpus.cpp </b></p> <pre><code>#include "wumpus.h" namespace wumpus { Dungeon::Dungeon() { // construct the Dungeon connect_rooms_to_dodecahedron(); // create room numbers std::vector&lt;Room_number&gt; random_room_numbers; for (size_t i = 0; i &lt; rooms.size(); ++i) { random_room_numbers.push_back(i + 1); } //generate random numbers t0 use to put room numbers random std::random_shuffle(random_room_numbers.begin(), random_room_numbers.end()); // add room numbers randomly for (size_t i = 0; i &lt; rooms.size(), i &lt; random_room_numbers.size(); ++i) { rooms[i].room_number = random_room_numbers[i]; } //add the wumpus rooms[get_random(1, rooms.size())-1].has_wumpus = true; //add pit for (int i = 0; i &lt; count_of_pits; ++i) { int index = get_random(1, rooms.size()) - 1; while (rooms[index].has_wumpus || rooms[index].has_pit) { index = get_random(1, rooms.size()); } rooms[index].has_pit = true; } //add bat for (int i = 0; i &lt; count_of_bats; ++i) { int index = get_random(1, rooms.size())-1; while (rooms[index].has_wumpus || rooms[index].has_pit || rooms[index].has_bat) { index = get_random(1, rooms.size()); } rooms[index].has_bat = true; } { //add player player_room_number = get_random(1, rooms.size()); int index = player_room_number - 1; while (rooms[index].has_wumpus || rooms[index].has_pit || rooms[index].has_bat) { player_room_number = get_random(1, rooms.size()); } rooms[index].has_player = true; } } void Dungeon::indicate_hazards() { bool is_first_bat = true; bool is_first_pit = true; int index = player_room_number - 1; for (auto&amp; x : rooms[index].neighbors) { if (x-&gt;has_wumpus) { std::cout &lt;&lt; "I smell the wumpus\n"; } if (is_first_pit &amp;&amp; x-&gt;has_pit) { is_first_pit = false; std::cout &lt;&lt; "I feel a breeze\n"; } if (is_first_bat &amp;&amp; x-&gt;has_bat) { is_first_bat = false; std::cout &lt;&lt; "I hear a bat\n"; } } std::cout &lt;&lt; "You are in room " &lt;&lt; rooms[index].room_number &lt;&lt; "\n" &lt;&lt; "You have "&lt;&lt;arrows&lt;&lt; " arrow(s) left\n" &lt;&lt; "Tunnels lead to rooms " &lt;&lt; rooms[index].neighbors[0]-&gt;room_number &lt;&lt; ", " &lt;&lt; rooms[index].neighbors[1]-&gt;room_number &lt;&lt; " and " &lt;&lt; rooms[index].neighbors[2]-&gt;room_number &lt;&lt; "\n" &lt;&lt; "what do you want to do? (M)ove or (S)hoot?\n"; } bool Dungeon::shoot_arrow(std::vector&lt;int&gt; target_rooms) //trys to shoot in the supplied tar rooms an arrow //if the wumpus is hit returns true to indicate victory //moves the wumpus on fail { --arrows; int index = player_room_number - 1; for (const auto&amp; target : target_rooms){ bool room_reached = false; for (const auto&amp; neigbour : rooms[index].neighbors) { if (neigbour-&gt;room_number == target) { room_reached = true; index = neigbour-&gt;room_number - 1; if (rooms[index].has_wumpus) { std::cout &lt;&lt; "!!!!!!YOU WON!!!!!!: You killed the Wumpus in room " &lt;&lt; rooms[index].room_number &lt;&lt; "\n"; return true; } break; } } if (!room_reached) { std::cout &lt;&lt; "Room " &lt;&lt; target &lt;&lt; " could not be reached from arrow\n"; return false; } } if (arrows == 0) { std::cout &lt;&lt; "You lost: You ran out of arrows"; return true; } } bool Dungeon::move_wumpus() //moves the wumpus with a chance of 75% to a new room //if player room is entered true is returned for game over { if (get_random(1, 4) == 4) { // no movement on 4 return false; } else { rooms[wumpus_room_number - 1].has_wumpus = false; wumpus_room_number = rooms[wumpus_room_number - 1].neighbors[get_random(0, 2)]-&gt;room_number; rooms[wumpus_room_number - 1].has_wumpus = true; if (rooms[wumpus_room_number - 1].has_player) { std::cout &lt;&lt; "You lost: Wumpus enters youre room and eats you\n"; return true; } } return false; } bool Dungeon::move_player(Room_number target_room) //trys to move player to the selected room //if deadly hazard like pit or wumpus is found return game over = true; //if bat is found choose new random room free from hazards to put the player { for (auto&amp; x : rooms[player_room_number - 1].neighbors) { if (x-&gt;room_number == target) { if (x-&gt;has_wumpus) { std::cout &lt;&lt; "You lost: You got eaten by the Wumpus\n"; return true; } else if (x-&gt;has_pit) { std::cout &lt;&lt; "You lost: You fell in a bottomless pit\n"; return true; } else if (x-&gt;has_bat) { std::cout &lt;&lt; "Gigantic bat appeared!!!\n"; std::cout &lt;&lt; "You got dragged to a new room\n"; int index = get_random(1, rooms.size()) - 1; //Only put player in empty room while (rooms[index].has_wumpus || rooms[index].has_pit || rooms[index].has_bat || rooms[index].has_player) { index = get_random(1, rooms.size()) - 1; } rooms[player_room_number - 1].has_player = false; player_room_number = index + 1; rooms[index].has_player = true; return false; } else { rooms[player_room_number - 1].has_player = false; player_room_number = target; rooms[player_room_number - 1].has_player = true; return false; } } } std::cerr &lt;&lt; "Dungeon::move_player: Unknown target room entered"; return false; } void Dungeon::debug() { for (const auto&amp;x : rooms) { std::cout &lt;&lt; "Room " &lt;&lt; x.room_number &lt;&lt; " connects to: "; for (const auto&amp;y : x.neighbors) { if (y != nullptr) std::cout &lt;&lt; y-&gt;room_number &lt;&lt; " "; else std::cout &lt;&lt; "np" &lt;&lt; " "; } std::cout &lt;&lt; " "; if (x.has_wumpus) { std::cout &lt;&lt; "wumpus:" &lt;&lt; x.has_wumpus &lt;&lt; " "; } if (x.has_pit) { std::cout &lt;&lt; "pit:" &lt;&lt; x.has_pit &lt;&lt; " "; } if (x.has_bat) { std::cout &lt;&lt; "bat:" &lt;&lt; x.has_bat &lt;&lt; " "; } if (x.has_player) { std::cout &lt;&lt; "player:" &lt;&lt; x.has_player &lt;&lt; " "; } std::cout &lt;&lt; "\n"; } } //------------------------------------------------------------- //Private functions //------------------------------------------------------------- void Dungeon::connect_rooms_to_dodecahedron() { rooms[0].neighbors = { &amp;rooms[1] ,&amp;rooms[4], &amp;rooms[19] }; rooms[1].neighbors = { &amp;rooms[0] ,&amp;rooms[2], &amp;rooms[17] }; rooms[2].neighbors = { &amp;rooms[1] ,&amp;rooms[3], &amp;rooms[15] }; rooms[3].neighbors = { &amp;rooms[2] ,&amp;rooms[4], &amp;rooms[13] }; rooms[4].neighbors = { &amp;rooms[0] ,&amp;rooms[3], &amp;rooms[5] }; rooms[5].neighbors = { &amp;rooms[4] ,&amp;rooms[6], &amp;rooms[12] }; rooms[6].neighbors = { &amp;rooms[5] ,&amp;rooms[7], &amp;rooms[19] }; rooms[7].neighbors = { &amp;rooms[6] ,&amp;rooms[8], &amp;rooms[11] }; rooms[8].neighbors = { &amp;rooms[7] ,&amp;rooms[9], &amp;rooms[18] }; rooms[9].neighbors = { &amp;rooms[8] ,&amp;rooms[10], &amp;rooms[16] }; rooms[10].neighbors = { &amp;rooms[9] ,&amp;rooms[11], &amp;rooms[14] }; rooms[11].neighbors = { &amp;rooms[7] ,&amp;rooms[10], &amp;rooms[12] }; rooms[12].neighbors = { &amp;rooms[5] ,&amp;rooms[11], &amp;rooms[13] }; rooms[13].neighbors = { &amp;rooms[3] ,&amp;rooms[12], &amp;rooms[14] }; rooms[14].neighbors = { &amp;rooms[10] ,&amp;rooms[13], &amp;rooms[15] }; rooms[15].neighbors = { &amp;rooms[2] ,&amp;rooms[14], &amp;rooms[16] }; rooms[16].neighbors = { &amp;rooms[9] ,&amp;rooms[15], &amp;rooms[17] }; rooms[17].neighbors = { &amp;rooms[1] ,&amp;rooms[16], &amp;rooms[18] }; rooms[18].neighbors = { &amp;rooms[8] ,&amp;rooms[17], &amp;rooms[19] }; rooms[19].neighbors = { &amp;rooms[0] ,&amp;rooms[6], &amp;rooms[18] }; } //------------------------------------------------------------- //Helper functions //------------------------------------------------------------- int get_random(int min, int max) { static std::random_device rd; static std::mt19937 mt(rd()); std::uniform_int_distribution&lt;int&gt; distribution(min, max); return distribution(mt); } void hunt_the_wumpus() { instructions(); for (;;) // restart game { Dungeon d1; for (;;) { // current room handle d1.indicate_hazards(); std::string in; std::cin &gt;&gt; in; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(999, '\n'); continue; } bool game_over = false; if (in == "m" || in == "M" || in == "Move" || in == "move") { game_over = d1.move_player(select_room_to_move(d1)); } else if (in == "s" || in == "S" || in == "Shoot" || in == "shoot") { game_over = d1.shoot_arrow(select_rooms_to_shoot()); if (game_over == true) { break; } game_over = d1.move_wumpus(); } if (game_over == true) { break; } } std::cout &lt;&lt; "Press any key to start a new game or (q)uit to end game\n"; std::string in; std::cin &gt;&gt; in; if (in == "q" || in == "Q" || in == "Quit" || in == "quit") break; } } void instructions() { std::cout &lt;&lt;R"(Welcome to "Hunt the Wumpus"! The wumpus lives in a cave of rooms.Each room has 3 tunnels leading to other rooms. (Look at a dodecahedron to see how this works - if you don't know what a dodecahedron is, ask someone). Hazards Bottomless pits - two rooms have bottomless pits in them.If you go there, you fall into the pit(and lose!) Super bats - two other rooms have super bats.If you go there, a bat grabs you and takes you to some other room at random. (Which may be troublesome). Wumpus The wumpus is not bothered by hazards(he has sucker feet and is too big for a bat to lift).Usually he is asleep.Two things wake him up : you shooting an arrow or you entering his room.\n" If the wumpus wakes he moves(p = .75) one room or stays still(p = .25).After that, if he is where you are, he eats you up and you lose!\n" Each turn you may move or shoot a crooked arrow. Moving: you can move one room(thru one tunnel). Arrows : you have 5 arrows.You lose when you run out.Each arrow can go from 1 to 3 rooms.You aim by telling the computer the rooms you want the arrow to go to.If the arrow can\'t go that way (if no tunnel) it moves at random to the next room.If the arrow hits the wumpus, you win.If the arrow hits you, you lose. Warnings When you are one room away from a wumpus or hazard, the computer says : Wumpus: "I smell the wumpus" Bat : "I hear a bat" Pit : "I feel a breeze" "Press any key to start")"; char c; std::cin.get(c); } int select_room_to_move(Dungeon&amp; d1) { for(;;) { std::cout &lt;&lt; "To where??\n"; int target = 0; std::cin &gt;&gt; target; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(999, '\n'); continue; } std::vector&lt;int&gt; neighbor = d1.get_neighbour_rooms(); if (target == neighbor[0] || target == neighbor[1] || target == neighbor[2]) return target; } } std::vector&lt;int&gt; select_rooms_to_shoot() { for(;;){ std::cout &lt;&lt; "Enter the rooms you want to shoot the arrow (e.g. 2-3-12, e.g. 4-5, e.g. 2)\n"; std::string input; std::cin &gt;&gt; input; std::istringstream ist{ input }; std::vector&lt;int&gt; target_rooms; bool bad_input = false; while (!ist.eof()) { int room_number; ist &gt;&gt; room_number; if (ist.fail()) { bad_input = true; break; } target_rooms.push_back(room_number); if (target_rooms.size() == 3 || ist.eof()) break; char seperator; ist &gt;&gt; seperator; if (ist.fail()) { bad_input = true; break; } if ((seperator != '-') || (target_rooms.size() &gt; 3)) { bad_input = true; break; } } if (bad_input) { continue; } else { return target_rooms; } } } } </code></pre> <p><b> main.cpp </b></p> <pre><code>#include &lt;iostream&gt; #include "wumpus.h" int main() try { wumpus::hunt_the_wumpus(); } catch (std::runtime_error&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; "\n"; std::cin.get(); } catch (...) { std::cerr &lt;&lt; "unknown error\n"; std::cin.get(); } </code></pre>
[]
[ { "body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Fix the bug (#1)</h2>\n\n<p>The <code>Dungeon::move_player</code> takes <code>target_room</code> as a parameter, but then refers to <code>target</code> within the code for the function, so it doesn't compile at the moment. I assume...
{ "AcceptedAnswerId": "199941", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T16:45:12.510", "Id": "199931", "Score": "4", "Tags": [ "c++", "game" ], "Title": "Text based game “Hunt the Wumpus” Version 2" }
199931
<p>I've written some simple helper functions that read data types from a vector of bytes (binary files) and having a tough time deciding which route to go. </p> <p><strong>Method 1 : reinterpret_cast</strong></p> <pre><code>int32_t read_32s(const std::vector&lt;uint8_t&gt; &amp;buf, const unsigned offset, const bool bswap = false) { // Check for out of bounds if (offset &gt; buf.size() - sizeof(int32_t)) { // error handling } // Cast the pointer to int32_t and get the first value const auto val = reinterpret_cast&lt;const int32_t *&gt;(&amp;buf[offset])[0]; // Swap bytes if necessary if (bswap) { return (((val &amp; 0xFF000000) &gt;&gt; 24) | ((val &amp; 0x00FF0000) &gt;&gt; 8) | ((val &amp; 0x0000FF00) &lt;&lt; 8) | ((val &amp; 0x000000FF) &lt;&lt; 24)); } return val; } </code></pre> <p>The biggest advantage with this method is probably performance, readability is debatable. This basically compiles down to a single instruction, two if you need to swap the bytes. The problem I have with this is casting like this in modern C++ is frowned upon, and I am unsure how safe it actually is despite bounds checking first. How does alignment work?</p> <p><strong>Method 2 : classic bit shifts</strong></p> <pre><code>int32_t read_32s(const std::vector&lt;uint8_t&gt; &amp;buf, const unsigned offset, const bool bswap = false) { // Check for out of bounds if (offset &gt; buf.size() - sizeof(int32_t)) { // error handling } // Swap bytes if necessary if (bswap) { return (buf[offset] &lt;&lt; 24) | (buf[offset + 1] &lt;&lt; 16) | (buf[offset + 2] &lt;&lt; 8) | buf[offset + 3]; } return (buf[offset + 3] &lt;&lt; 24) | (buf[offset + 2] &lt;&lt; 16) | (buf[offset + 1] &lt;&lt; 8) | buf[offset]; } </code></pre> <p>Very simple bit shifting, about double the instructions as the first method, and can get a bit messy with larger data types. I presume this is the safer solution though, and perhaps more readable.</p> <p>Is the first method OK, or would you consider it to be poor code in comparison to the second method? Or maybe there's just a better method all together (<code>std::byte</code>?).</p> <p><a href="https://godbolt.org/g/G1QTu5" rel="noreferrer">Here</a> is a compiler explorer link with both examples.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T10:19:26.200", "Id": "384855", "Score": "1", "body": "I wonder why do you need bswap at all. Is it to swap bytes from a known endianness to host? If that's the case...You should never ever do it (and you may want to double check you...
[ { "body": "<p>I'm quite fine with the first approach. You are \"reinterpreting\" 4 bytes as a single 32-bit value.</p>\n\n<p>However, I might want to replace the <code>[0]</code> array look-up with a straight dereference.</p>\n\n<pre><code>const auto val = * reinterpret_cast&lt;const int32_t *&gt;(&amp;buf[off...
{ "AcceptedAnswerId": "199946", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T18:51:20.857", "Id": "199935", "Score": "9", "Tags": [ "c++", "c++11", "comparative-review", "integer", "serialization" ], "Title": "reinterpret_cast vs bit shifts for extracting 32-bit integers from bytes, with either endianness" }
199935
<p><a href="https://i.stack.imgur.com/N5y9C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N5y9C.png" alt="enter image description here"></a></p> <h1>Introduction</h1> <p>I am working on a semi large project with a few hundred files. In this project there is a series of <em>lesson.yml</em> files I want to check is formatted correctly. And, yes, every file I want is called exactly that.</p> <p><em>Just to clarify my code works, and does exactly what I want. However, I expect there either exists a better method, or that the code can be cleaned up significantly.</em></p> <p>The files look exactly like this</p> <pre><code>level: 1-4 topic: [tags1] subject: [tags2] grade: [tags3] </code></pre> <p>or this</p> <pre><code>indexed: false topic: [tags1] subject: [tags2] grade: [tags3] </code></pre> <p>If the file starts with <code>indexed: false</code> it should be skipped. </p> <p>The title <code>level:</code> has to be from 1 to 4. Every file must have the titles <em>topic</em>, <em>subject</em> and <em>grade</em>, and only one of them . The tags can only be any of the words below. </p> <pre><code> topic_tags: app|electronics|step_based|block_based|text_based|minecraft|web|game|robot|animation|sound|cryptography, subject_tags: mathematics|science|programming|technology|music|norwegian|english|arts_and_crafts|social_science grade: preschool|primary|secondary|junior|senior </code></pre> <h2>Test cases</h2> <pre><code>level: 9 tags: topic: [block_based, game] subject: [programming] grade: [primary, secondary, junior] </code></pre> <p>This should output the <code>filepath</code> then <code>level: 9</code> with the <em>9</em> in red, as only levels 1-4 is supported. </p> <pre><code>level: 3 tags: topic: [text_based] subject: [mathematics, programming, yodeling] grade: [junior, senior] </code></pre> <p>This should output the line the <code>filepath</code> then <code>subject: [mathematics, programming, yodeling]</code> where the word <em>yodeling</em> is marked in red, as it is not a valid subject (even if most of us think it should be).</p> <pre><code>level: 1 </code></pre> <p>This should output <code>filepath: missing: topic, subjects, grade</code> where topic, subjects, and grade is marked in red. </p> <pre><code>level: 9 tags: topic: [block_based, game] subject: [programming] grade: [primary, secondary, junior] grade: [primary, junior] </code></pre> <p>This one should output filepath then <code>extra: grade</code> as there is more than one grade. </p> <h2>Results</h2> <p>Running the code on my database returns something like this</p> <p><a href="https://i.stack.imgur.com/N5y9C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N5y9C.png" alt="enter image description here"></a></p> <h1>Code</h1> <pre><code>import glob from termcolor import colored from collections import defaultdict import re tags_ = dict( level="[1-4]", topic= "app|electronics|step_based|block_based|text_based|minecraft|web|game|robot|animation|sound|cryptography", subject= "mathematics|science|programming|technology|music|norwegian|english|arts_and_crafts|social_science", grade="preschool|primary|secondary|junior|senior", ) # If a file starts with "indexed: false" skip it def is_indexed(filename): with open(filename, 'r') as f: first_line = f.readline().replace(" ", "").lower().strip() return first_line != "indexed:false" # Colors the words from bad_words red in a line def color_incorrect(bad_words, line): line = re.sub('(' + '|'.join(bad_words) + ')', '{}', line) return line.format(*[colored(w, 'red') for w in bad_words]) def find_incorrect_titles(title_count, titles): missing = [] extra = [] for title in titles: if title_count[title] &gt; 1: extra.append(colored(title, 'red')) elif title_count[title] &lt; 1: missing.append(colored(title, 'red')) miss_str = 'missing: ' + ', '.join(missing) if missing else '' extra_str = 'extra: ' + ', '.join(extra) if extra else '' if miss_str: return miss_str + ' | ' + extra_str if extra_str else miss_str else: return extra_str def find_incorrect_tags(filename): title_count = defaultdict(int) # Counts number of titles, topics, etc incorrect_tags = [] with open(filename, 'r') as f: for line in f: line = line.strip() for title, tag in tags_.items(): if not line.startswith(title): continue title_count[title] += 1 n = True # Finds every non-legal tag as defined at the start of the file regex = r'\b(?!{0}|{1}\b)\w+'.format(title, tag) m = re.findall(regex, line) # Places the words in a list if m: # If we got any hits, this means the words are wrong line = color_incorrect(m, line) # color the words # This block finds titles without any legal words (empty). else: if title != "level": regex_legal = r'{0}: *\[( *({1}),? *)+\]'.format( title, tag) else: regex_legal = r'{0}: *( *({1}),? *)+'.format( title, tag) n = re.search(regex_legal, line) # If no legal words has been found, color the line red if not n: line = colored(line, 'red') if m or not n: # Add line to list of incorrect tags incorrect_tags.append( (' ' * 4 if title != "level" else " ") + line) break # We find if any title, topic, subject does not appear exactly once return (incorrect_tags, title_count) def print_incorrect_titles_and_tags(filename): incorrect_tags, title_count = find_incorrect_tags(filename) incorrect_titles = find_incorrect_titles(title_count, tags_.keys()) # If any errors are found we print them if incorrect_titles or incorrect_tags: print(colored(filename, 'yellow') + ": " + incorrect_titles) print('\n'.join(incorrect_tags)) if incorrect_tags else '' if __name__ == "__main__": path = '../oppgaver/src' files = glob.glob(path + '/**/lesson.yml', recursive=True) for f in files: if is_indexed(f): print_incorrect_titles_and_tags(f) </code></pre>
[]
[ { "body": "<p>This is an odd statement:</p>\n\n<pre><code>print('\\n'.join(incorrect_tags)) if incorrect_tags else ''\n</code></pre>\n\n<p>It produces the return value of <code>print()</code>, if <code>incorrect_tags</code> is truthy, otherwise it produces <code>''</code>.</p>\n\n<p>If the <code>print()</code> ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T19:51:02.573", "Id": "199937", "Score": "2", "Tags": [ "python", "regex", "validation", "file-system" ], "Title": "Finding incorrect yml headers" }
199937
<p>I am a golang novice... I am trying to write an application that takes in many requests - up to a sustained 10000 HTTP posts/sec and post the payload to two back-ends in parallel (5 second timeout). A canned message is returned to the client, it doesn't matter whether the backed end returns a response or errors out, the same response text is sent to the client.</p> <p>I have a first crack at it below. I'm not worried about error handling yet. My thinking is that I can make each back-end call asynchronous using goroutines and let the go runtime deal with queuing/threads for the go routines. I simply need to perform the post and log the result, there is no communication between goroutines. I have had others guide me to using channels, but given that I don't need to return any data back from the post I'm not sure I need them. </p> <p>Here is my first very simple crack at it. Please make any suggestions on the code and approach!</p> <pre><code>package main import ( "fmt" "github.com/go-chi/chi" "net/http" "io/ioutil" "bytes" "time" ) func main() { r := chi.NewRouter() r.Post("/", func(w http.ResponseWriter, r *http.Request) { handlePost(w, r); }) http.ListenAndServe(":3000", r) } func handlePost(w http.ResponseWriter, r *http.Request) { body, _ := ioutil.ReadAll(r.Body) fmt.Fprintf(w, "dummy response will go here"); go callBackend("http://backend1", body) go callBackend("http://backend2", body) } func callBackend(url string, body []byte) { req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) req.Header.Set("Content-Type", "application/xml") client := &amp;http.Client{ Timeout: time.Second * 5, } resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Sprintf("backend [%s] response status: %s", url, resp.Status) fmt.Println("backend response Headers:", resp.Header) responsebody, _ := ioutil.ReadAll(resp.Body) fmt.Println("backend response Body:", string(responsebody)) } </code></pre>
[]
[ { "body": "<pre><code>r.Post(\"/\", func(w http.ResponseWriter, r *http.Request) {\n handlePost(w, r)\n})\n</code></pre>\n\n<p>can be simplified to</p>\n\n<pre><code>r.Post(\"/\", handlePost)\n</code></pre>\n\n<p>since both functions have same signature.</p>\n\n<hr>\n\n<pre><code>fmt.Fprintf(w, \"dummy respo...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T21:18:51.073", "Id": "199940", "Score": "4", "Tags": [ "go", "concurrency", "http" ], "Title": "HTTP Load test with Golang" }
199940
<p><code>std::variant</code> and <code>boost::variant</code> do not require the types involved to be unique, but lose some functionality when types repeat.</p> <p>I'm trying to create a simple type that has a fixed number of cases (<code>std::variant</code> and <code>boost::variant</code> are variadic) and has an elimination form that approximates the look and feel of <code>match</code>/<code>case</code>.</p> <p>Here's a sum type with two variants in OCaml:</p> <pre><code>type red_or_blue_int = Red of int | Blue of int </code></pre> <p>and here's a <code>match</code> statement:</p> <pre><code>match r_or_b with | Red r -&gt; string_of_int r | Blue b -&gt; string_of_int b </code></pre> <p>That is more or less the syntax that I'm trying to emulate.</p> <p>The syntax that I did manage to get looks like this:</p> <pre><code>BinaryPatternMatch&lt;std::string, int, int, decltype(on_left), decltype(on_right)&gt;::match( &amp;inr, on_left, on_right ) </code></pre> <p>where <code>on_left</code> and <code>on_right</code> would typically be lambdas. I'm not sure how to set up the deduction so that the types can be omitted.</p> <p>Here's the header file:</p> <pre><code>#ifndef BINARY_SUM_HPP #define BINARY_SUM_HPP #include &lt;cstring&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;cassert&gt; namespace binary_sum { /* is_decayed */ template &lt;class T&gt; struct is_decayed { static constexpr bool value = std::is_same&lt;T, typename std::decay&lt;T&gt;::type&gt;::value; }; /* end_is_decayed */ /* is_initializer_list */ template &lt;class T&gt; struct is_initializer_list { static constexpr bool value = false; }; template &lt;class T&gt; struct is_initializer_list&lt;std::initializer_list&lt;T&gt;&gt; { static constexpr bool value = true; }; /* end is_initializer_list */ template &lt;class Left, class Right&gt; class Either { public: virtual bool is_left() = 0; virtual bool is_left() const = 0; }; template &lt;class Left, class Right&gt; class InLeft : public Either&lt;Left, Right&gt; { protected: Left left; template &lt;class T&gt; static constexpr bool enable_from_left_ctor = std::is_convertible&lt;T, Left&gt;::value &amp;&amp; is_decayed&lt;T&gt;::value &amp;&amp; (!(is_initializer_list&lt;T&gt;::value)); public: bool is_left() override { return true; } bool is_left() const override { return true; } template &lt; class T, class = typename std::enable_if&lt;enable_from_left_ctor&lt;T&gt;&gt;::type &gt; InLeft(T&amp;&amp; t) : left(t) {} InLeft(InLeft&lt;Left, Right&gt;&amp;&amp; t) : left(std::move(t.left)) {} InLeft(const InLeft&lt;Left, Right&gt;&amp; t) : left(t.left) {} }; template &lt;class Left, class Right&gt; class InRight : public Either&lt;Left, Right&gt; { protected: Right right; template &lt;class T&gt; static constexpr bool enable_from_right_ctor = std::is_convertible&lt;T, Right&gt;::value &amp;&amp; is_decayed&lt;T&gt;::value &amp;&amp; (!(is_initializer_list&lt;T&gt;::value)); public: bool is_left() override { return false; } bool is_left() const override { return false; } template &lt; class T, class = typename std::enable_if&lt;enable_from_right_ctor&lt;T&gt;&gt;::type &gt; InRight(T&amp;&amp; t) : right(t) {} InRight(InRight&lt;Left, Right&gt;&amp;&amp; t) : right(t.right) {} InRight(const InRight&lt;Left, Right&gt;&amp; t) : right(t.right) {} }; template &lt;class Res, class Left, class Right, class LeftBranch, class RightBranch&gt; struct BinaryPatternMatch { static Res match(const Either&lt;Left, Right&gt; *e, LeftBranch lb, RightBranch rb) { assert(e != nullptr); if (e-&gt;is_left()) { return lb(*(static_cast&lt;const InLeft&lt;Left, Right&gt; *&gt;(e))); } else { return rb(*(static_cast&lt;const InRight&lt;Left, Right&gt; *&gt;(e))); } } }; }; #endif </code></pre> <p>And here's the corresponding (minimal) test suite:</p> <pre><code>// binary sum #include &lt;gtest/gtest.h&gt; #include "binary_sum.hpp" #include &lt;string&gt; #define UNUSED(x) \ ((void)(x)) using namespace binary_sum; TEST(BinarySum, InLeftConstr1) { InLeft&lt;int, int&gt; inl(4.0); ASSERT_EQ(inl.is_left(), true); auto on_left = [](const InLeft&lt;int, int&gt;&amp; x) { UNUSED(x); return std::string("LEFT"); }; auto on_right = [](const InRight&lt;int, int&gt;&amp; x) { UNUSED(x); return std::string("RIGHT"); }; std::string patres( BinaryPatternMatch&lt;std::string, int, int, decltype(on_left), decltype(on_right)&gt;::match( &amp;inl, on_left, on_right ) ); ASSERT_STREQ( "LEFT", patres.c_str() ); } TEST(BinarySum, InLeftConstr2) { InLeft&lt;int, int&gt; inl{4.0}; ASSERT_EQ(inl.is_left(), true); } TEST(BinarySum, InRight1) { InRight&lt;int, int&gt; inr(4.0); ASSERT_EQ(inr.is_left(), false); auto on_left = [](const InLeft&lt;int, int&gt;&amp; x) { UNUSED(x); return std::string("LEFT"); }; auto on_right = [](const InRight&lt;int, int&gt;&amp; x) { UNUSED(x); return std::string("RIGHT"); }; std::string patres( BinaryPatternMatch&lt;std::string, int, int, decltype(on_left), decltype(on_right)&gt;::match( &amp;inr, on_left, on_right ) ); ASSERT_STREQ( "RIGHT", patres.c_str() ); } </code></pre> <p>The project was build using two Makefiles, one handling <code>gtest</code> and one for the main project. They aren't terrible idiomatic, <code>CMake</code> would probably be a better choice here. They aren't really the main subject of the review, but are here for the sake of completeness/reproducibility.</p> <pre><code># Makefile CC ?= clang CXX ?= clang++ # our values come first, so they can be overridden CFLAGS ?= CPPFLAGS := -Igtest/include $(CPPFLAGS) CXXFLAGS := -std=c++14 -g -O2 -Wall -Werror -Wextra -fsanitize=address $(CXXFLAGS) LDFLAGS := -fsanitize=address -L. -lgtest -lgtest_main -lpthread $(LDFLAGS) # ugly, ugly rule. call ourselves with the libgtest in order # to prevent the dependency from appearing in $^ binary_sum: binary_sum.cpp.o $(MAKE) libgtest.a $(MAKE) libgtest_main.a $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -o $@ $^ %.cpp.o : %.cpp $(wildcard *.hpp) $(CXX) $(CPPFLAGS) -c $(CXXFLAGS) -o $@ $&lt; clean: $(RM) $(wildcard *.cpp.o) binary_sum $(MAKE) -f gtest.mak clean libgtest.a: $(MAKE) -f gtest.mak $@ libgtest_main.a: $(MAKE) -f gtest.mak $@ </code></pre> <p>and for building <code>gtest</code> and depositing its artifacts in the local directory.</p> <pre><code># gtest.mak GTEST_SRC ?= /usr/src/gtest GTEST_INCLUDE ?= /usr/include/gtest CPPFLAGS := -isystem -I$(dirname $(GTEST_HEADERS)) -I$(GTEST_SRC) $(CPPFLAGS) CXXFLAGS := -g -Wall -Wextra $(CXXFLAGS) # specifically override link-time options LDFLAGS := GTEST_HEADERS ?= $(wildcard $(GTEST_INCLUDE)/*.h) $(wildcard $(GTEST_INCLUDE)/internal/*.h) GTEST_SRCS ?= $(wildcard $(GTEST_SRC)/*.cc) $(wildcard $(GTEST_SRC)/*.h) gtest-all.o : $(GTEST_SRCS) $(GTEST_HEADERS) $(CXX) $(CPPFLAGS) -c $(CXXFLAGS) -o $@ $(GTEST_SRC)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS) $(GTEST_HEADERS) $(CXX) $(CPPFLAGS) -c $(CXXFLAGS) -o $@ $(GTEST_SRC)/src/gtest_main.cc libgtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ libgtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ clean: $(RM) gtest-all.o gtest_main.o libgtest.a libgtest_main.a </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T05:14:01.143", "Id": "384839", "Score": "1", "body": "IIRC, std::variant can have multiple equal types, but accessing them is only allowed through std::get with index specialization." }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>The way to fix your template deduction is: You have a function you're calling with certain arguments that you want to deduce the types of, right? So make that function into a template! That is, take your current:</p>\n\n<pre><code>template &lt;class Res, class Left, class Right, class LeftBranch, ...
{ "AcceptedAnswerId": "200004", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T23:35:08.493", "Id": "199943", "Score": "3", "Tags": [ "c++", "template-meta-programming", "variant-type" ], "Title": "Template Metaprogramming Discriminated Union" }
199943
<p>This is my first ever project I've coded in Python so I'm sorry if it's a little novice. I'm just looking for beginner feedback on what I could improve next time.</p> <p>There is one issue with this calculator: let's say I add 1 and 2, I expect to get <code>3</code>, instead it returns <code>3.0</code>, but I'm guessing that's because I'm casting to a float.</p> <p>The reason I'm casting to a float is to accept decimals in the equation. It would be nicer if it displayed the whole number without the <code>.0</code></p> <pre><code>while True: calculation = input("Calculation: ") if (calculation.__contains__("+")): print(float(calculation.split('+')[0]) + float(calculation.split('+')[1])) elif (calculation.__contains__("-")): print(float(calculation.split('-')[0]) - float(calculation.split('-')[1])) elif (calculation.__contains__("*")): print(float(calculation.split('*')[0]) * float(calculation.split('*')[1])) elif (calculation.__contains__("/")): print(float(calculation.split('/')[0]) / float(calculation.split('/')[1])) </code></pre>
[]
[ { "body": "<p><a href=\"https://www.python-course.eu/python3_magic_methods.php\" rel=\"nofollow noreferrer\">Pythons magic methods</a> are there to make your life easier, not harder. They allow custom classes to use built-in functionality. They are not there so you have to use long names with built-in types. </...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T23:55:50.287", "Id": "199947", "Score": "5", "Tags": [ "python", "beginner", "calculator" ], "Title": "Python novice's calculator" }
199947
<p>on leetcode.com, there is a question with the following description: </p> <blockquote> <p>Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. <a href="https://leetcode.com/problems/keyboard-row/description/" rel="noreferrer">link to the question here.</a></p> </blockquote> <p>Here is my implementation: </p> <pre><code>class Solution { public: std::vector&lt;std::string&gt; findWords(std::vector&lt;std::string&gt;&amp; words) { std::unordered_set&lt;char&gt; firstRow = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'}; std::unordered_set&lt;char&gt; secondRow = {'A','S','D','F','G','H','J','K','L'}; std::unordered_set&lt;char&gt; thirdRow = {'Z','X','C','V','B','N','M'}; std::vector&lt;std::string&gt; result; size_t vecSize = words.size(); for(size_t i = 0; i &lt; vecSize; ++i) { if(sameRow(words[i], firstRow)) result.push_back(words[i]); else if(sameRow(words[i], secondRow)) result.push_back(words[i]); else if(sameRow(words[i], thirdRow)) result.push_back(words[i]); } return result; } bool sameRow(const std::string&amp; words, const std::unordered_set&lt;char&gt;&amp; row) { size_t wordSize = words.size(); for(size_t j = 0; j &lt; wordSize; ++j) { if(row.find(toupper(words[j])) == row.end()) { return false; } } return true; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T06:28:44.387", "Id": "384842", "Score": "0", "body": "if you're allowed to use C `strspn()` was made for this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T07:52:46.287", "Id": "385028", "S...
[ { "body": "<h3>Algorithm/Data Structure Selection</h3>\n\n<p>Right now you're using three separate sets, one of the letters in each row of the keyboard.</p>\n\n<p>Instead, I think I'd use a single map from character to row number. Then you can start with the first character in the string, and find what row it's...
{ "AcceptedAnswerId": "199956", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T02:45:56.180", "Id": "199954", "Score": "6", "Tags": [ "c++", "programming-challenge" ], "Title": "Find words that can be typed using only one row on a keyboard" }
199954
<p>I'm new to Python and decided to work on a personal project and make a program that web scrapes and downloads manga. It works as expected, however, I am sure that there is a better way to structure my code. I'd appreciate some guidance on how to better write this project. You can check it out on my GitHub <a href="https://github.com/idenc/Manga-Downloader" rel="noreferrer">here</a>.</p> <pre><code>import threading import requests import os import re import queue from bs4 import BeautifulSoup from display import Display def gen_title(link): """Finds title of manga and removes any illegal characters""" page = requests.post(link, data=dict(adult="true")) soup = BeautifulSoup(page.text, 'lxml') title = soup.find('h1', {"class": "hb dnone"}).find('a').get('title') # Search for invalid characters and remove them. return re.sub('[^A-Za-z0-9 ]+', '', title) def get_volume(soup): """Finds volume num""" volume = soup.find('h1', {"class": "hb dnone"}).findAll('a') volume = volume[1].get('title') # Grab first number in title temp = re.findall('\d+', volume) return "Volume " + temp[0] def write_image(image, title, volume, counter): """Writes image to a file""" # Write the image to a file in chapter directory imagefile = open(title + "/" + volume + "/" + str(counter) + ".png", 'wb') imagefile.write(image.content) imagefile.close() def download_manga(start_link, end_link=""): """given a start link and end link from twistedhelscans.com, downloads all manga images""" next_link = start_link counter = 1 # Deal with end link being first page if end_link.endswith('1'): end_link = end_link[:-6] # get title of manga try: title = gen_title(start_link) except: queue.put("Title not found") return while next_link != end_link: # Open initial page page = requests.post(next_link, data=dict(adult="true")) # check if end link is first page redirect if page.url == end_link: break queue.put(page.url) soup = BeautifulSoup(page.text, 'lxml') if not end_link: end_link = soup.find('h1', {"class": "hb dnone"}).find('a').get('href') # Find image link and vol. num try: volume = get_volume(soup) image = soup.find('div', {"class": "inner"}).find('img').get('src') except: queue.put("Could not find image link. Website is not Twisted Hel Scan page?") return # Download the image image = requests.get(image) # Make manga directory if not os.path.exists(title): os.mkdir(title) # Make volume directory if not os.path.exists(title + "/" + volume): os.mkdir(title + "/" + volume) counter = 1 # Write image to file write_image(image, title, volume, counter) counter += 1 # Find next link next_link = soup.find('div', {"class": "inner"}).find('a').get('href') queue.put("Done") def on_click(window): """Fetches text from entries and calls download manga""" start_link = window.start_entry.get() end_link = window.end_entry.get() if not start_link.strip(): queue.put("No start link given") return def callback(): download_manga(start_link, end_link) t = threading.Thread(target=callback) t.start() display.progress.pack(fill='x') display.progress.start(15) def periodic_call(): """ Check every 100 ms if there is something new in the queue. """ display.process_incoming() display.root.after(100, periodic_call) # Create window and bind go button queue = queue.Queue() display = Display(queue) display.go_button.bind("&lt;Button-1&gt;", lambda x: on_click(display)) periodic_call() display.root.mainloop() os._exit(1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T10:10:31.500", "Id": "384951", "Score": "0", "body": "How about `async` instead of `threads`?" } ]
[ { "body": "<p>Welcome to Code Review. That is pretty useful tool. :) From the GitHub link, I notice that you're using Python 3. There are a few things, I think you'd benefit from:</p>\n\n<ol>\n<li>Reorder your <code>import</code>s so that Python's library is imported first, followed by 3rd party modules; follow...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T02:59:21.180", "Id": "199955", "Score": "7", "Tags": [ "python", "web-scraping" ], "Title": "Web scraping and downloading manga" }
199955
<p>I have two lists of <code>Person</code> objects. I need to compare the lists to determine if items in <code>list1</code> exist in <code>list2</code> and vice versa.</p> <p>This is not a straight <code>equals()</code> scenario as the objects are not the same, but may have identical field values. It is those values that I need to compare.</p> <p>Currently, I am using Java 8's <code>Streams</code> API to return either a match or <code>null</code>:</p> <pre><code>import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { ArrayList&lt;Person&gt; originalPeople = new ArrayList&lt;&gt;(); ArrayList&lt;Person&gt; newPeople = new ArrayList&lt;&gt;(); originalPeople.add(new Person("William", "Tyndale")); originalPeople.add(new Person("Jonathan", "Edwards")); originalPeople.add(new Person("Martin", "Luther")); newPeople.add(new Person("Jonathan", "Edwards")); newPeople.add(new Person("James", "Tyndale")); newPeople.add(new Person("Roger", "Moore")); // Create a list of people that no longer exist in the new list for (Person original : originalPeople) { if (getPersonInList( newPeople, original.getFirstName(), original.getLastName()) == null) { System.out.printf("%s %s is not in the new list!%n", original.getFirstName(), original.getLastName()); } } } private static Person getPersonInList( final List&lt;Person&gt; list, final String firstName, final String lastName) { return list.stream() .filter(t -&gt; t.getFirstName().equalsIgnoreCase(firstName)) .filter(t -&gt; t.getLastName().equalsIgnoreCase(lastName)) .findFirst().orElse(null); } } class Person { private final String firstName; private final String lastName; Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } String getFirstName() { return firstName; } public String getLastName() { return lastName; } } </code></pre> <p>In my real-world application, however, both lists have over 30,000 items and this is very time-consuming.</p> <p>Is there a better way to perform this comparison? I would want this to work both ways as well, so if there are items in <code>newPeople</code> that were not in <code>originalPeople</code>, I would want that list as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T07:18:51.623", "Id": "384844", "Score": "0", "body": "Did you try this? https://stackoverflow.com/questions/919387/how-can-i-calculate-the-difference-between-two-arraylists" }, { "ContentLicense": "CC BY-SA 4.0", "Creati...
[ { "body": "<p>There are certain reasons I would not prefer your approach. These are:</p>\n\n<p>1) There are multiple method calls which reduces the readability.</p>\n\n<p>2) You are using filter twice which decreases the performances. You could do it inside the same <code>filter</code> like I've shown below</p>...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T04:02:08.773", "Id": "199957", "Score": "3", "Tags": [ "java", "performance" ], "Title": "Determine if 2 lists with similar objects contain a partial duplicate" }
199957
<p>I want to take the capitalization of one string and apply it to another.</p> <p>For example: take <code>Apple</code> and <code>orange</code> and turn that into <code>Orange</code>.</p> <p>This is the solution I implemented. Is there a more efficient way of doing this?</p> <pre><code>public static String applyCapitalization(String to, String from) { int[] capArray = toCapitalizationArray(to); char[] charCap = from.toCharArray(); for (int i = 0; i &lt; capArray.length; i++) { if (capArray[i] == 1) { charCap[i] = Character.toUpperCase(charCap[i]); } else { charCap[i] = Character.toLowerCase(charCap[i]); } } return new String(charCap); } private static int[] toCapitalizationArray(String to) { int[] arr = new int[to.length()]; for (int i = 0; i &lt; to.length(); i++) { char c = to.toCharArray()[i]; if (Character.isUpperCase(c)) { arr[i] = 1; } else { arr[i] = 0; } } return arr; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T07:10:13.103", "Id": "384843", "Score": "0", "body": "What if both the strings are of different length?" } ]
[ { "body": "<p>We can do this in single traversal rather then two </p>\n\n<pre><code>for (int i = 0; i &lt; min(apple.length(),orange.length()); i++) {\n if (Character.isUpperCase(apple.toCharArray()[i]) &amp;&amp;\n Character.isLowercase(oranger.toCharArray()[i])){\n orange[i] = Character.to...
{ "AcceptedAnswerId": "199963", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T23:57:38.793", "Id": "199958", "Score": "2", "Tags": [ "java", "performance", "strings" ], "Title": "Apply capitalization of one string to another" }
199958
<p>NICK binary thresholding essentially boils down to a convolution where the kernel at each pixel calculates the sum and squared sum (for the standard deviation). These values are then used in the threshold function to determine whether the grayscale value should be black or white.</p> <p>A kernel size of 19x19 is pretty common and rather large to apply on a full HD image, especially if it has to be done in semi-real time video.</p> <p><strong>Optimizations I've done so far</strong></p> <p>The kernel (which is just a bunch of 1's) is a box filter and thus is separable ( M●(h●v) == (M●h)●v ) which reduces the #ops from O(N x M x k²) to O(N x M x (k+k)) but requires additional floating point memory storage to store the intermediate result after the x-pass (M●h).</p> <p>Next I further reduced the #ops by reusing the sum in both x and y passes. The x-pass calculates </p> <p>a <strong>b c d e</strong> f g h</p> <p>a b <strong>c d e f</strong> g h</p> <p>a b c <strong>d e f g</strong> h</p> <p>and so on, which is a lot of overlap. I calculate the sum once at the start of each row and then for each consecutive pixel I subtract the element that falls outside the window and add the element that now falls inside the window:</p> <p>first pixel: sum1 = a+b+c+d</p> <p>second pixel: sum2 = b+c+d+e, which is sum1 -a + e</p> <p>For larger kernels this saves a huge chunks of operations, making it O(M x k + M x (N-1) x 2)) for the x-pass and O(N x k + N x (M-1) x 2) for the y-pass afterwards.</p> <p>I've put in some numbers (N=1920, M = 1080, k = 19) which yields the following:</p> <pre><code>Naive convolution 748569600 Seperable kernels 78796800 Seperable kernels with reuse of sum 8345400 </code></pre> <p>This should be done x2 as it calculates this for both the sum and the squared sum.</p> <p>This works really well on a desktop computer with a lot of memory available, but my android phone struggles, it's easily 50-100x times slower. I suspect it's the additional large allocation of the buffers required to store the x-pass results. If I don't use separable kernels but do reuse the sum the #ops would come to</p> <pre><code>Naive convolution with reuse of sum 79145640 </code></pre> <p>which is again a magnitude of operations higher.</p> <p>I avoided storing the y-pass result and then iterate over the entire image again to use the sum and sum squared values by applying the threshold immediately, which already helped a lot but I was wondering if there are other approaches to further optimize the algorithm.</p> <p><strong>Typescript code</strong></p> <pre><code>function binaryThresholdNICK(grayscale: Uint8Array, width: number, height: number, wndSize: number, k: number) { // keep track of the sum and squared sum of the sliding window // this implementation is using a separable kernel so it's divided into // an x-pass which just sums up the row in the window followed by an y-pass // which takes these partial sums and sums them in the y direction let piSumXPass: Float32Array = new Float32Array(width * height); let piSquaredSumXPass: Float32Array = new Float32Array(width * height); let halfWndSize = Math.floor(wndSize / 2); // doing x-pass and then y-pass is different if the values around the border // are taken in account, because x-pass is only done with padding and yet y-pass // would take the 0 values from x-pass, compared doing it in 1 go would use the values // of the border directly, so removing the border ensures the values are the same as the // original slow method without separating the kernels. removeBorder(halfWndSize, grayscale, width, height); let NP = wndSize * wndSize; // keep track of index based on padding let padding = halfWndSize; let idx = padding * width + padding; for (let y: number = padding; y &lt; height - padding; y++) { // instead of calculating the sum of the entire row within the window // it can be done more efficiently by only calculating the sum for the first // window and then with each shift of the window to the right subtract the element // that falls out of the window and add the element that now falls inside the window // for large kernels this means only k + 2 * width operations instead of k * width ops let sum = 0; let sumSquared = 0; for (let wnd: number = -halfWndSize; wnd &lt;= halfWndSize; wnd++) { let val = grayscale[idx + wnd]; sum += val sumSquared += val * val; } piSumXPass[idx] = sum; piSquaredSumXPass[idx] = sumSquared; idx++; for (let x: number = padding + 1; x &lt; width - padding; x++) { let remVal = grayscale[idx - 1 - halfWndSize]; let addVal = grayscale[idx + halfWndSize]; // remove the element that falls out of the range sum -= remVal; // and add the element that enters the range sum += addVal; // remove the element that falls out of the range sumSquared -= remVal * remVal; // and add the element that enters the range sumSquared += addVal * addVal; piSumXPass[idx] = sum; piSquaredSumXPass[idx] = sumSquared; idx++; } idx += 2 * padding; } // now do the y-pass &amp; immediately use the result at pixel (x,y) to determine // the threshold. It follows the same scheme as the x-pass but differs in index // calculation because it's vertical for (let x: number = padding; x &lt; width - padding; x++) { idx = x + padding * width; let sum = 0; let sumSquared = 0; for (let wnd: number = -halfWndSize; wnd &lt;= halfWndSize; wnd++) { let cidx = idx + wnd * width; sum += piSumXPass[cidx]; sumSquared += piSquaredSumXPass[cidx] } // calculate and apply the threshold at pixel { let m = sum / NP; let A = (sumSquared - (m * m)) / NP; let T = m + k * Math.sqrt(A); if (grayscale[idx] &gt;= T) grayscale[idx] = 255; } idx += width; let wEdge = halfWndSize * width; for (let y: number = padding + 1; y &lt; height - padding; y++) { let cidx = idx - width - wEdge; sum -= piSumXPass[cidx]; sumSquared -= piSquaredSumXPass[cidx]; cidx = idx + wEdge; sum += piSumXPass[cidx]; sumSquared += piSquaredSumXPass[cidx]; // now calculate and apply the threshold at each pixel { let m = sum / NP; let A = (sumSquared - (m * m)) / NP; let T = m + k * Math.sqrt(A); if (grayscale[idx] &gt;= T) grayscale[idx] = 255; } idx += width; } } } </code></pre> <p><strong>EDIT:</strong></p> <p>I've implemented a BufferManager pool where each step can request a buffer of specified length and then release it back to the pool. The pool keeps the buffers in memory and by ensuring the buffer sizes remain constant (= the input feed, even though that much space isn't always necessary) the same buffers get reused over and over again. This all but eliminated the huge spikes I would get due to garbage collection. I'm getting a relatively stable processing time now of around 250ms in chrome for a 1920x1080 video feed. If anyone else has some other suggestions that I can try, feel free. I haven't looked into webgl yet, but I think the overhead of transferring the images as textures would already make it not worth it</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T08:31:48.810", "Id": "199965", "Score": "3", "Tags": [ "algorithm", "typescript" ], "Title": "Optimizing NICK binary thresholding" }
199965
<p>I have written a class to quantize values to arbitrary bit depths within a specified amplitude. It is meant to process one value at a time, and has two ways of quantizing values.</p> <p>I wrote the class so that i could create objects of it as a property for another class, so that the quantization process can easily be included into other, more complex operations. This class I wrote, however, has some things I am quite sure about whether they were solved optimally.</p> <p>My Header file, <code>Quantizer.h</code>, looks like this:</p> <pre><code>#pragma once #include &lt;cmath&gt; class CQuantizer { public: ~CQuantizer(); enum qType { lin_midrise, lin_midtread, numberOfTypes }; CQuantizer(CQuantizer::qType type = CQuantizer::lin_midtread, int nBits=4, float amplitude = 1.f); float processOneSample(float in); void setNBits(int bits); void setAmplitude(float amplitude); void setType(CQuantizer::qType type); private: int m_nBits; float m_amplitude; CQuantizer::qType m_type; float processOneSampleLinMidtread(float in); float processOneSampleLinMidrise(float in); float (CQuantizer::*processSampleFunc)(float); }; </code></pre> <p>The first thing I am wondering about is the enum I used for the types: is it a good idea to include <code>numberOfTypes</code> as last element for later loops through the enum etc.?</p> <p>Also, I saw somewhere else for a similar class that as some kind of switch, function pointers were used, which I did for the <code>processOneSample</code>-method. In this scenario, is it appropriate to do so?</p> <p>Also, below I've included my implementation:</p> <pre><code>#include "Quantizer.h" CQuantizer::~CQuantizer() { } CQuantizer::CQuantizer(CQuantizer::qType type, int nBits, float amplitude) { setType(type); setNBits(nBits); setAmplitude(amplitude); } float CQuantizer::processOneSample(float in) { if (m_amplitude == 0.f) { // watch out for zero-amplitude return 0.f; }else{ // use function specified by type return (this-&gt;*processSampleFunc)(in); } } void CQuantizer::setNBits(int bits) { m_nBits = bits; } void CQuantizer::setAmplitude(float amplitude) { m_amplitude = amplitude; } void CQuantizer::setType(CQuantizer::qType type) { m_type = type; switch (m_type) { case CQuantizer::lin_midtread: processSampleFunc = &amp;CQuantizer::processOneSampleLinMidtread; break; case CQuantizer::lin_midrise: processSampleFunc = &amp;CQuantizer::processOneSampleLinMidrise; break; } } float CQuantizer::processOneSampleLinMidtread(float in) { // upscaling float out = std::roundf( (in / m_amplitude) * powf(2.f, m_nBits - 1.f)); // check for upper boundary if (out &gt; powf(2.f, m_nBits - 1.f) - 1.f) { out = powf(2.f, m_nBits - 1.f) - 1.f; } // check for lower boundary if (out &lt; -powf(2.f, m_nBits - 1.f)) { out = -powf(2.f, m_nBits - 1.f); } // downscaling return m_amplitude * out / powf(2.f, m_nBits - 1.f); } float CQuantizer::processOneSampleLinMidrise(float in) { // upscaling float out = std::round((in / m_amplitude) * powf(2.f, m_nBits - 1.f) + 0.5f) - 0.5f; // check for upper boundary if (out &gt; powf(2.f, m_nBits - 1.f) - 0.5f) { out = powf(2.f, m_nBits - 1.f) - 0.5f; } // check for lower boundary if (out &lt; -powf(2.f, m_nBits - 1.f) + 0.5f) { out = -powf(2.f, m_nBits - 1.f) + 0.5f; } //downscaling return m_amplitude * out / powf(2.f, m_nBits - 1.f); } </code></pre> <p>In my processing methods, i feel like there is too much going on: is there a smarter way for me to round these values and ensure they are within a set range?</p> <p>(The effect I'd like to achieve with this class is that for a given amplitude, there can only be \$2^{\text{nBits}}\$ possible output values within a certain range.)</p>
[]
[ { "body": "<ul>\n<li><p><code>powf(2.f, m_nBits - 1.f)</code> should be a class member, to be computed in <code>setNBits</code>.</p></li>\n<li><p>Test for <code>m_amplitude == 0.f</code> also feels as belonging to <code>setAmplitude</code>. This of course requires raising an exception (since it is used in a con...
{ "AcceptedAnswerId": "200010", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T09:43:48.500", "Id": "199970", "Score": "5", "Tags": [ "c++", "object-oriented", "signal-processing" ], "Title": "DSP-Quantizer class in C++" }
199970
<p>I wrote code to extract the contour of a hole, based mostly on the <a href="http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/moore.html" rel="nofollow noreferrer">Moore-Neighbor Tracing algorithm</a>. Only </p> <p>a. instead of finding a shape, I'm finding a "hole"; and, </p> <p>b. I'm looking for the (outer) boundary of the hole, i.e. the actual pixels that are not part of the hole but that are hole boundary.</p> <pre><code>public class MooreTrace : ITraceAlgorithm { public List&lt;Pixel&gt; Trace(Image img) { Pixel hole_pixel; for (int i = 0; i &lt; img.LenX; i++) for (int j = 0; j &lt; img.LenY; j++) { hole_pixel = img.GetArrayElement(i, j); if (hole_pixel.Value == -1) // while goto statements are not highly approved of, as they create hard-to-read spaghetti code, // this (breaking out of nested loops) is one of the rare cases where they should be used, // as they are more coherent than setting up multiple flags, or using sub-methods that will return. goto Hole_Exists; } // if here - no hole was found, simply return null return null; Hole_Exists: // What if hole is in (x,0) ? if (hole_pixel.Yi == 0) { var next_pixel = GetNextPixel(hole_pixel, img); while (next_pixel.Value == -1) { hole_pixel = next_pixel; next_pixel = GetNextPixel(hole_pixel, img); } _start = 4; } else _start = 0; _8i = _start; var Boundary = new List&lt;Pixel&gt;(); // priming the loop var first = GetClockWisePixel(hole_pixel, img); Boundary.Add(first); var boundary_pixel = GetClockWisePixel(hole_pixel, img); // stop condition: // A. reach the same first pixel we started from // B. in cases of enclaves with 1 space gap, this might cause a premature stop // we can make sure we are reaching it while completeing the full circle of the circle-wise turning // i.e. that the turning index (_8i) == 0 (minus the extra step that is taken) // (also called Jacob's stopping criteria) while (!(boundary_pixel == first &amp;&amp; _8i - 1 == _start)) { if (boundary_pixel.Value != -1) { if (!Boundary.Contains(boundary_pixel)) Boundary.Add(boundary_pixel); } else { Backtrack(); hole_pixel = boundary_pixel; } boundary_pixel = GetClockWisePixel(hole_pixel, img); } return Boundary; } // +---+---+---+ // | 1 | 2 | 3 | // |nw | n |ne | // +---+---+---+ // | 0 | | 4 | // | w | | e | // +---+---+---+ // | 7 | 6 | 5 | // |sw | s |se | // +---+---+---+ private int[,] _8connected = new int[,] { {0, -1}, // 0 = w {-1, -1}, // 1 = nw {-1, 0}, // 2 = n {-1, 1}, // 3 = ne {0, 1}, // 4 = e {1, 1}, // 5 = se {1, 0}, // 6 = s {1, -1}, // 7 = sw }; private int _start; private int _8i; // index to keep where are we in the clock-wise clock // 0 - w, 1 - nw, 2 - n, 3 - ne, 4 - e, 5 - se, 6 - s, 7 - sw private Pixel GetClockWisePixel(Pixel input, Image img) { int new_x, new_y; do { var x_offset = _8connected[_8i, 0]; var y_offset = _8connected[_8i, 1]; _8i = (_8i + 1) % 8; new_x = input.Xi + x_offset; new_y = input.Yi + y_offset; } // if edge pixels, move to next clockwise while (new_x &lt; 0 || new_x &gt;= img.LenX || new_y &lt; 0 || new_y &gt;= img.LenY); return img.GetArrayElement(new_x, new_y); } private void Backtrack() { // We want to go back to the last connected pixel we were in. // The return position might seem at first a bit redundant, as it returns us to a pixel already covered // it's crucial for the stop condition in certain cases... If we wouldn't mind missing enclaves // we could return one less to the next connected pixel not yet covered, and remove Jacob's stopping criteria... // There can be 2 cases where a new hole pixel was found in: // diagonal - we will want to go counter clock 3 (+1 of the already advanced _8i) = -4 = +4 // _8i index will be +1, i.e. 2,4,6 or 0 // straight - we will want to go counter clock 2 (+1 of the already advanced _8i) = -3 = +5 // _8i index will be +1, i.e. 1,3,5 or 7 if (_8i % 2 == 1) _8i = (_8i + 5) % 8; else _8i = (_8i + 4) % 8; } private Pixel GetNextPixel(Pixel input, IImageMatrix img) { if (input.Yi + 1 &lt; img.LenY) { return img.GetArrayElement(input.Xi, input.Yi + 1); } else if (input.Xi + 1 &lt; img.LenX) { return img.GetArrayElement(input.Xi + 1, 0); } else return null; } } </code></pre> <p>Would be really happy to get 2 things:</p> <ol> <li>Code Review - how to make it better, more clear, more simple, etc.</li> <li><p>Understand the complexity of it. According to my calculations the tracing algorithm complexity is somewhere between \$O(\sqrt n)\$ to \$O(n)\$, where \$n\$ is the number of hole-pixels. The logic is as follows: </p> <ul> <li><p>Finding the initial hole-position is determined by the image size, for a \$K \times L\$ pixels it will take on average \$\frac{K L - N}{2}\$, which is in the magnitude of \$O(K L)\$; Should I ignore this part?</p></li> <li><p>In the best case, the shape is a perfect square. The tracing algo. will be around \$12\sqrt n\$ (\$\sqrt n\$ for each side, times 4 sides, times 3 for the algorithm redundancy - i.e. if we go right and down and find a hole pixel, we will now have to go up, right and down - just to get to the next hole - that's 3 steps). This is the same as \$O(\sqrt n)\$.</p></li> <li><p>In the worst case, the shape is a perfect diagonal. Tracing algo. will be around \$8n\$ which is same as \$O(n)\$. This is because we will traverse the diagonal from two of its sides (x2) and for ~all hole pixels we will require 4 steps to move from one hole-pixel to another. </p></li> </ul></li> </ol> <p>So which one is it? </p> <hr> <p>You can check out (download and test) the entire project on <a href="https://github.com/DavidMeerkatRefaeli/HoleFilling/tree/7ae3e7b103a09857cf14b8640dbd9efa8266ba5c" rel="nofollow noreferrer">github</a>.</p> <p>Hole in image:</p> <p><a href="https://i.stack.imgur.com/HolVv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HolVv.png" alt="Hole in image"></a></p> <p>Fixed with weighted average function:</p> <p><a href="https://i.stack.imgur.com/kizUS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kizUS.png" alt="Fixed with weighted average function"></a></p> <p>Fixed with regular average function:</p> <p><a href="https://i.stack.imgur.com/EGidN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EGidN.png" alt="Fixed with regular average function"></a></p> <p>Fixed with gradient average function:</p> <p><a href="https://i.stack.imgur.com/eFYRt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eFYRt.png" alt="Fixed with gradient average function "></a></p> <p>Fixed with spiral 8-connected function:</p> <p><a href="https://i.stack.imgur.com/YnHmR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YnHmR.png" alt="Fixed with spiral 8-connected function"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T11:34:29.783", "Id": "385249", "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": "<p>I can't agree with the comments about goto and using sub methods. </p>\n\n<blockquote>\n<pre><code>Pixel hole_pixel;\nfor (int i = 0; i &lt; img.LenX; i++)\n for (int j = 0; j &lt; img.LenY; j++)\n {\n hole_pixel = img.GetArrayElement(i, j);\n if (hole_pixel.Value == -1)\n ...
{ "AcceptedAnswerId": "200171", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T10:00:35.673", "Id": "199971", "Score": "6", "Tags": [ "c#", "algorithm", "image", "complexity" ], "Title": "Moore-Neighbor Tracing Algorithm" }
199971
<p>I'm totally new to python and coding in general and I tried for my first project to recreate Conway's game of life. After days of trial and error, I came up with this code: </p> <pre><code>import numpy as np import copy import png import PIL as PIL def a(a) : if a == "gen" : size=int(input("size ? ")) ratio=float(input("ratio ? ")) name=input("file name: ") matrix=np.random.choice(2,(size,size),p=[1-ratio,ratio]) i = png.from_array(matrix, mode='L;1') i.save(str(name)+'.JPEG') if a == "start" : name=input("file name: ") time=input('number of rounds: ') matrix=np.asarray(PIL.Image.open(str(name)+'.jpeg')).astype(int) matrix2=copy.deepcopy(matrix) taille1,taille2=matrix.shape counter=0 while counter&lt;int(time): for x in range(0,taille1-1): for y in range(0,taille2-1): if matrix[x,y]==0 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]==3: matrix2[x,y]=1 if matrix[x,y]==1 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]&lt;2: matrix2[x,y]=0 if matrix[x,y]==1 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]&gt;3: matrix2[x,y]=0 i = png.from_array(matrix2, mode='L;1') i.save(str(name)+'_output_'+str(counter+1)+'.JPEG') matrix=copy.deepcopy(matrix2) counter+=1 task=input("command : ") a(task) </code></pre> <p>It works really fine but I'm afraid it is quite unefficient, so I'd like to hear advice on how to make it faster (especially the triple loop)</p>
[]
[ { "body": "<p>First of all, please try to reformat the Python code according to Python's style guide (<a href=\"https://www.python.org/dev/peps/pep-0008/?\" rel=\"nofollow noreferrer\">PEP 8</a>).</p>\n\n<p>When programming, it is important to give meaningful names to all variables (with exception to some loop ...
{ "AcceptedAnswerId": "199986", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T10:46:34.203", "Id": "199974", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x", "game-of-life" ], "Title": "A beginners implementation of Game of Life" }
199974
<p>You are given two binary search trees, the goal is produce a sorted array of elements containing elements from both the trees. </p> <p>I wanted to know if there is a simpler approach, and if the use of boost variant is justified in the code. The code uses a stack to iterate over the binary search tree. The stack maintains the state for pre-order traversal of the tree. </p> <pre><code>#include &lt;iostream&gt; #include &lt;stack&gt; #include &lt;boost/range/irange.hpp&gt; #include &lt;boost/variant.hpp&gt; #include &lt;random&gt; #include &lt;algorithm&gt; using namespace std; using boost::irange; using boost::variant; struct Node { Node(Node* l, Node* r, int v):left(l), right(r), val(v) { } Node* left; Node* right; int val; }; typedef variant&lt;Node*, int&gt; stkElemT; typedef stack&lt;stkElemT&gt; bstStkT; //from variant extract the pointer if valid otherwise NULL struct stkElemVisitorNode : public boost::static_visitor&lt;Node*&gt; { Node* operator()(const int&amp; val) const { return NULL; } Node* operator()(Node*&amp; ptr) const { return ptr; } }; //from variant extract the integer value if valid otherwise -1 struct stkElemVisitorInt : public boost::static_visitor&lt;int&gt; { int operator()(const int&amp; val) const { return val; } int operator()(Node*&amp; ptr) const { return -1; } }; //expand left most path of top node. void fillPathStkRecurse(bstStkT&amp; bstStk) { stkElemT topE = bstStk.top(); Node* topN = boost::apply_visitor(stkElemVisitorNode(), topE); if(topN != NULL) // { bstStk.pop(); if (topN-&gt;right) bstStk.push(topN-&gt;right); bstStk.push(topN-&gt;val); if (topN-&gt;left) { bstStk.push(topN-&gt;left); } fillPathStkRecurse(bstStk); } else{ return; //top node is not a pointer but value } } int getTopVal(const bstStkT&amp; bstStk) { assert(!bstStk.empty()); stkElemT topE = bstStk.top(); int val = boost::apply_visitor(stkElemVisitorInt(), topE); return val; } void incrBstStk(bstStkT&amp; bstStk) { if(bstStk.empty()) return; int topVal = getTopVal(bstStk); assert(topVal != -1); bstStk.pop(); if(!bstStk.empty()) fillPathStkRecurse(bstStk); //expand till child node return; } Node* create_tree(vector&lt;int&gt;&amp; vals, int start, int end) //end excluded { if(end==start) return new Node(NULL, NULL, vals[start]); if(end == start + 1) { Node* curr = new Node(NULL, NULL, vals[start]); curr-&gt;right = new Node(NULL, NULL, vals[start+1]); return curr; } int mid = floor((start + end)/2.0); Node* left = create_tree(vals, start, mid-1); Node* right = create_tree(vals, mid+1, end); Node* curr = new Node(left, right, vals[mid]); return curr; } vector&lt;int&gt; merge_bst(Node* root1, Node* root2) { vector&lt;int&gt; res; bstStkT bstStk1; bstStk1.push(root1); fillPathStkRecurse(bstStk1); bstStkT bstStk2; bstStk2.push(root2); fillPathStkRecurse(bstStk2); while(1) { //cout&lt;&lt;"stk sizes = "&lt;&lt;bstStk1.size()&lt;&lt;" "&lt;&lt;bstStk2.size()&lt;&lt;endl; if(bstStk1.empty() &amp;&amp; bstStk2.empty()) break; int val1 = numeric_limits&lt;int&gt;::max(); if(!bstStk1.empty()) val1 = getTopVal(bstStk1); int val2 = numeric_limits&lt;int&gt;::max(); if(!bstStk2.empty()) val2 = getTopVal(bstStk2); if(val1 &lt; val2)//consume bstStk1 { res.push_back(val1); incrBstStk(bstStk1); } else { res.push_back(val2); incrBstStk(bstStk2); } } return res; } int main(int argc, char** argv) { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution&lt;std::mt19937::result_type&gt; uid5k(0, 1000); // distribution in range [1, 6] int n = 10000; for(auto k: irange(0, 10000)) { vector&lt;int&gt; inVec1; for(auto i: irange(0, n)) inVec1.push_back(uid5k(rng)); sort(inVec1.begin(), inVec1.end()); Node* root1 = create_tree(inVec1, 0, n-1); vector&lt;int&gt; inVec2; for(auto i: irange(0, n)) inVec2.push_back(uid5k(rng)); sort(inVec2.begin(), inVec2.end()); Node* root2 = create_tree(inVec2, 0, n-1); vector&lt;int&gt; merged_vec(inVec1.begin(), inVec1.end()); merged_vec.insert(end(merged_vec), begin(inVec2), end(inVec2)); sort(begin(merged_vec), end(merged_vec)); auto res = merge_bst(root1, root2); assert(res == merged_vec); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T14:01:59.810", "Id": "384891", "Score": "2", "body": "Take a look at lines 90 to 93. This is a great example why you should *never* omit braces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T14:25:4...
[ { "body": "<h2>Design</h2>\n\n<p>If you are going to do this the C++ way then you should be using standard algorithms. A tree is a type of container; so you should be able to get an iterator to logically pass over each element in the container.</p>\n\n<p>As a result I would expect the code to look like this:</p...
{ "AcceptedAnswerId": "200148", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T11:41:59.763", "Id": "199981", "Score": "0", "Tags": [ "c++", "tree", "variant-type" ], "Title": "create sorted vector of content of two binary search trees in sorted order" }
199981
<p>I'm preparing for an interview doing the preparation questions on Hacker Rank and I want to become better at this. Is it possible to get some feedback on this? How can I improve my code? How did you solve this question?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getCount(array){ let counts = {} for(let word of array){ let count = counts[word] counts[word] = count ? counts[word] + 1: 1; } return counts } // Complete the checkMagazine function below. function compareNoteMag(note,mag){ let noteKeys = Object.keys(note) let string = 'Yes' for(let key of noteKeys){ if(!mag[key]) string = 'No' if(mag[key] &lt; note[key]){ string = 'No' } } console.log(string) } function checkMagazine(magazine, note) { let magazineCount = getCount(magazine); let noteCount = getCount(note); compareNoteMag(noteCount,magazineCount) };</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T16:24:31.150", "Id": "384978", "Score": "2", "body": "Welcome to Code Review. Please describe the problem being solved, and add a link to it if possible." } ]
[ { "body": "<h3>Performance</h3>\n\n<p>There are several performance issues in the posted code:</p>\n\n<ol>\n<li>The loop over <code>noteKeys</code> continues even after it knows that a word is missing. It should stop.</li>\n<li>The map of counts of words in the magazine is unnecessary internal storage. A likely...
{ "AcceptedAnswerId": "200039", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T14:14:19.147", "Id": "199989", "Score": "2", "Tags": [ "javascript", "programming-challenge" ], "Title": "Hash Tables: Ransom Note - Hacker Rank in Javascript" }
199989
<p>I like to collect images for my desktop background, the problem is sometimes the image names don't represent what the image is. I decided to write a script that reads a text file that contains the source of the images to be renamed, and the base name. The script renames the images using the base name and increment counter and moves it to a portable drive.</p> <p><strong>Picture Database:</strong> </p> <pre><code>Pictures\Landscape,landscape Pictures\Batman,batman </code></pre> <p><strong>Script:</strong></p> <pre><code>$picture_database_location = "$PSScriptRoot\pictures_database.txt" $filter_ext = "jpg" $rootDestination = "R:" function determineIfFileorDirectoryExists { Param([string]$fileordirectory) &lt;# Determine if a File or Directory Exists. If the file or directory doesn't exists, it will throw an exception. Args: string: $fileordirectory - the variable that contains the file or directory we're going to Test. Returns: None #&gt; $fileordirectoryExists = Test-Path $fileordirectory if($fileordirectoryExists -eq $false){ throw [System.IO.DirectoryNotFoundException] "Not Found: $fileordirectory" } } function determineargumentCount { Param([string[]]$arraytoverify) &lt;# Determines if the array length is correct. If not, it will throw and display the elements in the array. Args: string[]: $arraytoverify - the array to check for length. Return: None #&gt; if ($arraytoverify.Length -ne 2){ throw "Argument count incorrect. # of Parameters: $arraytoverify.Length. `nProvided Parameters: $arraytoverify" } } try{ # Before renaming any images we need to verify that the source location and destination exist. determineIfFileorDirectoryExists -fileordirectory "$picture_database_location" determineIfFileorDirectoryExists -fileordirectory "$rootDestination" $picture_database = Get-Content $picture_database_location ForEach ($image in $picture_database){ # Construct an array based on the split string # $imagaeArray is constructed as follows: # $imageArray[0]: The directory that contains the images to rename # $imageArray[1]: The base name to rename the images $imageArray = $image.Split(",") determineargumentCount -arraytoverify $imageArray # Construct the Source path with USERPROFILE environment variable and the first element in the array (the directory that contains our pictures) $imagePath = Join-Path $env:USERPROFILE -ChildPath $imageArray[0] determineIfFileorDirectoryExists -fileordirectory "$imagePath" Set-Location -Path "$imagePath" # Filter images by type and bulid a list with all the image names $fileList = (Get-ChildItem $imagePath -Filter "*.jpg").Name if($fileList.Length -gt 0){ # Construct a string representing the desination path $DestinationPath = Join-Path $rootDestination -ChildPath $imageArray[0] $doesDirectoryExist = Test-Path $DestinationPath if($doesDirectoryExist -eq $false){ # - ErrorAction Stop - stops the script if the action take fails. md "$DestinationPath" -ErrorAction Stop determineIfFileorDirectoryExists -fileordirectory "$DestinationPath" } # Get the number of pictures in the destionation and set the counter. [int]$fileCounter = (Get-ChildItem $DestinationPath -Filter "*.jpg").Length ForEach ($imagetoRename in $fileList){ $fileCounter++ $renamed_file = "{0}_{1}.{2}" -f $imageArray[1],$fileCounter,$filter_ext $imageDestination = Join-Path $DestinationPath -ChildPath $renamed_file Write-Output "Image : {0} will be renamed to {1}" -f $imagetoRename, $imageDestination Move-Item -Path "$imagetoRename" -Destination "$imageDestination" } } } Set-Location $PSScriptRoot } catch [System.IO.DirectoryNotFoundException] { Write-Output $PSItem.Exception.Message } catch [System.IO.IOException] { Write-Output $PSItem.Exception.Message } catch{ Write-Output $PSItem.Exception.Message } finally{ exit } </code></pre> <p>Suppose there were two images in each of the source folders, it will rename them like this:</p> <pre><code>landscape_1.jpg landscape_2.jpg batman_1.jpg batman_2.jpg </code></pre> <p><strong>Areas of Concern:</strong></p> <ul> <li>I use the variable <code>$imageArray</code> but I'm thinking simple classes might make it more readable instead of a bulky comment.</li> <li>I'm aware a nested <code>for</code> loop isn't good for performance, but I'm unsure how to rewrite the code.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T15:33:51.190", "Id": "384904", "Score": "0", "body": "Nice first question. I hope you get good answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-25T00:22:38.790", "Id": "385400", "Score": ...
[ { "body": "<p>The name Picture Database is not quite correct, as it is a Picture Location Database. </p>\n\n<p><strong>I</strong> would use a csv to store the elements and use <code>Import-Csv</code> to read data in. </p>\n\n<p>I have a small problem with the assumption that the <code>Picture</code> folder is...
{ "AcceptedAnswerId": "200007", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T15:30:46.683", "Id": "199992", "Score": "4", "Tags": [ "powershell" ], "Title": "Rename jpg images using a script" }
199992
<p>I have a following exercise from ANSI C book:</p> <blockquote> <p>Exercise 6.1. Our version of getword does not properly handle underscores, string constants, comments, or preprocessor control lines. Write a better version.</p> </blockquote> <p>Here's my improved version of getword function and code that test if it works:</p> <pre><code>#include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define BUFSIZE 100 #define MAXWORD 100 #define NKEYS (sizeof keytab / sizeof(keytab[0])) int buf[BUFSIZE]; int bufp = 0; struct key { char * word; int count; } keytab[] = { { "#define", 0 }, { "#elif", 0 }, { "#else", 0 }, { "#endif", 0 }, { "#error", 0 }, { "#if", 0 }, { "#ifdef", 0 }, { "#ifndef", 0 }, { "#include", 0 }, { "#line", 0 }, { "#pragma", 0 }, { "auto", 0 }, { "break", 0 }, { "case", 0 }, { "char", 0 }, { "const", 0 }, { "continue", 0 }, { "default", 0 }, { "do", 0 }, { "double", 0 }, { "else", 0 }, { "enum", 0 }, { "extern", 0 }, { "float", 0 }, { "for", 0 }, { "goto", 0 }, { "if", 0 }, { "int", 0 }, { "long", 0 }, { "register", 0 }, { "return", 0 }, { "short", 0 }, { "signed", 0 }, { "sizeof", 0 }, { "static", 0 }, { "struct", 0 }, { "switch", 0 }, { "typedef", 0 }, { "union", 0 }, { "unsigned", 0 }, { "void", 0 }, { "volatile", 0 }, { "while", 0 }, }; int getword(char *, int); int binsearch(char *, struct key *, int); int getch(void); void ungetch(int); int main(void) { int n, c; char word[MAXWORD]; while ((c = getword(word, MAXWORD)) != EOF) { // printf("getword(word, MAXWORD) = %c %d\n", c, c); // printf("word = %s\n", word); if (isalpha(word[0]) || word[0] == '_' || word[0] == '#') { if ((n = binsearch(word, keytab, NKEYS)) &gt;= 0) { keytab[n].count++; } } } for (n = 0; n &lt; NKEYS; n++) if (keytab[n].count &gt; 0) printf("%4d %s\n", keytab[n].count, keytab[n].word); return 0; } int getch(void) { return (bufp &gt; 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { if (bufp &gt;= BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; } int getword(char * word, int lim) { int c; char * w = word; static int last; while (isblank(c = getch())) ; if (c != EOF) *w++ = c; if (last == '/' &amp;&amp; c == '/') { while (c = getch() != '\n') ; return c; } if (last == '/' &amp;&amp; c == '*') { x: while (c = getch() != '*') ; if (c = getch() == '/') return c; else goto x; } if (c == '\'') { while (c = getch() != '\'') ; return c; } if (c == '\"') { while (c = getch() != '\"') ; return c; } if (!isalpha(c) &amp;&amp; c != '_' &amp;&amp; c != '#') { *w = '\0'; last = c; return c; } for ( ; --lim &gt; 0; w++) { if (!isalnum(*w = getch()) &amp;&amp; *w != '_') { ungetch(*w); break; } } *w = '\0'; last = word[0]; return word[0]; } int binsearch(char * word, struct key tab[], int n) { int cond; int low, high, mid; low = 0; high = n - 1; while (low &lt;= high) { mid = (low + high) / 2; if ((cond = strcmp(word, tab[mid].word)) &lt; 0) high = mid - 1; else if (cond &gt; 0) low = mid + 1; else return mid; } return -1; } </code></pre> <p>What are your opinions about my solution? Is it a correct approach? Is this code enough fast?</p>
[]
[ { "body": "<ul>\n<li><p>The <code>last</code> logic is quite hard to trace, and it is prone to bugs. Consider <code>/* ... */*</code>. Once the code reached the closing <code>/</code>, it returns, but <code>last</code> is not updated, and remains <code>/</code>, so the next <code>*</code> is still treated as a ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T16:01:12.420", "Id": "199994", "Score": "1", "Tags": [ "c", "binary-search" ], "Title": "Exercise 6.1 from ANSI C book - getword function" }
199994
<p>I stumbled upon this problem on cses.fi (a problem set for the Finnish Olympiad in Informatics. This problem is in finnish so I'll translate it). I'll describe the problem, present the code and think what went wrong.</p> <blockquote> <p><strong>The problem</strong></p> <p>You are given a blueprint of a house. The size of the blueprint is \$n * m\$ and each square is either a wall (#) or the floor (.).<br> Calculate the number of rooms in the house.</p> <p><strong>Input</strong></p> <p>On the first row there are two integers: \$n\$ and \$m\$. On the \$n\$ following lines are \$m\$ characters (# or .)</p> <p><strong>Output</strong></p> <p>Print the number of rooms in the house.</p> <p><strong>Limits</strong></p> <p>\$1 &lt; n, m &lt; 1000\$</p> <p><strong>Example</strong></p> <p><em>Input:</em></p> <p><a href="https://i.stack.imgur.com/klGsR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/klGsR.png" alt=""></a></p> <p><em>Output:</em></p> <p>3</p> </blockquote> <p><strong>My idea, pseudocode</strong></p> <p><em>Step 1:</em></p> <p>Loop through the 2D array I've created. Let count = 0. </p> <p><em>Step 2:</em></p> <p>If the char is '.', search the squares on its left, right, top and bottom. If those squares are '.', add them to the list visit and mark them in the 2D array with count. Go through visit and do step 2 for each element.</p> <p><em>Step 3:</em></p> <p>When visit is traversed through, one room is ready. Let's increment count and empty visit. Continue step 1.</p> <p><strong>My c++ code</strong></p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { int numberofrows; int rowlength; vector&lt;vector&lt;char&gt;&gt; house; cin &gt;&gt; numberofrows &gt;&gt; rowlength; for (int i = 0; i &lt; numberofrows; i++) { vector&lt;char&gt; add; house.push_back(add); for (int k = 0; k &lt; rowlength; k++) { char mychar; cin &gt;&gt; mychar; house.back().push_back(mychar); } } int counter = 0; for (int row = 0; row &lt; numberofrows; row++) { for (int column = 0; column &lt; rowlength; column++) { if (house[row][column] != '.') { continue; } vector&lt;vector&lt;int&gt;&gt; visit = {}; house[row][column] = (char)counter; if (row != 0 &amp;&amp; house[row - 1][column] == '.') { house[row - 1][column] = (char)counter; visit.push_back({ row - 1, column }); } if (row != numberofrows - 1 &amp;&amp; house[row + 1][column] == '.') { house[row + 1][column] = (char)counter; visit.push_back({ row + 1, column }); } if (column != 0 &amp;&amp; house[row][column - 1] == '.') { house[row][column - 1] = (char)counter; visit.push_back({ row, column - 1 }); } if (column != rowlength - 1 &amp;&amp; house[row][column + 1] == '.') { house[row][column + 1] = (char)counter; visit.push_back({ row, column + 1 }); } for (int i = 0; i &lt; (int)visit.size(); i++) { if (visit[i][0] != numberofrows - 1 &amp;&amp; house[visit[i][0] + 1][visit[i][1]] == '.') { //Add the square down from the current square house[visit[i][0] + 1][visit[i][1]] = (char)counter; visit.push_back({ visit[i][0] + 1, visit[i][1] }); } if (visit[i][0] != 0 &amp;&amp; house[visit[i][0] - 1][visit[i][1]] == '.') { //Add the square on top of the current square to visit house[visit[i][0] - 1][visit[i][1]] = (char)counter; visit.push_back({ visit[i][0] - 1, visit[i][1] }); } if (visit[i][1] != rowlength - 1 &amp;&amp; house[visit[i][0]][visit[i][1] + 1] == '.') { //Add the square on the right of the current square to visit house[visit[i][0]][visit[i][1] + 1] = (char)counter; visit.push_back({ visit[i][0], visit[i][1] + 1 }); } if (visit[i][1] != 0 &amp;&amp; house[visit[i][0]][visit[i][1] - 1] == '.') { //Add the square on the left of the current square to visit house[visit[i][0]][visit[i][1] - 1] = (char)counter; visit.push_back({ visit[i][0], visit[i][1] - 1 }); } } counter += 1; } } cout &lt;&lt; counter; return 0; } </code></pre> <p><strong>The problems with my code</strong></p> <p>With the 1000*1000 house, my code sometimes throws a runtime error. I suspect it might be MemoryError as the memory limit is 128 MB. The vector visit might be getting too big. All other improvements are welcome, too! Don't be too harsh as I'm just learning C++.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T20:06:47.850", "Id": "384909", "Score": "0", "body": "Does that work at all if there are more than 255 rooms?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T20:08:34.560", "Id": "384910", "Sc...
[ { "body": "<h3>General remarks</h3>\n\n<p>Don't use <code>namespace std;</code>, see for example <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a>.</p>\n\n<p><code>\"stdafx.h\"</code> is typically...
{ "AcceptedAnswerId": "200033", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T19:48:58.800", "Id": "200005", "Score": "7", "Tags": [ "c++", "beginner", "programming-challenge", "array" ], "Title": "Calculating the number of rooms in a 2D house" }
200005
<p>Any tips to reduce lines, improve speed, or any cool thing, are welcome.</p> <p>I have been using this for years and I just realized, why not improve ...?</p> <pre><code>Sub AtualizarRelatorioGeral() Application.Calculation = xlCalculationManual Application.ScreenUpdating = False Application.EnableEvents = False Application.DisplayAlerts = False SaveChanges = False Dim Arquivo(18) As String Arquivo(1) = "zpp03ontem" Arquivo(2) = "vl10a" Arquivo(3) = "mb51consumomensal" Arquivo(4) = "mb51repassegerado" Arquivo(5) = "mb52peixerev" Arquivo(6) = "mb52peixepro" Arquivo(7) = "mb52exp" Arquivo(8) = "mb52repassesaldo" Arquivo(9) = "zsd17" Arquivo(10) = "zsd25fat" Arquivo(11) = "zsd25dev" Arquivo(12) = "mc.9estoquecd" Arquivo(13) = "mc.9consumo" Arquivo(14) = "mc.9centro" Arquivo(15) = "mc.9cdhipet" Arquivo(16) = "mc.9valor" Arquivo(17) = "zpp25" Arquivo(18) = "mc.9produto" For i = 1 To 18 Sheets(Arquivo(i)).Visible = True Next i Set WBgeral = ActiveWorkbook 'IMPORTAR ARQUIVOS For i = 1 To 18 WBgeral.Activate Sheets(Arquivo(i)).Activate Cells.Select Selection.Clear Workbooks.OpenXML ("C:\macrosm\prerelatoriolucimara\" &amp; Arquivo(i) &amp; ".xls") Range("A1").Select Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select Selection.Copy WBgeral.Activate Sheets(Arquivo(i)).Activate ActiveSheet.Paste Workbooks(Arquivo(i)).Close SaveChanges:=False Next i 'IMPORTAR ARQUIVOS Sheets("Principal").Activate For i = 1 To 18 Sheets(Arquivo(i)).Visible = False Next i Cells(4, 16).Value = Date Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True Application.EnableEvents = True Application.DisplayAlerts = True SaveChanges = True End Sub </code></pre>
[]
[ { "body": "<p>Firstly, as a habit, always include \"Option Explicit\" at the top of every module. This would force you to declare <code>WBgeral</code> (as <code>Workbook</code> would be logical),</p>\n\n<p>I assume that you originally created this from a recorded macro. Your use of <code>.Select</code> and <cod...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T19:51:55.963", "Id": "200006", "Score": "4", "Tags": [ "vba", "excel", "file" ], "Title": "Importing files into Excel" }
200006
<p>I'm a Java beginner currently practising MVC pattern and came up with this. Could you please check if this is a proper implementation of MVC and if there are any best practices that I have broken?</p> <pre><code>public class Appka { public static void main(String[] args) { Model model = new Model(); Controller controller = new Controller(model); View view = new View(model, controller); model.addListener(view); } } public class Model { String value; List&lt;StateChangedListener&gt; listeners = new ArrayList&lt;&gt;(); public Model() { this.value = ""; } public String getValue() { return value; } public void setValue(String value) { this.value = value; notifyListeners(); } public void addListener(StateChangedListener l) { listeners.add(l); } public void removeListener(StateChangedListener l) { listeners.remove(l); } public void notifyListeners() { listeners.forEach(l -&gt; l.stateChanged()); } } public class View extends JFrame implements StateChangedListener { private Model model; private Controller controller; private JLabel label1; private JLabel label2; private JButton button1; private JButton button2; public View(Model model, Controller controller) { this.model = model; this.controller = controller; initComponents(); } private void initComponents() { button1 = new JButton(); button2 = new JButton(); label1 = new JLabel(); label2 = new JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); button1.setText("1"); button1.addActionListener(controller); button2.setText("2"); button2.addActionListener(controller); label1.setText("label1"); label2.setText("label2"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(button1) .addComponent(label1)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label2) .addComponent(button2)) .addContainerGap(113, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(label1) .addComponent(label2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(button1) .addComponent(button2)) .addContainerGap(30, Short.MAX_VALUE)) ); pack(); setVisible(true); } @Override public void stateChanged() { label1.setText(model.getValue()); label2.setText(model.getValue()); } } public class Controller implements ActionListener { private Model model; public Controller(Model model) { this.model = model; } @Override public void actionPerformed(ActionEvent e) { JButton clicked = (JButton) e.getSource(); model.setValue(clicked.getText()); } } interface StateChangedListener { public void stateChanged(); } </code></pre>
[]
[ { "body": "<p>There are a couple of problems:</p>\n\n<ol>\n<li><p>You connected the buttons instead of the text fields to your model.</p></li>\n<li><p>You have two text fields but only a single value in your model. In proper MVC, each text field should be attached to a different property of the model.</p></li>\...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-21T23:06:09.740", "Id": "200012", "Score": "1", "Tags": [ "java", "mvc", "swing" ], "Title": "Simple Java MVC (swing)" }
200012
<p>I am developing a project with various tables so I can have better understanding of model relation by communicating with the experts. Can anyone look at my code and see if I have designed my models based on the following conditions or not (only the relation in the model)?</p> <blockquote> <h1>Users</h1> <p>There are 3 types of users:</p> <ol> <li>Manufacturer</li> <li>Agency</li> <li>Agents</li> </ol> <p>Manufacturer can create Agency and Agents. Agency can create Agents. Agents can create their own account and Agency or Manufacturers can search and assign that agent under their ownership.</p> <h1>Manufacturer</h1> <p>Name</p> <p>Address:</p> <p>City</p> <p>Street</p> <p>Country</p> <p>Contact Number (At least 3 numbers can be added)</p> <p>Email</p> <p>VAT/PAN Number</p> <p>Agency ============= Name</p> <p>Address:</p> <p>City</p> <p>Street</p> <p>Country</p> <p>Contact Number (At least 3 numbers can be added)</p> <p>Email</p> <p>VAT/PAN Number</p> <h1>Agent</h1> <p>DOB</p> <p>Sex</p> <p>Address:</p> <p>City</p> <p>Street</p> <p>Country</p> <p>Mobile Number (At least 2 numbers can be added)</p> <p>[All the below fields should contain user information regarding Who Created it?. Like, Which agent added that shop, which agent took that order?)</p> <h1>Products</h1> <p>Product Code</p> <p>Name</p> <p>Category (User should be able to select single category)</p> <p>Packaging</p> <p>Package Dimension (L x B x H)</p> <p>Package Weight</p> <p>Photo</p> <p>Selling Price</p> <p>Note (For discount note purpose. Buy 1 cartoon and get 2 pcs. free)</p> <h1>Shop</h1> <p>Name</p> <p>Address:</p> <p>City</p> <p>Street</p> <p>Country</p> <p>Coordinate</p> <p>Contact (Multiple)</p> <p>Photo</p> <p>VAT/PAN Number</p> <p>Owner Name</p> <h1>Order</h1> <p>Shop (user should be able to select shop from listing)</p> <p>Product (user should be able to select product from listing)</p> <p>Quantity</p> <p>Unit</p> <p>DateTime (order date time)</p> <p>Due Date</p> </blockquote> <p>Here is my code to fulfill the following condition:</p> <pre><code>accounts/models.py class Role(models.Model): ROLE_CHOICES = ( ('agent', 'Agent'), ('agency', 'Agency'), ('manufacturer', 'Manufacturer'), ) role = models.CharField(max_length=15, choices=ROLE_CHOICES) def __str__(self): return self.role class User(AbstractUser): role = models.ForeignKey( Role, on_delete=models.CASCADE, blank=True, null=True, ) def __str__(self): return self.username def save(self, *args, **kwargs): if not self.pk: # the instance is created self.role, created = Role.objects.get_or_create(role="agent") return super().save(*args, **kwargs) agency/models.py class Agency(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField( max_length=200, blank=False, null=False) city = models.CharField(max_length=150, blank=False, null=False) street = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) mobile_number = PhoneNumberField() email = models.EmailField(blank=False, null=False) vat_number = models.CharField(max_length=40, blank=False, null=False) agents/models.py class Agent(models.Model): SEX_CHOICE = ( ('male', 'Male'), ('female', 'Female'), ) owner = models.OneToOneField(User, on_delete=models.CASCADE) agencies = models.ForeignKey( Agency, related_name="agents", on_delete=models.CASCADE) manufacturers = models.ForeignKey( Manufacturer, related_name="agents_manufacturer", on_delete=models.CASCADE, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) sex = models.CharField(max_length=6, choices=SEX_CHOICE) city = models.CharField(max_length=150, blank=False, null=False) street = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) mobile_number = PhoneNumberField() class Manufacturer(models.Model): owner = models.OneToOneField( User, on_delete=models.CASCADE, related_name="manufacturer") agency = models.ForeignKey( Agency, blank=True, null=True, related_name="agency_manufacturer", on_delete=models.CASCADE) name = models.CharField( max_length=200, blank=False, null=False) city = models.CharField(max_length=150, blank=False, null=False) street = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) shops/models.py class Shop(models.Model): agent = models.ForeignKey(Agent, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=150, blank=False, null=False) city = models.CharField(max_length=150, blank=False, null=False) street = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) mobile_number = PhoneNumberField() vat_number = models.CharField(max_length=40, blank=False, null=False) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, db_index=True) description = models.TextField() parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Product(models.Model): product_code = models.CharField(max_length=50, blank=False, null=False) agencies = models.ForeignKey( Agency, on_delete=models.CASCADE, related_name="product_agencies", null=True) manufacturer = models.ForeignKey( Manufacturer, related_name="product_manufacturers", on_delete=models.CASCADE, null=True) name = models.CharField(max_length=120, db_index=True) category = models.ForeignKey( Category, related_name="product_category", null=True, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) min_price = models.DecimalField(max_digits=10, decimal_places=2) packaging = models.CharField(max_length=120) package_dimension = models.CharField(max_length=120, blank=True, null=True) package_weight = models.PositiveIntegerField(default=1) orders/models.py class Order(models.Model): product_code = models.CharField(max_length=50, blank=False, null=False) agents = models.ForeignKey( Agent, on_delete=models.CASCADE, related_name="order_agents") shops = models.ForeignKey( Shop, related_name="order_manufacturers", on_delete=models.CASCADE) product = models.ForeignKey( Product, related_name="order_product", on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) unit = models.CharField(max_length=50) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T02:43:26.603", "Id": "200019", "Score": "1", "Tags": [ "python", "django" ], "Title": "Model architecture in Django" }
200019
<p>Please give me some pointers on how I can improve this project with Python 2.7.</p> <pre><code>import json import urllib urls = ["https://data.calgary.ca/resource/kqmd-3dsq.json","https://data.calgary.ca/resource/4wni-k3sg.json"] print " \nThis is Json Data Parser Program. \nThis program will print the Unique Voting Station Name from 2013 or 2017 City Elections from City of Calgary OpenData Portal" CRED = '\033[91m' CEND = '\033[0m' try: year= int (raw_input("\nElection Year to Search [2013 or 2017]:")) if ( year not in range(2013,2018,4) ): year=int(raw_input("Invalid Year ! \nPlease type again Year to Search [2013 or 2017]:"))\ except (EOFError, KeyboardInterrupt, ValueError): year= int (raw_input("\nThe exception has occured !!\nPlease type again Year to Search [2013 or 2017]:")) else: print "You choose: {} year for Elections Results".format(year) try: ward=int(raw_input("\nWard to Search:")) if ( ward not in range(0,14)): ward=int(raw_input("Ward does not exist in City of Calgary !\nPlease type again Ward to Search:")) except (EOFError,ValueError,KeyboardInterrupt): ward=int(raw_input("\nThe exception has occured !!\nPlease type again Ward to Search:")) else: print "\nYou choose ward: {} for Elections Results".format(ward) def jsonUrl(year): global url if (year == 2017): url = urls[0] return url elif (year == 2013): url = urls[1] return url else: raise Exception('The City of Calgary only has data for 2013 and 2017') jsonUrl(year) response = urllib.urlopen(url) data= json.loads(response.read()) def wardstnname(ward): wardwithscore = "{}".format(ward) wardstnresult = [] for i in data: try: if (i["ward"] == wardwithscore and i["voting_station_name"] not in wardstnresult): wardstnresult.append(i["voting_station_name"]) except KeyError: continue if len(wardstnresult) &gt; 0: print "\nThere were total", len(wardstnresult),"unique voting stations in your ward" print "\nThe list of the Voting Station were as follows" for votingstnname,b in enumerate(wardstnresult,1): print '{} {}'.format(votingstnname,b) else: print CRED,"\nCity of Calgary has no Data on this Ward for Voting Station Name on Year", year,CEND wardstnname(ward) def wardOffice(ward): wardwithscore= "{}".format(ward) officeResult = [] for i in data: if (i["ward"] == wardwithscore and i["office"] == "COUNCILLOR" and i["ballot_name"] not in officeResult): officeResult.append(i["ballot_name"]) if len(officeResult) &gt; 0: print "\nThere were total", len(officeResult),"councillors in your ward" print "\nThe list of the Councillors were as follows" for councillorname,b in enumerate(officeResult,1): print '{} {}'.format(councillorname,b) else: print CRED,"\nCity of Calgary has no Data on this Ward for Councillors on Year", year,CEND wardOffice(ward) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T07:21:08.427", "Id": "384938", "Score": "1", "body": "Change the title and description to reflect what this program does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T09:26:05.463", "Id": "3849...
[ { "body": "<p>First, you should stop using Python 2, if possible. <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">It will stop being supported in a bit over a year.</a> Switch to Python 3, it is better in many ways.</p>\n\n<hr>\n\n<p>Now, let's start with <code>year not in range(2013,2018,4)</c...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T07:17:51.510", "Id": "200026", "Score": "2", "Tags": [ "python", "python-2.x" ], "Title": "Download the JSON from API and parse the data like Unique Voting Station Name and Councillors Name" }
200026
<p>After implementing SAT (separating axis theorem) and not being happy with it only working on stationary shapes, this in theory allowing for fast objects to <em>glitch through</em> others, I came up with this approach to detect collisions between moving objects. </p> <h1>Algorithm explained</h1> <p>The idea is quite simple:</p> <p>I figured that, if two shapes A and B aren't intersecting in their starting positions and A moves relative to B, the two shapes collide if and only if<br> a) any vertex of A crosses a segment of B or<br> b) any segment of A touches ("sweeps over") a vertex of B.</p> <p>A vertex of A collides with a segment of B when the segment from A to A + V, V being the velocity of A (aka. it's movement) intersect. That is implemented in the line intersection method of the line class (see below).</p> <p>Lastly, if I loop through all vertices in A and B and let them collide with all segments of the respective other and repeat the same with B and A with the movement vector turned 180 degrees, the shortest distance any point can travel until a collision happens is the shortest distance A can travel until it collides with B.</p> <p>To figure out if two segments intersect, I first trasnform them both so that the first segment goes from (0, 0) to (1, 0). Then, the two segments intersect if and only if the second segment cuts the X axis between 0 and 1, which is trivial to implement.</p> <h1>Implementation</h1> <h2>Collision detection itself</h2> <pre><code>local function single(a, b, v) local vertices = {a:vertices()} local segments = {b:segments()} local min_intersection for idx,vertex in ipairs(vertices) do local v_end = vertex + v local projection = line(vertex.x, vertex.y, v_end.x, v_end.y) for idx,segment in ipairs(segments) do min_intersection = nil_min(min_intersection, projection * segment) end end if min_intersection == 1 then return nil end return min_intersection end function module.movement(a, b, v) return nil_min(single(a, b, v), single(b, a, -v)) end </code></pre> <h2>Line intersection</h2> <pre><code>intersection = function(self, other) if not is_line(other) then error("Invalid argument; expected line, got "..type(other), 2) end local origin, base = self:vectors() local a = vector_2d(other.x_start, other.y_start) local b = vector_2d(other.x_end, other.y_end ) a = (a - origin):linear_combination(base) b = (b - origin):linear_combination(base) -- Both points are above or below X axis if a.y &lt; 0 and b.x &lt; 0 or a.y &gt; 0 and b.y &gt; 0 then return nil end -- A always has the smallest X value if a.x &gt; b.x then a, b = b, a end local x0 = a.x + (b.x-a.x) * a.y / (a.y-b.y) if x0&gt;=0 and x0&lt;=1 then return x0 else return nil, x0 end end </code></pre> <h2>Cheaty linear combination</h2> <p>As you can see, I only need the linear combination of a given vector and that same vector rotated by 90 degrees, making it quite trivial. Implementation with two vectors is irrelevant to this situation and may get implemented in the future should I need it.</p> <pre><code>linear_combination = function(self, basis_x, basis_y) if basis_y then error("Not Implemented!", 2) else -- Assumes basis_y is basis_x + 90 degrees local angle = self:angle() - basis_x:angle() local f_len = self:length() / basis_x:length() return vector_2d( round(f_len * cos(angle)), round(f_len * sin(angle)) ) end end; </code></pre> <p>Okay, that's pretty much it. I have done some testing using busted and it <em>seems</em> to work, but I am not sure if I may have overlooked some stupid mistake that might lead to complications later on. I am also unsure if that algorithm will be fast enough. Considering 3D games do complex collision detection these days, I would assume even a slightly slower algorithm wouldn't impact a 2D game on a modern gaming PC, but since this is löve, would this run on a mid-tier android phone or tablet at an acceptable framerate?</p> <p>Assumptions:</p> <ul> <li>Any game this might be used in will not have an unhealthily high number of collisions</li> <li>It is purely meant for 2D, no intention to try it in 3D</li> <li><em>most</em> shapes will be rectangles, on average they may have at most 10 or so vertices</li> <li>Vectors and segments are implemented using LuaJIT FFI structs, not Lua Tables</li> </ul> <p>As a small extra: The angle at which the first vertex collides with a segment of the other shape, can easily be used to obtain the angle to apply a force to both shapes at the point of collision. This can mean anything from just bouncing the entire object without considering center of mass, to more advanced phyiscal calculations that apply an actual force to the object. While this is interesting and a nice feature of the algorithm, it is trivial to implement and thus out of scope for the actual question.</p>
[]
[ { "body": "<p>I'm not experienced in LUA, so I can't comment on the code style itself. But I can on the algorithm and implementation.</p>\n\n<hr>\n\n<p>Bugs:</p>\n\n<ul>\n<li><p>I'm fairly confident this should be <code>b.y &lt; 0</code>, not <code>b.x &lt; 0</code>.</p>\n\n<pre><code>-- Both points are above ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T09:37:22.430", "Id": "200031", "Score": "5", "Tags": [ "performance", "collision", "lua" ], "Title": "Collision detection for moving 2D objects" }
200031
<p>I have written this function (in C++) to apply an arithmetic operation on two numbers and print the result.</p> <pre><code>void printResults(double a, double b, char c) { double r; if (c=='+') { r = a + b; } else if (c == '-') { r = a - b; } else if (c == '*') { r = a * b; } else if (c == '/') { r = a / b; } else { cout &lt;&lt; "Invalid operator" &lt;&lt; endl; } cout &lt;&lt; a &lt;&lt; " " &lt;&lt; c &lt;&lt; " " &lt;&lt; " is " &lt;&lt; r &lt;&lt; endl; } </code></pre> <p>but I am not happy as when condition fails I'll get an else output along with the last cout statement. </p> <p>Can I make it better using IF or do I have to use SWITCH-CASE or take the cout statement inside of else?</p> <p>I don't want to duplicate the last cout statement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T12:21:54.057", "Id": "384956", "Score": "1", "body": "Please include a short description of your code, and edit the title to be a summary of that description. As it stands, we'd have to guess what this is supposed to accomplish." ...
[ { "body": "<p>Here are a number of things that may help you improve your code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad...
{ "AcceptedAnswerId": "200036", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T11:36:28.653", "Id": "200032", "Score": "-1", "Tags": [ "c++", "c++11" ], "Title": "Function to perform an arithmetic operation on two numbers and print the result" }
200032
<p>I am working with 2 databases. </p> <p>One for admins ('backoffice') and one for users. </p> <p>Account managers: Use the 'backoffice' database to manage customer accounts. </p> <p>Customers: Whenever a users connects and inserts his username password and company name, the code must connect to the backoffice database, validate his data, get his database host name (there are 5 customer databases), disconnect from 'backoffice' and connect to the customer personal account. </p> <p>Is it "good practice" to create a general 'Database' class, a 'Backoffice_db' class (extending if with 'Database') and a 'Customer_db' class (extending it with Backoffice_db class)? or should i manage both in one 'Database' class? </p> <p>Database.class.php: </p> <pre><code>&lt;?php /** * Database class * https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class * */ class Database { # @object, The PDO object protected $pdo; # @object, PDO statement object protected $sQuery; # @array, The database settings protected $ini; # @bool , Connected to the database protected $connected = false; # @object, Object for logging exceptions protected $log; # @array, The parameters of the SQL query protected $parameters; # Create an instance private /** * Default Constructor * * 1. Instantiate Log class. * 2. Creates the parameter array. */ public function __construct() { } /** * Get the PDO connection * */ public function getPDO() { if ($this-&gt;pdo instanceof PDO) return $this-&gt;pdo; } /** * This method makes connection to the database. * * 1. Reads the database settings from a ini file. * 2. Puts the ini content into the settings array. * 3. Tries to connect to the database. * 4. If connection failed, exception is displayed and a log file gets created. */ protected function Connect($host, $user, $password, $dbname) { $dsn = 'mysql:dbname=' . $dbname . ';host=' . $host . ''; try { # Read settings from INI file, set UTF8 $this-&gt;pdo = new PDO($dsn, $user, $password, array( PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8" )); # We can now log any exceptions on Fatal error. $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # Disable emulation of prepared statements, use REAL prepared statements instead. $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); # Connection succeeded, set the boolean to true. $this-&gt;connected = true; } catch (PDOException $e) { # Write into log // echo $this-&gt;ExceptionLog($e-&gt;getMessage()); dbg( $this-&gt;ExceptionLog($e-&gt;getMessage()) ); die(); } } /* * You can use this little method if you want to close the PDO connection * */ public function CloseConnection() { # Set the PDO object to null to close the connection # http://www.php.net/manual/en/pdo.connections.php $this-&gt;pdo = null; } /* * Gets db.ini data * */ protected function get_db_ini() { if ( empty($this-&gt;ini) ) $this-&gt;load_db_ini(); } /* * Load db.ini file contents * */ protected function load_db_ini() { $this-&gt;ini = parse_ini_file('/etc/optimizeit/db.ini', true); } /* * Gets section from db.ini resultarray * */ protected function get_db_ini_section($section) { return isset( $this-&gt;ini[$section] ) ? $this-&gt;ini[$section] : Array(); } /** * Every method which needs to execute a SQL query uses this method. * * 1. If not connected, connect to the database. * 2. Prepare Query. * 3. Parameterize Query. * 4. Execute Query. * 5. On exception : Write Exception into the log + SQL query. * 6. Reset the Parameters. */ protected function Init($query, $parameters = "") { # Connect to database if (!$this-&gt;connected) { $this-&gt;Connect(); } try { # Prepare query $this-&gt;sQuery = $this-&gt;pdo-&gt;prepare($query); # Add parameters to the parameter array $this-&gt;bindMore($parameters); # Bind parameters if (!empty($this-&gt;parameters)) { foreach ($this-&gt;parameters as $param =&gt; $value) { if(is_int($value[1])) { $type = PDO::PARAM_INT; } else if(is_bool($value[1])) { $type = PDO::PARAM_BOOL; } else if(is_null($value[1])) { $type = PDO::PARAM_NULL; } else { $type = PDO::PARAM_STR; } // Add type when binding the values to the column $this-&gt;sQuery-&gt;bindValue($value[0], $value[1], $type); } } # Execute SQL $this-&gt;sQuery-&gt;execute(); } catch (PDOException $e) { # Write into log and display Exception // echo $this-&gt;ExceptionLog($e-&gt;getMessage(), $query); dbg( $this-&gt;ExceptionLog($e-&gt;getMessage(), $query) ); die(); } # Reset the parameters $this-&gt;parameters = array(); } /** * @void * * Add the parameter to the parameter array * @param string $para * @param string $value * Updated 11.07.2018: https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class/issues/83 */ public function bind($para, $value) { if (is_int($para)) { $this-&gt;parameters[sizeof($this-&gt;parameters)] = [++$para , $value]; } else { $this-&gt;parameters[sizeof($this-&gt;parameters)] = [":" . $para , $value]; } } /** * @void * * Add more parameters to the parameter array * @param array $parray */ public function bindMore($parray) { if (empty($this-&gt;parameters) &amp;&amp; is_array($parray)) { $columns = array_keys($parray); foreach ($columns as $i =&gt; &amp;$column) { $this-&gt;bind($column, $parray[$column]); } } } /** * If the SQL query contains a SELECT or SHOW statement it returns an array containing all of the result set row * If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows * * @param string $query * @param array $params * @param int $fetchmode * @return mixed */ public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC) { $query = trim(str_replace("\r", " ", $query)); $this-&gt;Init($query, $params); $rawStatement = explode(" ", preg_replace("/\s+|\t+|\n+/", " ", $query)); # Which SQL statement is used $statement = strtolower($rawStatement[0]); if ($statement === 'select' || $statement === 'show') { return $this-&gt;sQuery-&gt;fetchAll($fetchmode); } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') { return $this-&gt;sQuery-&gt;rowCount(); } else { return NULL; } } /** * Returns the last inserted id. * @return string */ public function lastInsertId() { return $this-&gt;pdo-&gt;lastInsertId(); } /** * Starts the transaction * @return boolean, true on success or false on failure */ public function beginTransaction() { return $this-&gt;pdo-&gt;beginTransaction(); } /** * Execute Transaction * @return boolean, true on success or false on failure */ public function executeTransaction() { return $this-&gt;pdo-&gt;commit(); } /** * Rollback of Transaction * @return boolean, true on success or false on failure */ public function rollBack() { return $this-&gt;pdo-&gt;rollBack(); } /** * Returns an array which represents a column from the result set * * @param string $query * @param array $params * @return array */ public function column($query, $params = null) { $this-&gt;Init($query, $params); $Columns = $this-&gt;sQuery-&gt;fetchAll(PDO::FETCH_NUM); $column = null; foreach ($Columns as $cells) { $column[] = $cells[0]; } return $column; } /** * Returns an array which represents a row from the result set * * @param string $query * @param array $params * @param int $fetchmode * @return array */ public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC) { $this-&gt;Init($query, $params); $result = $this-&gt;sQuery-&gt;fetch($fetchmode); $this-&gt;sQuery-&gt;closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued, return $result; } /** * Returns the value of one single field/column * * @param string $query * @param array $params * @return string */ public function single($query, $params = null) { $this-&gt;Init($query, $params); $result = $this-&gt;sQuery-&gt;fetchColumn(); $this-&gt;sQuery-&gt;closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued return $result; } /** * Writes the log and returns the exception * * @param string $message * @param string $sql * @return string */ protected function ExceptionLog($message, $sql = "") { $exception = "Unhandled Exception. &lt;br /&gt; \n"; $exception .= $message; $exception .= "&lt;br /&gt; \n You can find the error back in the log."; if (!empty($sql)) { # Add the Raw SQL to the Log $message .= "\r\nRaw SQL : " . $sql; } # Write into log // $this-&gt;log-&gt;write($message); return $exception; } /** * Generate a string for columns selection * @param Array $app_name An array of app name/s or preferable - comma separated sting * @throws Array An array of app_id, app_name, lhm_threshold, enable_evm, evm_type, evm_rate for each app. */ private function select_columns(Array $colums_array) { return implode(",", $columns_array); } } ?&gt; </code></pre> <p>Backoffice_db.php: </p> <pre><code>&lt;?php /** * Backoffice Database Connection class * */ require("Database.class.php"); class Backoffice_db extends Database { # @string, Database Host private $bo_host; # @string, Database Username protected $user = 'root'; # @string, Database Password protected $password = 'thisismyrealpassword'; # @string, Database Name private $bo_dbname = 'backoffice'; /** * Default Constructor * * 1. Instantiate Log class. * 2. Creates the parameter array. * 3. Get backoffice variables from ini * 4. Connect to database. * */ public function __construct() { $this-&gt;parameters = array(); // Init params for queries. if ( empty($this-&gt;ini) ) $this-&gt;get_db_ini(); // Make sure INI is fetched. $this-&gt;get_bo_host(); // Set global variables for the backoffice. $this-&gt;Connect($this-&gt;bo_host, $this-&gt;user, $this-&gt;password, $this-&gt;bo_dbname); // Connect with global vars. } /** * Get backoffice HOST for connection * * 1. Get backoffice credentials. * 2. Set backoffice credentials. * */ protected function get_bo_host() { $backoffice_credentials = $this-&gt;get_db_config($this-&gt;dbname); $this-&gt;bo_host = $backoffice_credentials['host']; } /** * Get db configurations via given $dbname * * 1. Return 'main' array section (backoffice credentials) * */ protected function get_db_config($dbname) { try { $settings = $this-&gt;get_db_ini_section(md5($this-&gt;bo_dbname)); if ( empty($settings) ) throw new Exception('Cannot Find the customers name `' . $this-&gt;bo_dbname . '` in .ini file.'); } catch (Exception $e) { // echo $this-&gt;ExceptionLog($e-&gt;getMessage()); // dbg( $this-&gt;ExceptionLog($e-&gt;getMessage()) ); err( $this-&gt;ExceptionLog($e-&gt;getMessage()) ); die($ex-&gt;getMessage()); } return $settings; } } </code></pre> <p>Customer_db.php: </p> <pre><code>&lt;?php /** * Customer Database Connection class * */ require("Backoffice_db.class.php"); class Customer_db extends Backoffice_db { # @string, Database Host private $host; # @string, Database Name private $dbname; # The Single Instance private static $instance; /* * Get an instance of the Database * @return Instance */ public static function getInstance() { if ( !self::$instance ) { // If no instance then make one self::$instance = new self(); } return self::$instance; // Return the Database obj // return self::$instance-&gt;getPDO();// Return the PDO connectoion instance from dabase obj } /** * Default Constructor * 1. Sets given dbnmae * 2. Connects to the backoffice * 3. Get customer data from backoffice db * 4. Disconnects from backoffice db * 5. Connect to customers database if active account */ public function __construct($dbname) { self::$instance = $this; $this-&gt;dbname = $dbname; $bo_conn = new Backoffice_db(); list($this-&gt;host, $this-&gt;dbname, $status) = $this-&gt;get_customer_conn_info($bo_conn); $bo_conn-&gt;CloseConnection(); // Disconnect from backoffice and connect to customer try { if ( ($status === 'Deleted') || ($status === 'Inactive') ) throw new Exception('Customer ('. $dbname .') account is "Deleted" or "Inactive".'); $this-&gt;Connect($this-&gt;host, $this-&gt;user, $this-&gt;password, $this-&gt;dbname); } catch(Exception $e) { err($this-&gt;ExceptionLog($e-&gt;getMessage())); die($e-&gt;getMessage()); } } /** * Get user HOST, DBNAME &amp; STATUS from backoffice=&gt;customers table * * 1. Run a query on backoffice to fetch users host and db name * 2. return 2 separate vairbles of host and db name * */ protected function get_customer_conn_info($bo_conn){ $customer_data = $bo_conn-&gt;row("SELECT db_host, db_name, assessment_status FROM customers WHERE customer_name = :customer_name", array("customer_name" =&gt; $this-&gt;dbname)); return array($customer_data['db_host'], $customer_data['db_name'], $customer_data['assessment_status']); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T12:47:21.250", "Id": "384958", "Score": "0", "body": "This isn't an answer to your specific question but I have to wonder why there are multiple databases involved in the first place. Seems to be overly complicating things for no ap...
[ { "body": "<p>There are several areas of improvement</p>\n<h3>Architecture</h3>\n<p>First of all, I don't see why these classes should inherit to each other. To me, there is no difference between these classes and I don't see why can't you just instantiate two objects of the same class. Of course if you fix ano...
{ "AcceptedAnswerId": "200057", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T12:38:44.713", "Id": "200034", "Score": "2", "Tags": [ "php", "object-oriented", "database" ], "Title": "Connecting 2 databases: one for admins and one for customers" }
200034
<p>This is my first program in Python that I have coded and I am relatively happy with how it turned out. I would like to know how I could make my code shorter and more efficient. </p> <pre><code>def one_round(player): #Distinguish player 1 from player 2 if player == "p1": p = "Player 1" elif player == "p2": p = "Player 2" pin = raw_input("%s move (a/b/c for row | 1/2/3 for column):" % (p)) #receive input for player from console #separating row from column row = pin[0].lower() col = int(pin[1]) - 1 if row == "a": #changing the row letter into a digit for the index of board row = 0 elif row =="b": row = 1 elif row == "c": row = 2 while (row &gt; 2 or col &gt; 2) or (board[row][col] == 'X' or board[row][col] == 'O'): if row &gt; 2 or col &gt; 2: print "Oops, these co-ordinates are off of the board, please try again" elif board[row][col] == 'X' or board[row][col] == 'O': print "Oops this spot has been taken, please pick another" pin = raw_input("%s move (a/b/c for row | 1/2/3 for column):" % (p)) #receive input for player from console #separating row from column row = pin[0].lower() col = int(pin[1]) - 1 if row == "a": #changing the row letter into a digit for the index of board row = 0 elif row =="b": row = 1 elif row == "c": row = 2 if player == "p1": #Determining whether to use X or O x = 'X' elif player == "p2": x = 'O' del board[row][col] #Swapping out the dashes for a symbol board[row].insert(col, x) print str(" ".join(board[0])) + '\n' + str(" ".join(board[1])) + '\n' + str(" ".join(board[2])) #Printing board if board[0] == [x, x, x] or board[1] == [x, x, x] or board[2] == [x, x, x] or (board[0][0] == x and board[1][0] == x and board[2][0] == x) or (board[0][1] == x and board[1][1] == x and board[2][1] == x) or (board[0][2] == x and board[1][2] == x and board[2][2] == x) or (board[0][0] == x and board[1][1] == x and board[2][2] == x) or (board[0][2] == x and board[1][1] == x and board[2][0] == x): #Checking for winner print '%s wins!' % (p) + '\n' + 'Game Over!' return True elif board[0][0] != '-' and board[0][1] != '-' and board[0][2] != '-' and board[1][0] != '-' and board[1][1] != '-' and board[1][2] != '-' and board[2][0] != '-' and board[2][1] != '-' and board[2][2] != '-': #Checking for draw print 'Draw!' + '\n' + 'Game Over!' return True else: return False #--------------------------------------------------------------------------------------------------------------------- """Tic tac toe game. (Noughts and crosses)""" print "Welcome to Tic Tac Toe!" + "\n" + " Find a friend and start the game by typing coordinates for a 3x3 grid labelled with the letters a,b,c from top to bottom along the vertical axis and with 1,2,3 from left to right along the horizontal axis." + "\n" + "Have Fun!" #initialising board and players board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]] p1 = False p2 = False row = 0 col = 0 while (p1 == False and p2 == False): #running game p1 = one_round("p1") if p1 == True: break p2 = one_round("p2") </code></pre>
[]
[ { "body": "<p>Welcome to Python xD! You did a great job on it ^^</p>\n\n<p>Here are my suggestions</p>\n\n<h2>Don‘t code everything all in one function</h2>\n\n<p>there are two parts in your <code>one_round</code></p>\n\n<ul>\n<li>place new piece on board</li>\n<li>check if there is a winner or game over</li>\...
{ "AcceptedAnswerId": "200041", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T14:34:04.460", "Id": "200037", "Score": "3", "Tags": [ "python", "beginner", "game", "python-2.x", "tic-tac-toe" ], "Title": "Noughts and crosses game for 2 players" }
200037
<p>I have 40 CSV files, each containing ~6 million rows, and 2 columns. The columns are <code>account_id</code> and <code>account_balance</code>.</p> <p>The objective is getting the sum of all <code>account_balance</code> grouped by first two digits/chars of <code>account_id</code>.</p> <p>For example:</p> <p><code>account_id = 00as3dff01234</code> is in group <code>00</code>, and the account id is paired with an <code>account_balance</code> value.</p> <p>For illustration:</p> <p>Each CSV file is of the form:</p> <pre><code>account_id, account_balance 0012228hgs, 123000 01223jj4d, 34000 fb1233999, 1245999 . . . (all about 6 million rows) </code></pre> <p>The output by using all 40 CSV files would be of the form:</p> <pre><code>00 : 123000444220 01 : 500000 0a : 30444555120 . . . ff : 45002221222 (all 276 groups) </code></pre> <p>The right-hand side is the sum of money of all accounts that have <code>account_id</code> with the left-hand side as first two digits/characters. </p> <hr> <p>My code gives the correct result, BUT not efficient enough. On my laptop it consumes around 11-12 minutes. How can I improve the performance such that the time is around 5-6 minutes? Sorry, I can't provide the data, but I think it can be replicated by simulating only 1 replicated CSV file.</p> <pre><code>import pandas for i in range(4): for j in range(10): digits = str(i)+str(j) all_data = pandas.read_csv('/home/asus/data/arief_anbiya_{}.csv'.format(digits), chunksize = 100000, iterator = True) #Transform each csv data to DF. all_data = pandas.concat(all_data, ignore_index= True) all_data['account_group'] = [acc_id[0:2] for acc_id in all_data.account_id] #Adding a now column 'first_two' of each account_id (from current csv). dummy = all_data.groupby(by = 'account_group').sum() #Sum of 'account_balance' of current DF grouped by 'first_two' (from current csv). if i == 0 and j == 0: #Create the Series for the total 'account_balance' (grouped by 'first_two'). sum_of_groupby = dummy.account_balance else: #Update the Series of total 'account_balance'. for ft in set(all_data['account_group']): # unique_ft is all unique 'first_two' (from current csv). try: sum_of_groupby[ft] += dummy.account_balance[ft] except: sum_of_groupby[ft] = dummy.account_balance[ft] print('Done adding : arief_anbiya_{}.csv'.format(digits)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T17:01:21.933", "Id": "385125", "Score": "0", "body": "Learn to meassure times, which part is slowing the process the most? Its meaningless to try to improve code performance when 95% of that time is from reading/writing file" }, ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T16:11:05.480", "Id": "200042", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "csv", "pandas" ], "Title": "Grouped by First Two Digits of Account_ID of ~240 million rows of Pandas DF" }
200042
<p>I'm very new to Python, and I've made a small program/script that will allow me to stream specific files at a given time. </p> <p>My idea is that I have a .csv file for each day, with one row for each movie/tv show i want to watch and a cron job that checks every 30 minutes (at :00 and :30). If the job finds any row that matches the current time, then it will play the file given in the row. </p> <p>As it is now, it has been configured to my installation of Mac OS High Sierra, using VLC as player. Since i've split the config out to a seperate file, I'm hoping it will be easy to setup on another environment (e.g. a Raspberry Pi) </p> <p>I've split things into three seperate files (all located in the same folder), one of the files being a config file.</p> <p><strong>cron.py</strong> is the file, that is executed by the cron job.</p> <pre><code>import tvshow import config tvShowFile = tvshow.getTodaysFilename() time = tvshow.getTime() print ("Scanning file %s for %s" % (tvShowFile, time)) row = tvshow.scanFileForTime(tvShowFile, time) if(row): urlColIndex = config.csvIndexes['url'] streamUrl = row[urlColIndex] print("Executing app:" + config.apppath) print("URL:" + streamUrl) try: tvshow.show(streamUrl) except Exception as e: print ("Something went wrong:" + str(e)) else: print("No show at time %s" % time) </code></pre> <p><strong>tvshow.py</strong> is the file with all the actual stuff</p> <pre><code>from datetime import datetime import config import csv import config from subprocess import call def getTodaysFilename(): filename = datetime.now().strftime(config.fileTimeFormat) return config.filepath + "/" + filename + "." + config.extension def getTime(): return datetime.now().strftime(config.hourMinuteFormat) def getFileContent(filename): lines = [] with open(filename) as csvfile: csvContent = csv.reader(csvfile, delimiter = ',') for row in csvContent: lines.append(row) return lines def scanFileForTime(filename, time): timeColIndex = config.csvIndexes['time'] content = getFileContent(filename) for row in content: if(row[timeColIndex] == time): return row def compileArguments(streamUrl): arguments = [] arguments.append(config.apppath) arguments.append(streamUrl) for item in config.appArguments: arguments.append(item) return arguments def show(streamUrl): arguments = compileArguments(streamUrl) call(arguments) </code></pre> <p><strong>config.py</strong> is the configuration</p> <pre><code>apppath = '/Applications/VLC.app/Contents/MacOS/VLC' filepath = '/Users/Shared/tvshow' fileTimeFormat = "%Y_%m_%d" hourMinuteFormat = "%H:%M" extension = 'csv' csvIndexes = dict( time = 0, title = 1, url = 2 ) appArguments = [ '--fullscreen', '--no-loop', '--play-and-exit' ] </code></pre> <p><strong>Tv show listings sample file</strong> - The "title" is not used for anything and could be left out. </p> <pre><code>"19:47","Big Buck Bunny","http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" </code></pre> <p>Any feedback on the code would be appreciated. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T20:23:39.420", "Id": "384995", "Score": "0", "body": "Is it python 2.7 or 3? Since you're using `print()` as a function, I'd suggest moving to 3.5+ if you're still in 2.7." } ]
[ { "body": "<p>I'd start with a few specific points for the code style.</p>\n\n<ol>\n<li>Consistent naming. You are mixing <code>snake_case</code> and <code>camelCase</code>. Check the section on <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">naming conventio...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T16:18:49.587", "Id": "200043", "Score": "8", "Tags": [ "python", "python-2.x", "csv", "video", "scheduled-tasks" ], "Title": "Streaming scheduled TV shows according to a CSV playlist" }
200043
<p>I wrote a little script to automate upgrading Firefox to a new version under Debian, since I don't want to install it from unstable and the <code>snap</code> version has rendering issues.</p> <p>Any comments are welcome, is there anything I have missed or any potential problems?</p> <pre><code>#!/bin/bash # firefox_upgrade - program to upgrade firefox quantum error_exit() { echo "$1" 1&gt;&amp;2 exit 1 } firefox_path="" firefox_file="" # parsing path and filename if [ $# -ne 1 ]; then error_exit "usage: $0 firefox_quantum_path" else firefox_path="$1" firefox_file="${firefox_path##*/}" fi # checking if input is a valid file if [ ! -f "$firefox_path" ]; then error_exit "Invalid file! Aborting." fi # removing previous install, if existent firefox_bin="/opt/firefox" if [ -e "$firefox_bin" ]; then rm -rf $firefox_bin else echo "$firefox_bin doesn't exist." fi # removing previous symlink, if existent firefox_link="/usr/bin/firefox-quantum" if [ -f "$firefox_link" ]; then rm $firefox_link else echo "$firefox_link doesn't exist." fi # copying the tar to /opt rsync -ah --progress $firefox_path /opt/$firefox_file # unpacking the tar if successfully changed directory if cd /opt; then tar -jxvf $firefox_file else error_exit "Could not change directory! Aborting." fi # if unpack was successful, set permissions, create symlink, and remove tar if [ "$?" = "0" ]; then chmod 755 /opt/firefox ln -s /opt/firefox/firefox /usr/bin/firefox-quantum rm $firefox_file else error_exit "Could not extract file! Aborting." fi exit 0 </code></pre>
[]
[ { "body": "<p>Pretty nice script, I have mostly minor suggestions.</p>\n\n<h3>Always double-quote variables used in command arguments</h3>\n\n<p>The parameters in these command should be double-quoted to protect from word splitting and globbing:</p>\n\n<blockquote>\n<pre><code>rsync -ah --progress $firefox_path...
{ "AcceptedAnswerId": "200048", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T16:24:42.363", "Id": "200044", "Score": "9", "Tags": [ "bash", "linux", "installer", "firefox" ], "Title": "Upgrade Firefox Quantum from tarball" }
200044
<p>Here is my very first event dispatcher. I would like to get both, style and code review, as well as some ideas to improve this implementation (new features etc.)</p> <p>I tried to write code in C++17 style as much as possible.</p> <p><strong>IEventDispatcher.h</strong></p> <pre><code>#pragma once #include &lt;map&gt; #include &lt;functional&gt; template&lt;typename EventType&gt; class IEventDispatcher { public: using EventHandler = std::function&lt;void()&gt;; virtual void addEventListener(EventType eventToAdd, EventHandler handler) = 0; virtual void removeEventListener(EventType eventToRemove) = 0; virtual void dispatch(EventType eventToDispatch) = 0; }; </code></pre> <p><strong>EventDispatcher.hpp</strong></p> <pre><code>#pragma once #include "IEventDispatcher.h" template&lt;typename EventType&gt; class EventDispatcher : public IEventDispatcher&lt;EventType&gt; { public: using EventHandler = std::function&lt;void()&gt;; EventDispatcher(); ~EventDispatcher(); void addEventListener(EventType eventToAdd, EventHandler handler); void removeEventListener(EventType eventToRemove); void dispatch(EventType eventToDispatch); private: std::multimap&lt;EventType, EventHandler&gt; eventListeners; }; template&lt;typename EventType&gt; EventDispatcher&lt;EventType&gt;::EventDispatcher() {} template&lt;typename EventType&gt; EventDispatcher&lt;EventType&gt;::~EventDispatcher() {} template&lt;typename EventType&gt; void EventDispatcher&lt;EventType&gt;::addEventListener(EventType eventToAdd, EventHandler handler) { eventListeners.emplace(eventToAdd, handler); } template&lt;typename EventType&gt; void EventDispatcher&lt;EventType&gt;::removeEventListener(EventType eventToRemove) { eventListeners.erase(eventToRemove); } template&lt;typename EventType&gt; void EventDispatcher&lt;EventType&gt;::dispatch(EventType eventToDispatch) { for (const auto &amp;[event, handler] : eventListeners) { if (event == eventToDispatch) { handler(); } } } </code></pre>
[]
[ { "body": "<h1>Design</h1>\n\n<ul>\n<li><p>Is there a need for <code>IEventDispatcher</code>? Defining it as an abstract base class doesn't provide much utility if there's only ever going to be one derived class.</p></li>\n<li><p>Is there any requirement for <code>EventDispatcher::eventListeners</code> to be of...
{ "AcceptedAnswerId": "200061", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T17:58:16.107", "Id": "200049", "Score": "4", "Tags": [ "c++", "event-handling", "callback", "c++17", "observer-pattern" ], "Title": "Simple event dispatcher" }
200049
<p><strong>Note</strong> this was the wrong version of the code. The updated version is here: <a href="https://codereview.stackexchange.com/questions/200054/efficiently-counting-rooms-from-a-floorplan-version-2">Efficiently counting rooms from a floorplan (version 2)</a> My apologies!</p> <h2>Update</h2> <p>Final version 3 with test harness here: <a href="https://codereview.stackexchange.com/questions/200145/multithreaded-testing-for-counting-rooms-from-a-floor-plan-solution">Multithreaded testing for counting rooms from a floor plan solution</a></p> <hr> <p>I was inspired by <a href="https://codereview.stackexchange.com/questions/200005/calculating-the-number-of-rooms-in-a-2d-house">Calculating the number of rooms in a 2D house</a> and decided to see if I could come up with efficient code to solve the same problem.</p> <p>To recap, the problem (<a href="https://cses.fi/problemset/task/1192/" rel="nofollow noreferrer">from here</a>) is this: </p> <blockquote> <p>You are given a map of a building, and your task is to count the number of rooms. The size of the map is \$n \times m\$ squares, and each square is either floor or wall. You can walk left, right, up, and down through the floor squares.</p> <h2>Input</h2> <p>The first input line has two integers \$n\$ and \$m\$: the height and width of the map.</p> <p>Then there are \$n\$ lines of \$m\$ characters that describe the map. Each character is <code>.</code> (floor) or <code>#</code> (wall).</p> <h2>Output</h2> <p>Print one integer: the number of rooms.</p> <h2>Constraints</h2> <p>\$1\le n,m \le 2500\$</p> <h2>Example</h2> <h3>Input:</h3> <pre><code>5 8 ######## #..#...# ####.#.# #..#...# ######## </code></pre> <h3>Output:</h3> <p>3</p> </blockquote> <h2>Strategy</h2> <p>It seemed to me to be possible to solve the problem by processing line at a time, so that's what my code does. Specifically, it keeps a tracking <code>std::vector&lt;std::size_t&gt;</code> named <code>tracker</code> that corresponds to the rooms from the previous row and starts with all zeros.</p> <p>As it reads each line of input, it processes the line character at a time. If it's non-empty (that is, if it's a wall), set the corresponding <code>tracker</code> entry to 0. </p> <p>Otherwise, if the previous row (that is, the matching value from the <code>tracker</code> vector) was a room, then this is part of the same room.</p> <p>If the previous character in the same row was a room, this is the same room.</p> <p>The code also has provisions for recognizing that what it "thought" was two rooms turns out to be one room, and adjusts both the <code>tracker</code> vector and the overall <code>roomcount</code>.</p> <p>Because I wanted to be able to test it with many different inputs, my version of the code keeps reading and processing each floor plan until it gets to the end of the file.</p> <p>The code is time efficient because it makes only a single pass through the input, and it's memory efficient because it only allocates a single \$1 \times m\$ vector.</p> <h2>Questions</h2> <ol> <li><strong>Correctness</strong> - The code works correctly on every input I've tried, but if there is any error in either the code or the algorithm, I'd like to know.</li> <li><strong>Efficiency</strong> - Could the code be made even more efficient?</li> <li><strong>Reusability</strong> - This works for a 2D map, but I'd like to adapt it to 3 or more dimensions. Are there things I could do in this code to make such adaptation simpler?</li> </ol> <p>Any hints on style or any other aspect of the code would be welcome as well.</p> <h2>rooms.cpp</h2> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; std::size_t rooms(std::istream &amp;in) { std::size_t height; std::size_t width; std::size_t roomcount{0}; static constexpr char empty{'.'}; in &gt;&gt; height &gt;&gt; width; if (!in) return roomcount; std::vector&lt;std::size_t&gt; tracker(width, 0); for (auto i{height}; i; --i) { std::string row; in &gt;&gt; row; if (row.size() != width) { in.setstate(std::ios::failbit); return roomcount; } for (std::size_t j{0}; j &lt; width; ++j) { if (row[j] == empty) { // continuation from line above? if (tracker[j]) { // also from left? if (j &amp;&amp; tracker[j-1] &amp;&amp; (tracker[j-1] != tracker[j])) { tracker[j] = tracker[j-1] = std::min(tracker[j], tracker[j-1]); --roomcount; } } else { // continuation from left? if (j &amp;&amp; tracker[j-1]) { tracker[j] = tracker[j-1]; } else { tracker[j] = ++roomcount; } } } else { tracker[j] = 0; } } } return roomcount; } int main() { auto r = rooms(std::cin); while (std::cin) { std::cout &lt;&lt; r &lt;&lt; '\n'; r = rooms(std::cin); } } </code></pre> <h2>test.in</h2> <pre><code>5 8 ######## #..#...# ####.#.# #..#...# ######## 9 25 ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#...# ######################### 3 3 ... ... ... 3 3 ### ... ### 3 3 ### ### ### 7 9 ######### #.#.#.#.# #.#.#.#.# #.#...#.# #.#####.# #.......# ######### 5 8 ######## #..#.#.# ##.#.#.# #..#...# ######## 7 8 ######## #..#.#.# ##.#.#.# #..#...# ######## #..#...# ######## 7 9 ######### #.#.#.#.# #.#.#.#.# #.#.#.#.# #.#.#.#.# #.......# ######### 7 9 ######### #.#.##..# #.#.##.## #.#.##..# #.#...#.# #...#...# ######### 7 9 ######### #.#.....# #.#.###.# #.#...#.# #.#####.# #.......# ######### 7 9 ######### #.......# #.#####.# #.#.#.#.# #.#.#.#.# #.......# ######### </code></pre> <h2>Results</h2> <p>Running the program as <code>rooms &lt;test.in</code> produces this expected result:</p> <pre><code>3 47 1 1 0 2 2 4 1 1 1 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T07:54:28.030", "Id": "385029", "Score": "0", "body": "\"The corrected version is here\" Since that version has since been proven to be incorrect as well, perhaps the text should be modified." } ]
[ { "body": "<p>The program does not work correctly for all input. As an example,\nthe output is <code>0</code> (zero rooms) for the input</p>\n\n<pre>\n5 8\n########\n######.#\n#......#\n##.#...#\n########\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "20...
{ "AcceptedAnswerId": "200053", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T18:10:39.973", "Id": "200051", "Score": "6", "Tags": [ "c++", "algorithm", "programming-challenge", "c++14" ], "Title": "Efficiently counting rooms from a floorplan" }
200051
<p>This is version 2 of <a href="https://codereview.stackexchange.com/questions/200051/efficiently-counting-rooms-from-a-floorplan">Efficiently counting rooms from a floorplan</a>. I had accidentally pasted in the wrong version of the code.</p> <h2>Update</h2> <p>Final version (version 3) of the code with updated test harness is here: <a href="https://codereview.stackexchange.com/questions/200145/multithreaded-testing-for-counting-rooms-from-a-floor-plan-solution">Multithreaded testing for counting rooms from a floor plan solution</a></p> <hr> <p>I was inspired by <a href="https://codereview.stackexchange.com/questions/200005/calculating-the-number-of-rooms-in-a-2d-house">Calculating the number of rooms in a 2D house</a> and decided to see if I could come up with efficient code to solve the same problem.</p> <p>To recap, the problem (<a href="https://cses.fi/problemset/task/1192/" rel="nofollow noreferrer">from here</a>) is this: </p> <blockquote> <p>You are given a map of a building, and your task is to count the number of rooms. The size of the map is \$n \times m\$ squares, and each square is either floor or wall. You can walk left, right, up, and down through the floor squares.</p> <h2>Input</h2> <p>The first input line has two integers \$n\$ and \$m\$: the height and width of the map.</p> <p>Then there are \$n\$ lines of \$m\$ characters that describe the map. Each character is <code>.</code> (floor) or <code>#</code> (wall).</p> <h2>Output</h2> <p>Print one integer: the number of rooms.</p> <h2>Constraints</h2> <p>\$1\le n,m \le 2500\$</p> <h2>Example</h2> <h3>Input:</h3> <pre><code>5 8 ######## #..#...# ####.#.# #..#...# ######## </code></pre> <h3>Output:</h3> <p>3</p> </blockquote> <h2>Strategy</h2> <p>It seemed to me to be possible to solve the problem by processing line at a time, so that's what my code does. Specifically, it keeps a tracking <code>std::vector&lt;std::size_t&gt;</code> named <code>tracker</code> that corresponds to the rooms from the previous row and starts with all zeros.</p> <p>As it reads each line of input, it processes the line character at a time. If it's non-empty (that is, if it's a wall), set the corresponding <code>tracker</code> entry to 0. </p> <p>Otherwise, if the previous row (that is, the matching value from the <code>tracker</code> vector) was a room, then this is part of the same room.</p> <p>If the previous character in the same row was a room, this is the same room.</p> <p>The code also has provisions for recognizing that what it "thought" was two rooms turns out to be one room, and adjusts both the <code>tracker</code> vector and the overall <code>roomcount</code>.</p> <p>Because I wanted to be able to test it with many different inputs, my version of the code keeps reading and processing each floor plan until it gets to the end of the file.</p> <p>The code is time efficient because it makes only a single pass through the input, and it's memory efficient because it only allocates a single \$1 \times m\$ vector.</p> <h2>Questions</h2> <ol> <li><strong>Correctness</strong> - The code works correctly on every input I've tried, but if there is any error in either the code or the algorithm, I'd like to know.</li> <li><strong>Efficiency</strong> - Could the code be made even more efficient?</li> <li><strong>Reusability</strong> - This works for a 2D map, but I'd like to adapt it to 3 or more dimensions. Are there things I could do in this code to make such adaptation simpler?</li> </ol> <p>Any hints on style or any other aspect of the code would be welcome as well.</p> <h2>rooms.cpp</h2> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; std::size_t rooms(std::istream &amp;in) { std::size_t height; std::size_t width; std::size_t roomcount{0}; static constexpr char empty{'.'}; in &gt;&gt; height &gt;&gt; width; if (!in) return roomcount; std::vector&lt;std::size_t&gt; tracker(width, 0); for (auto i{height}; i; --i) { std::string row; in &gt;&gt; row; if (row.size() != width) { in.setstate(std::ios::failbit); return roomcount; } for (std::size_t j{0}; j &lt; width; ++j) { if (row[j] == empty) { // continuation from line above? if (tracker[j]) { // also from left? if (j &amp;&amp; tracker[j-1]) { if (tracker[j-1] &lt; tracker[j]) { tracker[j] = tracker[j-1]; --roomcount; } else if (tracker[j] &lt; tracker[j-1]) { // set all contiguous areas to the left for (auto k{j-1}; k; --k) { if (tracker[k]) { tracker[k] = tracker[j]; } else { break; } } --roomcount; } } } else { // continuation from left? if (j &amp;&amp; tracker[j-1]) { tracker[j] = tracker[j-1]; } else { tracker[j] = ++roomcount; } } } else { tracker[j] = 0; } } } return roomcount; } int main() { auto r = rooms(std::cin); while (std::cin) { std::cout &lt;&lt; r &lt;&lt; '\n'; r = rooms(std::cin); } } </code></pre> <h2>test.in</h2> <pre><code>5 8 ######## #..#...# ####.#.# #..#...# ######## 9 25 ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#...# ######################### 3 3 ... ... ... 3 3 ### ... ### 3 3 ### ### ### 7 9 ######### #.#.#.#.# #.#.#.#.# #.#...#.# #.#####.# #.......# ######### 5 8 ######## #..#.#.# ##.#.#.# #..#...# ######## 7 8 ######## #..#.#.# ##.#.#.# #..#...# ######## #..#...# ######## 7 9 ######### #.#.#.#.# #.#.#.#.# #.#.#.#.# #.#.#.#.# #.......# ######### 7 9 ######### #.#.##..# #.#.##.## #.#.##..# #.#...#.# #...#...# ######### 7 9 ######### #.#.....# #.#.###.# #.#...#.# #.#####.# #.......# ######### 7 9 ######### #.......# #.#####.# #.#.#.#.# #.#.#.#.# #.......# ######### </code></pre> <h2>Results</h2> <p>Running the program as <code>rooms &lt;test.in</code> produces this expected result:</p> <pre><code>3 47 1 1 0 2 2 4 1 1 1 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T13:53:10.200", "Id": "385077", "Score": "0", "body": "What constitutes a room? Maybe I’m just not seeing the bit that defines when a hallway suddenly meets room criteria. Also, I haven’t had a chance to fully analyze your source, bu...
[ { "body": "<p>Unfortunately, it does not work correctly. The output is <code>0</code> (zero rooms)\nfor the floor plan</p>\n\n<pre>\n4 6\n######\n#.#..#\n#....#\n######\n</pre>\n\n<p>After parsing the second row, the room count is two and the tracker\nvector is</p>\n\n<pre><code>010220 \n</code></pre>\n\n<p>The...
{ "AcceptedAnswerId": "200067", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T18:46:42.210", "Id": "200054", "Score": "11", "Tags": [ "c++", "algorithm", "programming-challenge", "c++14" ], "Title": "Efficiently counting rooms from a floorplan (version 2)" }
200054
<p>I have got some code that calculates the angle between all of the points in an array. It works, but it is quite slow. This is because it has complexity O(n^2). It has to loop through the array and apply the <code>angle</code> function to every combination of points.</p> <pre><code>import math import random def angle(pos1,pos2): dx=pos2[0]-pos1[0] dy=pos2[1]-pos1[1] rads=math.atan2(dy,dx) rads%=2*math.pi degs=math.degrees(rads) return degs class Point(object): def __init__(self): self.pos=[random.randint(0,500) for _ in range(2)]#random x,y self.angles=[] points=[Point() for _ in range(100)] for point in points: point.angles=[] #so that each frame, they will be recalculated for otherC in points: if otherC is point:continue #don't check own angle ang=angle(point.pos,otherC.pos) point.angles.append(ang) </code></pre> <p>I feel like it could be greatly sped up by using numPy or some other method. I did some searching (<a href="https://www.google.com/search?q=numpy%20angle%20between%20points%20in%20array" rel="nofollow noreferrer">here</a>), but all I could find was functions to get angle between planes, or complex numbers. I just need simple arrays. <strong>How can this code be optimized for more speed?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T21:29:38.257", "Id": "384999", "Score": "1", "body": "[`itertools.combinations`](https://devdocs.io/python~2.7/library/itertools#itertools.combinations)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22...
[ { "body": "<p>Mathematically, if you have the angle between \\$ A(x_1, y_1) \\$ and \\$ B(x_2, y_2) \\$, given as:</p>\n\n<p>$$ \\theta = \\tan^{-1}{\\dfrac{y_2 - y_1}{x_2 - x_1}} \\tag{in degrees} $$</p>\n\n<p>then, the angle between \\$ B \\$ and \\$ A \\$ would be:</p>\n\n<p>$$ \\phi = 180° + \\theta \\mod {...
{ "AcceptedAnswerId": "200063", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T20:39:31.973", "Id": "200060", "Score": "3", "Tags": [ "python", "performance", "array", "numpy" ], "Title": "Getting angle between all points in array" }
200060
<p>Inspired by recent questions about counting the rooms in a floor plan (<a href="https://codereview.stackexchange.com/q/200005/35991">1</a>, <a href="https://codereview.stackexchange.com/q/200051/35991">2</a>, <a href="https://codereview.stackexchange.com/q/200054/35991">3</a>), here is my attempt to solve the problem with a Swift program.</p> <p>The problem (from <a href="https://cses.fi/problemset/task/1192/" rel="nofollow noreferrer">“Counting Rooms” on CSES</a>) is: </p> <blockquote> <p>You are given a map of a building, and your task is to count the number of rooms. The size of the map is \$ n \times m \$ squares, and each square is either floor or wall. You can walk left, right, up, and down through the floor squares.</p> <h2>Input</h2> <p>The first input line has two integers \$n\$ and \$m\$: the height and width of the map.</p> <p>Then there are \$n\$ lines of \$m\$ characters that describe the map. Each character is <code>.</code> (floor) or <code>#</code> (wall).</p> <h2>Output</h2> <p>Print one integer: the number of rooms.</p> <h2>Constraints</h2> <p>\$1\le n,m \le 2500\$</p> <h2>Example</h2> <h3>Input:</h3> <pre><code>5 8 ######## #..#...# ####.#.# #..#...# ######## </code></pre> <h3>Output:</h3> <p>3</p> </blockquote> <p>I took this as an opportunity to learn about <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow noreferrer">“disjoint-set data structures”</a> (also called “union-find data structures”). Here is my implementation, it follows closely the pseudo-code from the Wikipedia page. The only difference is that the parent of the “representative” (or “root”) does not point to itself, but is <code>nil</code>. </p> <p><strong>UnionFind.swift</strong></p> <pre><code>class UnionFind { var parent: UnionFind? var rank: Int init() { self.parent = nil self.rank = 0 } // Find with path compression func find() -&gt; UnionFind { if let parent = self.parent { let p = parent.find() self.parent = p return p } return self } // Combine the trees if the roots are distinct. // Returns `true` if the trees were combined, and // `false` if the trees already had the same root. @discardableResult func union(with other: UnionFind) -&gt; Bool { var xRoot = self.find() var yRoot = other.find() if xRoot === yRoot { return false } if xRoot.rank &lt; yRoot.rank { swap(&amp;xRoot, &amp;yRoot) } // Merge yRoot into xRoot yRoot.parent = xRoot if xRoot.rank == yRoot.rank { xRoot.rank += 1 } return true } } </code></pre> <p>The main code is highly inspired by <a href="https://codereview.stackexchange.com/questions/200054/efficiently-counting-rooms-from-a-floorplan-version-2">Efficiently counting rooms from a floorplan (version 2)</a>:</p> <ul> <li>The data is read from standard input, and can be more than one floor plan.</li> <li>For each column we keep track of the room to which the field at the current row and this column belongs to. Here we use the <code>UnionFind</code> structure.</li> <li>If a field is a continuation from both left and top then the two tracker values are combined with <code>union()</code>. </li> </ul> <p><strong>main.swift</strong></p> <pre><code>import Foundation func readDimensions() -&gt; (height: Int, width: Int)? { guard let line = readLine() else { return nil } let ints = line.split(separator: " ") guard ints.count == 2, let height = Int(ints[0]), let width = Int(ints[1]) else { return nil } return (height, width) } func readMapAndCountRooms(height: Int, width: Int) -&gt; Int? { var tracker = Array&lt;UnionFind?&gt;(repeating: nil, count: width) var roomCount = 0 for _ in 0..&lt;height { guard let line = readLine(), line.count == width else { return nil } for (offset, field) in line.enumerated() { if field == "." { if let top = tracker[offset] { // Continuation from the top ... if offset &gt; 0, let left = tracker[offset - 1] { // ... and from the left: if top.union(with: left) { roomCount -= 1 } } } else if offset &gt; 0, let left = tracker[offset - 1] { // Continuation from the left: tracker[offset] = left } else { // New room: tracker[offset] = UnionFind() roomCount += 1 } } else { // A wall: tracker[offset] = nil } } } return roomCount } while let (height, width) = readDimensions(), let count = readMapAndCountRooms(height: height, width: width) { print(count) } </code></pre> <p>For the input data</p> <pre> 7 9 ######### #.#.#.#.# #.#.#...# #.#...#.# #.#.#.#.# #.......# ######### 4 6 ###### #.#..# #....# ###### 5 8 ######## ######.# #......# ##.#...# ######## 5 8 ######## #..#...# ####.#.# #..#...# ######## 9 25 ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#.#.# ######################### #.#.#.#.#.#.#.#.#.#.#...# ######################### 3 3 ... ... ... 3 3 ### ... ### 3 3 ### ### ### 7 9 ######### #.#.#.#.# #.#.#.#.# #.#...#.# #.#####.# #.......# ######### 5 8 ######## #..#.#.# ##.#.#.# #..#...# ######## 7 8 ######## #..#.#.# ##.#.#.# #..#...# ######## #..#...# ######## 7 9 ######### #.#.#.#.# #.#.#.#.# #.#.#.#.# #.#.#.#.# #.......# ######### 7 9 ######### #.#.##..# #.#.##.## #.#.##..# #.#...#.# #...#...# ######### 7 9 ######### #.#.....# #.#.###.# #.#...#.# #.#####.# #.......# ######### 7 9 ######### #.......# #.#####.# #.#.#.#.# #.#.#.#.# #.......# ######### </pre> <p>this produces the (correct) output</p> <pre> 1 1 1 3 47 1 1 0 2 2 4 1 1 1 1 </pre> <p>Any feedback on the code is welcome, in particular:</p> <ul> <li>This is my first experiment with union-find data structures. Is it correctly implemented? Can it be simplified?</li> <li>Is the main program logic correct or can you spot any errors?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:47:13.480", "Id": "385109", "Score": "0", "body": "A question about the code: Does `tracker[offset] = UnionFind()` allocate a new bit of memory to store the object? I presume so, and I presume that `var parent: UnionFind?` is a r...
[ { "body": "<p>Not a full review, I don’t know Swift at all. I just wanted to comment on the union-find implementation.</p>\n\n<p>I’ve seen this a lot, keeping track of the rank, it never found it useful. When you are comparing the rank to determine which of the two labels should be the parent, you have just <c...
{ "AcceptedAnswerId": "200069", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T22:16:48.533", "Id": "200066", "Score": "7", "Tags": [ "algorithm", "programming-challenge", "swift", "union-find" ], "Title": "Swiftly counting rooms in a floor plan" }
200066
<p>There are 12 buttons, and each of them has 3 options for selecting pictures, depending on the data. It works but I think need a shorter and more intelligent decision.</p> <pre><code>import SpriteKit class SelectEasyLevelViewController: UIViewController{ @IBOutlet weak var level_1: UIButton! @IBOutlet weak var level_2: UIButton! @IBOutlet weak var level_3: UIButton! @IBOutlet weak var level_4: UIButton! @IBOutlet weak var level_5: UIButton! @IBOutlet weak var level_6: UIButton! @IBOutlet weak var level_7: UIButton! @IBOutlet weak var level_8: UIButton! @IBOutlet weak var level_9: UIButton! @IBOutlet weak var level_10: UIButton! @IBOutlet weak var level_11: UIButton! @IBOutlet weak var level_12: UIButton! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) //This thing help me to open data if UserDefaults.standard.array(forKey: "levelPassed") != nil { Model.sharedInstance.levelPassed = UserDefaults.standard.array(forKey: "levelPassed") as! [Int] } let image = UIImage(named: "levelbutton01") let image2 = UIImage(named: "levelbutton02") let image3 = UIImage(named: "levelbutton03") switch Model.sharedInstance.levelPassed[0] { case 1: level1.setBackgroundImage(image, for: .normal) case 2: level1.setBackgroundImage(image2, for: .normal) case 3: level1.setBackgroundImage(image3, for: .normal) default: break } .......................................... Here codes for button 2, 4, 5, 6, 7, 8, 9, 10, 12 ......................................... switch Model.sharedInstance.levelPassed[11] { case 1: level_12.setBackgroundImage(image, for: .normal) case 2: level_12.setBackgroundImage(image2, for: .normal) case 3: level_12.setBackgroundImage(image3, for: .normal) default: break } } </code></pre> <p>Or maybe another way.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T23:54:52.423", "Id": "385189", "Score": "0", "body": "at first: if you need to count your items then you have a possible code smell in programming ;) good that you ask for it" }, { "ContentLicense": "CC BY-SA 4.0", "Crea...
[ { "body": "<p><strong>DRY</strong> - Don't Repeat Yourself:</p>\n\n<p><strong>1) change this block into an method:</strong></p>\n\n<pre><code>switch Model.sharedInstance.levelPassed[0] {\n case 1:\n level1.setBackgroundImage(image, for: .normal)\n case 2:\n level1.setBackgroundImage(image2, ...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T19:47:12.960", "Id": "200068", "Score": "0", "Tags": [ "swift", "uikit" ], "Title": "Change level button's image" }
200068
<p>The following code is my solution to an old <a href="https://www.hackerrank.com/contests/quora-haqathon/challenges/upvotes/problem" rel="nofollow noreferrer">problem</a> I found today.</p> <blockquote> <h2>Input Format</h2> <p>Line 1: Two integers, <em>N</em> (1 ≤ <em>N</em> ≤ 10<sup>6</sup>) and window size <em>K</em> (1 ≤ <em>K</em> ≤ <em>N</em>)<br> Line 2: <em>N</em> positive integers of upvote counts, each integer less than or equal to 10<sup>9</sup></p> <h2>Output Format</h2> <p>Line 1..: <em>N</em> - <em>K</em> + 1 integers, one integer for each window's result on each line</p> <h2>Sample Input</h2> <pre><code>5 3 1 2 3 1 1 </code></pre> <h2>Sample Output</h2> <pre><code>3 0 -2 </code></pre> <h2>Explanation</h2> <p>For the first window of [1, 2, 3], there are 3 non-decreasing subranges and 0 non-increasing, so the answer is 3. For the second window of [2, 3, 1], there is 1 non-decreasing subrange and 1 non-increasing, so the answer is 0. For the third window of [3, 1, 1], there is 1 non-decreasing subrange and 3 non-increasing, so the answer is -2.</p> </blockquote> <p>I could solve the problem's logic and the initial test cases passed. But for the longer test cases, it gives timeout.</p> <p>Are there any ways I can optimize parts of the following code? </p> <pre><code>def window_result(arr, size): num_inc = 0 count = 0 for elem in arr: if elem == 'i' or elem == 'e': count += 1 else: num_inc += (count*(count+1))/2 count = 0 num_inc += (count*(count+1))/2 num_dec = 0 count = 0 for elem in arr: if elem == 'd' or elem == 'e': count += 1 else: num_dec += (count*(count+1))/2 count = 0 num_dec += (count*(count+1))/2 return num_inc-num_dec conf = raw_input().strip().split() num_days, window_size = int(conf[0]), int(conf[1]) data = [int(i) for i in raw_input().strip().split()] begin = 0 end = window_size - 1 while end &lt; num_days: diff_array = [] for i in xrange(begin + 1, end + 1): if data[i] &gt; data[i - 1]: diff_array.append('i') elif data[i] == data[i - 1]: diff_array.append('e') else: diff_array.append('d') print window_result(diff_array, window_size-1) begin += 1 end += 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T05:46:54.853", "Id": "385012", "Score": "0", "body": "Have you tried locally whether the code resolves to the correct answer for longer cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-30T16:59:03....
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T00:02:33.603", "Id": "200072", "Score": "1", "Tags": [ "python", "programming-challenge", "python-2.x", "time-limit-exceeded" ], "Title": "Quora upvotes trends Hackerrank challenge" }
200072
<p>I recently tried to solve the <a href="https://en.wikipedia.org/wiki/Josephus_problem" rel="noreferrer">Josephus Problem</a> on <a href="https://www.spoj.com/problems/CLSLDR/" rel="noreferrer">Sphere Online</a> to help answer <a href="https://codereview.stackexchange.com/questions/182850/spoj-class-leader-using-circular-linked-list">this question</a> but am getting TLE for any solution I come up with.</p> <p>The exact parameters of the problem are:</p> <blockquote> <p>This is new year in Planet X and there is something special! A classroom in this planet is looking for a new class leader using an unique game!</p> <p>These are the ways how the game is played.</p> <ol> <li>There are n students in the class. Each student is labeled from 1 (first student) to n (last student).</li> <li>A paper is given to m-th student.</li> <li>The next o-th student who gets the paper quits the game.</li> <li>The paper is passed until there is one last student who hasn't quitted the game.</li> <li>The student becomes the class leader.</li> </ol> <p>Now, your task is to find the number of such student.</p> <p>Input</p> <p>The first line contains a number T (0 &lt;= T &lt;= 106). Each of the next T lines contains 3 integers which are n (0 &lt; n &lt;= 103), m, o (0 &lt; m, o &lt;= n) and are separated by a single space.</p> <p>Output</p> <p>For each test case, print the required answer. </p> <p>Example</p> <pre><code>Input: 2 4 1 2 5 2 3 Output: 2 1 </code></pre> <p>Explanation for test case 1</p> <p>1 2 3 4 -> The paper is being held by student 1. Pass the paper by 2 students. Now, the paper is being held by student 3.</p> <p>1 2 4 -> Student 3 quits. Pass the paper by 2 students. Now, the paper is being held by student 1.</p> <p>2 4 -> Student 1 quits. Pass the paper by 2 students. Now, the paper is being held by student 4.</p> <p>2 -> Student 4 quits. Student 2 becomes the class leader.</p> </blockquote> <p>I chose to use a linked list for several reasons. First I wanted the fast random deletion times. I considered a vector because calculating the index may be faster than traversal but I also got TLE with that.</p> <p>In the following code I iterate to the <code>start_index</code>, then iterate each step-remove sequence until there is only one node left, then return its value. </p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; int josephus(int num_students, int start_index, int steps) { std::list&lt;int&gt; students; for (auto i = 1; i &lt;= num_students; ++i) { students.push_back(i); } std::list&lt;int&gt;::iterator it = students.begin(); for (auto i = 1; i &lt; start_index; ++i) { ++it; if (it == students.end()) { it = students.begin(); } } int countdown = num_students - 1; while (countdown--) { for (auto i = 0; i &lt; steps; ++i) { ++it; if (it == students.end()) { it = students.begin(); } } if (it != students.begin()) { it = students.erase(it); --it; } else { students.erase(it); it = students.end(); --it; } } return *it; } int main() { int num_tests; std::cin &gt;&gt; num_tests; while (num_tests--) { int num_students; // formerly n int start_index; //formerly m int steps; //formerly o std::cin &gt;&gt; num_students &gt;&gt; start_index &gt;&gt; steps; std::cout &lt;&lt; josephus(num_students, start_index, steps) &lt;&lt; '\n'; } } </code></pre> <p>The biggest issues I can think of are the insertion and the iteration.</p> <p>With insertion I mean setting the value of each node grows with the size of <code>num_students</code> and is thus \$\mathcal{O}(n)\$. That is just setting the list it doesn't even account for iteration and removal. The only solution to this I can think of is to express the problem mathematically.</p> <p>When I say iteration may be a problem I mean two things. First I have no idea if I implemented the iterator properly and therefor are there so speed issues there? Is this the proper way to use an iterator efficiently in modern C++? Do you need to implement it differently for Lists? But also I was far more concerned with large values of <code>steps</code> and the lengthy iteration process with that.</p> <p>Also, am I getting cache misses with the use of Lists? Inserting continuously doesn't guarantee contiguous memory if I understand correctly. Is there any way around that?</p> <p>Being stumped with linked lists and determined to figure out the solution I tried to find a mathematical solution. After all Time Limit Exceeded usually just means you were trying a naïve and brute-force approach. I was able find this mathematical expression on <a href="https://www.geeksforgeeks.org/josephus-problem-set-1-a-on-solution/" rel="noreferrer">GeeksForGeeks</a> which ultimately was not fast enough either.</p> <blockquote> <pre><code>#include &lt;iostream&gt; int josephus(int num_students, int steps) { if (num_students == 1) { return 1; } else { /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k % n + 1 as position 1 */ return (josephus(num_students - 1, steps) + steps - 1) % num_students + 1; } } int main() { int num_tests; std::cin &gt;&gt; num_tests; while (num_tests--) { int num_students; // formerly n int start_index; //formerly m int steps; //formerly o std::cin &gt;&gt; num_students &gt;&gt; start_index &gt;&gt; steps; int answer = josephus(num_students, steps); answer = (answer + start_index) % num_students; if (answer != 0) { std::cout &lt;&lt; answer &lt;&lt; '\n'; } else { std::cout &lt;&lt; num_students &lt;&lt; '\n'; } } } </code></pre> </blockquote> <p>I share this because it still doesn't solve the problem on Sphere Online. I'm not sure what else to try. I didn't use recursion with my List implementation because I didn't think it would help. After all the first post I was answering use exposed nodes that were traversed recursively and when I cleaned that up it was still giving TLE. The mathematic solution above uses lots of calls to mod which I understand can be a very time-consuming operator. If the reason I can't solve this is because the math is just too far over my head then I'll accept that and move on but I have a feeling I'm just being silly and would prefer a hint or a nudge at the solution as apposed to the outright answer.</p> <p>I am also always trying to improve my programming ability and would love feedback on any and all aspects of my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T04:38:07.577", "Id": "385009", "Score": "1", "body": "Did you note the \\$\\mathcal{O}(k \\log n)\\$ algorithm on the linked wikipedia page?" } ]
[ { "body": "<h1><code>josephus</code> implementation with <code>std::list</code></h1>\n\n<ul>\n<li><p>The list initialization can be simplified to</p>\n\n<pre><code>std::list&lt;int&gt; students(num_students); // No braces here! (Would use the constructor taking a std::initializer_list)\nstd::iota(std::begin(stu...
{ "AcceptedAnswerId": "200142", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T03:43:03.477", "Id": "200079", "Score": "5", "Tags": [ "c++", "performance", "programming-challenge", "time-limit-exceeded" ], "Title": "Counting out game with std::list" }
200079
<blockquote> <p>I am solving the "Generating Parentheses Given a Number" challenge. The total number of parentheses combination turns out to be Catalan Series. The following code works but I am looking for comment on the coding style and performance. The particular solution itself might not be the most efficient but I want to try this algorithm out. In this code, I don't assume I know that this is Catalan Series, which might help with memory allocation a bit. The resizing could be more efficient and could have used <code>realloc</code>.</p> </blockquote> <p>I have included the code without the reallocation for comparison. The solution using catalan passes the test. I am not trying to pass the test with this code. Just want some comment for my own improvement. This seems to be a popular problem online. Here is question and article from leetcode. <a href="https://leetcode.com/articles/generate-parentheses/" rel="nofollow noreferrer">https://leetcode.com/articles/generate-parentheses/</a></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef struct paren_info_s{ int size; int capacity; int slen; char **parens; int idx; } paren_info_t; #define SIZE_INCREMENT 8 int catalan(int n) { if (n &lt;= 1 ) return 1; int res = 0; for (int i=0; i &lt; n; i++) { res += catalan(i) *catalan(n-i-1); } return res; } void dfs_paren(int left, int right, paren_info_t *paren_info, char *temp) { if (right &lt; left) { return; } #if 0 if (!left &amp;&amp; !right) { paren_info-&gt;parens[paren_info-&gt;size] = malloc(sizeof(paren_info-&gt;slen)); memcpy(paren_info-&gt;parens[paren_info-&gt;size], temp, paren_info-&gt;slen); paren_info-&gt;size++; } #endif if (!left &amp;&amp; !right) { paren_info-&gt;parens[paren_info-&gt;size] = malloc(sizeof(paren_info-&gt;slen)); memcpy(paren_info-&gt;parens[paren_info-&gt;size], temp, paren_info-&gt;slen); printf("%d. %s\n", paren_info-&gt;size, paren_info-&gt;parens[paren_info-&gt;size]); paren_info-&gt;size++; //memset(temp+paren_info-&gt;idx,0,paren_info-&gt;slen); if (paren_info-&gt;size &gt;= paren_info-&gt;capacity) { char **temp_paren_info; paren_info-&gt;capacity = SIZE_INCREMENT * ((paren_info-&gt;size/2)+1); temp_paren_info = malloc(sizeof(char*)*(paren_info-&gt;capacity)); for (int i=0; i &lt; paren_info-&gt;size; i++) { temp_paren_info[i] = paren_info-&gt;parens[i]; } free(paren_info-&gt;parens); paren_info-&gt;parens = temp_paren_info; } } int idx ; if (left&gt;0) { idx = paren_info-&gt;idx; temp[paren_info-&gt;idx] = '('; paren_info-&gt;idx++; dfs_paren(left-1, right, paren_info, temp); temp[idx] = ' '; paren_info-&gt;idx--; } if (right&gt;0) { idx = paren_info-&gt;idx; temp[paren_info-&gt;idx] = ')'; paren_info-&gt;idx++; dfs_paren(left, right-1, paren_info, temp); temp[idx] = ' '; paren_info-&gt;idx--; } } char** gen_paren(int n, int* return_size, paren_info_t *paren_info) { paren_info-&gt;size = 0; paren_info-&gt;parens = malloc(sizeof(char*)*SIZE_INCREMENT); paren_info-&gt;capacity= SIZE_INCREMENT; paren_info-&gt;slen = (n*2) + 1; paren_info-&gt;idx = 0; char *temp = malloc(paren_info-&gt;slen); memset(temp,0,paren_info-&gt;slen); dfs_paren(n,n,paren_info,temp); char **ans = malloc(sizeof(char*)*paren_info-&gt;size); for(int i=0; i &lt; paren_info-&gt;size;i++) { ans[i] = paren_info-&gt;parens[i]; } *return_size = paren_info-&gt;size; return ans; } void test_paren(int n) { char** ans; int size; paren_info_t *paren_info; paren_info = malloc(sizeof(paren_info_t)); ans = gen_paren(n, &amp;size, paren_info); for(int i=0; i &lt; size; i++) { printf("%s\n", ans[i]); } } int main() { test_paren(7); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T05:29:13.407", "Id": "385011", "Score": "3", "body": "Please add a *description* of the task (and a link to the source if this comes from some online challenge/competition)." }, { "ContentLicense": "CC BY-SA 4.0", "Creat...
[ { "body": "<p>General recommendations:</p>\n\n<ol>\n<li>Style: Please be consistent, you sometimes add spaces around operators, sometimes not, you sometimes add spaces after keywords, sometimes not, ...</li>\n<li>Comments ...</li>\n<li>Choose appropriate types, almost all <code>int</code>s here would be better ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T05:27:16.573", "Id": "200083", "Score": "-1", "Tags": [ "performance", "algorithm", "c" ], "Title": "Generating parentheses using DFS" }
200083
<p>I have heard from my friend that it is bad practice to normally loop though the whole database to meet certain criteria. He mentioned something about the proper way being that you index the objects of interest. </p> <p>What I want to achieve here is make a report for our company. So I do this by summing up all the items that have the same account that is within the filter date range set by <code>start_date</code> and <code>end_date</code> to start.</p> <p>Some variable definitions:</p> <p>Account name: <code>data_entries.iloc[j, 4]</code></p> <p>Account type: <code>data_listofaccounts.iloc[i, 1]</code></p> <p>Account amount: <code>data_entries.iloc[j, 5]</code></p> <p>So is there a more efficient way to write this code that will be less computationally taxing on the computer specifically. (minimize computational requirement)</p> <pre><code>import pandas as pd import datetime entries_csv = "C:\\Users\\Pops\\Desktop\\Entries.csv" listofaccounts_csv = "C:\\Users\\Pops\\Desktop\\List of Accounts.csv" data_entries = pd.read_csv(entries_csv) data_listofaccounts = pd.read_csv(listofaccounts_csv) data_entries['VOUCHER DATE'] = pd.to_datetime(data_entries['VOUCHER DATE'], format="%m/%d/%Y").dt.date summary_amount = [0]*(len(data_listofaccounts) + 1) summary = (('DEBIT ACCOUNT', 'DEBIT AMOUNT'),) start_date = datetime.date(2018, 4, 1) end_date = datetime.date(2018, 10, 30) for i in range(0, len(data_listofaccounts)): for j in range(0, len(data_entries)): if start_date &lt;= data_entries.iloc[j, 1] &lt;= end_date: if data_listofaccounts.iloc[i, 0] == data_entries.iloc[j, 4]\ and (data_listofaccounts.iloc[i, 1] == "CURRENT ASSET" or data_listofaccounts.iloc[i, 1] == "FIXED ASSET" or data_listofaccounts.iloc[i, 1] == "EXPENSE"): summary_amount[i] += data_entries.iloc[j, 5] elif data_listofaccounts.iloc[i, 0] == data_entries.iloc[j, 4]\ and (data_listofaccounts.iloc[i, 1] == "CURRENT LIABILITY" or data_listofaccounts.iloc[i, 1] == "LONG TERM LIABILITY" or data_listofaccounts.iloc[i, 1] == "EQUITY"): summary_amount[i] -= data_entries.iloc[j, 5] summary += ((data_listofaccounts.iloc[i, 0], "{:,}".format(round(summary_amount[i], 2))),) </code></pre> <p>Entries sample data: <a href="https://i.stack.imgur.com/j9Jyj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j9Jyj.png" alt="enter image description here"></a></p> <p>List of Accounts sample data: <a href="https://i.stack.imgur.com/9ICtx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ICtx.png" alt="enter image description here"></a></p> <p><code>List of Accounts</code> contains unique account names while in the <code>Entries</code> worksheet, it can be repeated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T08:04:37.947", "Id": "385031", "Score": "1", "body": "How does this work: `data_listofaccounts.iloc[i, 1] == \"CURRENT ASSET\" or \"FIXED ASSET\" or \"EXPENSE\"`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "...
[ { "body": "<p>The kind of operation you’re doing is called <a href=\"https://pandas.pydata.org/pandas-docs/stable/merging.html\" rel=\"nofollow noreferrer\">a join</a>: you want to associate data from a <code>DataFrame</code> to data from another one based on a shared information on a given column.</p>\n\n<p>To...
{ "AcceptedAnswerId": "200100", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T06:38:15.910", "Id": "200085", "Score": "0", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Create a summary report by summing the amount's of accounts with the same name and within the date range specified" }
200085
<p>I'm new in python and I'm wondering if there any issue I should worry about in the following code?</p> <pre><code>from base64 import b64encode class Base64Encoder: @classmethod def encode_basic(cls, usr, pwd): token = cls.base64_encode(f"{usr}:{pwd}") return f'Basic {token}' @classmethod def encode_bearer(cls, token): return f'Bearer {token}' @staticmethod def base64_encode(token): return b64encode(token.encode('ascii')).decode('ascii') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T09:55:00.363", "Id": "385052", "Score": "0", "body": "Did you write this code yourself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T14:45:09.840", "Id": "385088", "Score": "0", "body":...
[ { "body": "<p>You've got a class with only two <code>classmethod</code>s and one <code>staticmethod</code>. One <code>classmethod</code> does not use the class argument, the other one refers to a static method. Hence none of the class' methods use either the class or one of its instances. Thus, you do not requi...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T09:30:43.493", "Id": "200094", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Base64Encoder class wrapper" }
200094
<p>My goal is to implement a method, which finds a list of Windows Services that match given set of criteria:</p> <ol> <li><code>SearchString</code>: A search string</li> <li><code>SearchServiceBy</code>: Could be <code>ServiceName</code> or <code>DisplayName</code></li> <li><code>SearchOption</code>: Could be <code>Equals</code>, <code>Contains</code>, <code>StartsWith</code>, <code>EndsWith</code> or <code>Regex</code></li> <li><code>SearchServiceType</code>: Could be <code>SingleService</code> or <code>GroupOfServices</code></li> </ol> <p></p> <pre><code>private List&lt;ServiceController&gt; GetServices() { var allServices = ServiceController.GetServices().ToList(); var resultList = new List&lt;ServiceController&gt;(); switch (SearchOption) { case SearchOption.Equals: if (SearchServiceBy == SearchServiceBy.ServiceName) { resultList = allServices.Where(s =&gt; s.ServiceName.Equals(SearchString)).ToList(); } else if (SearchServiceBy == SearchServiceBy.DisplayName) { resultList = allServices.Where(s =&gt; s.DisplayName.Equals(SearchString)).ToList(); } break; case SearchOption.Contains: if (SearchServiceBy == SearchServiceBy.ServiceName) { resultList = allServices.Where(s =&gt; s.ServiceName.Contains(SearchString)).ToList(); } else if (SearchServiceBy == SearchServiceBy.DisplayName) { resultList = allServices.Where(s =&gt; s.DisplayName.Contains(SearchString)).ToList(); } break; case SearchOption.StartsWith: if (SearchServiceBy == SearchServiceBy.ServiceName) { resultList = allServices.Where(s =&gt; s.ServiceName.StartsWith(SearchString)).ToList(); } else if (SearchServiceBy == SearchServiceBy.DisplayName) { resultList = allServices.Where(s =&gt; s.DisplayName.StartsWith(SearchString)).ToList(); } break; case SearchOption.EndsWith: if (SearchServiceBy == SearchServiceBy.ServiceName) { resultList = allServices.Where(s =&gt; s.ServiceName.EndsWith(SearchString)).ToList(); } else if (SearchServiceBy == SearchServiceBy.DisplayName) { resultList = allServices.Where(s =&gt; s.DisplayName.EndsWith(SearchString)).ToList(); } break; case SearchOption.Regex: var pattern = new Regex(SearchString); if (SearchServiceBy == SearchServiceBy.ServiceName) { resultList = allServices.Where(s =&gt; pattern.IsMatch(s.ServiceName)).ToList(); } else if (SearchServiceBy == SearchServiceBy.DisplayName) { resultList = allServices.Where(s =&gt; pattern.IsMatch(s.DisplayName)).ToList(); } break; default: throw new ArgumentException("Unknown SearchOption: {0}", SearchOption.ToString()); } if (SearchServiceType == SearchServiceType.SingleService &amp;&amp; resultList.Count &gt; 1) { resultList = new List&lt;ServiceController&gt; { resultList.FirstOrDefault() }; } return resultList; } </code></pre> <p>Is there any better way to implement this?</p> <p>There is no additional complex logic around the method invoke. The use case is simple: Wix Toolset Custom Action passes required parameters to the method, gets a list of services match the given criteria. So these services could be started/stopped further.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T11:27:09.847", "Id": "385059", "Score": "2", "body": "I think you would get some more useful help if you could include the entire class rather than only a single method. We then could see how this method is used in context." }, ...
[ { "body": "<p>These are my suggestions:</p>\n\n<ul>\n<li>Get rid of all the ugly and duplicate <code>if</code>s by replacing them with two dictionaries where each one returns a <code>Func</code>.</li>\n<li>Use <code>Regex</code> for all searching criteria by creating appropriate patterns or returning the <code>...
{ "AcceptedAnswerId": "200118", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T09:53:16.947", "Id": "200096", "Score": "4", "Tags": [ "c#", "linq", "windows" ], "Title": "Find a list of Windows Services by given criteria" }
200096
a Windows service is a computer program that operates in the background.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T11:21:07.623", "Id": "200099", "Score": "0", "Tags": null, "Title": null }
200099
<p>I'm currently trying to build a in-memory read model on application startup. Therefor I use an event store that returns the event data as json. In my read model class there are handler methods for different event types that populate the read model.</p> <p>For this I use the following parts:</p> <p>Event interfaces that inherit a common IEvent interface. The events should only be messages without any logic on them.</p> <pre><code>public interface IEvent {} public interface ISpecificEvent : IEvent { /* ... */} public interface IOtherSpecificEvent : IEvent { /* ... */} </code></pre> <p>A serializer that converts the json to the actual types (depending on contents in the json data)</p> <pre><code>public interface IEventSerializer { IEvent Deserialize(TypeThatContainsJsonEventData e); } </code></pre> <p>And a ReadModel class that contains <code>Consume</code> methods for the specific event types.</p> <pre><code>public class ReadModel { private readonly IEventSerializer _eventSerializer; public ReadModel(IEventSerializer eventSerializer) { _eventSerializer = eventSerializer ?? throw new ArgumentNullException(nameof(eventSerializer)); } private void Consume(ISpecificEvent e) { if (e == null) return; // actual event handling - building the model Console.WriteLine("Consumed specific event."); } private void Consume(IOtherSpecificEvent e) { if (e == null) return; // actual event handling - building the model Console.WriteLine("Consumed other specific event."); } } </code></pre> <p>Now when I come to how to dispatch the events to the consume methods I came up with three different options. The signature of the <code>DispatchEvents</code> methods are required by the third party library that is responsible to forward the events from the event store to my code. Simplified it looks like <code>EventStore.ReadEventsFromStream("streamName", e =&gt; DispatchEvents(e))</code></p> <p><strong>Option 1</strong></p> <pre><code>// dispatches events to the appropriate Consume method by first determening the // actual type and performs a cast for it public void DispatchEvents(TypeThatContainsJsonEventData e) { var deserializedEvent = _eventSerializer.Deserialize(e); if (deserializedEvent is ISpecificEvent) Consume((ISpecificEvent) deserializedEvent); if (deserializedEvent is IOtherSpecificEvent) Consume((IOtherSpecificEvent) deserializedEvent); } </code></pre> <p><strong>Option 2</strong></p> <pre><code>// dispatches events by attempting a cast to a specific type. // Requires null check in the Consume methods public void DispatchEvents(TypeThatContainsJsonEventData e) { var deserializedEvent = _eventSerializer.Deserialize(e); Consume(deserializedEvent as ISpecificEvent); Consume(deserializedEvent as IOtherSpecificEvent); } </code></pre> <p><strong>Option 3</strong></p> <pre><code>// dispatch events by using a dynamic type public void DispatchEvents(TypeThatContainsJsonEventData e) { dynamic deserializedEvent = _eventSerializer.Deserialize(e); Consume(deserializedEvent); } </code></pre> <p>Which of the options above options would you consider the best and why? Do you have another suggestion on how to do it - preferably without having to put logic in the event classes? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T12:24:59.850", "Id": "385065", "Score": "0", "body": "I think that in option 3, it's the model consuming the event that would have to be `dynamic`, so that you can call `Consume` dynamically, i.e. do a late bound call that would be ...
[ { "body": "<p>A way to avoid the if-else chains is to use double dispatch. Let the event data call the right <code>Consume</code> method of the event consumer. For this to work, the consumer methods need to be known to the event data. We can declare an interface for this:</p>\n\n<pre><code>public interface ICon...
{ "AcceptedAnswerId": "200104", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T12:08:38.690", "Id": "200101", "Score": "-2", "Tags": [ "c#", "comparative-review" ], "Title": "Forward call to method depending on runtime type" }
200101
<p>I am creating a project which will respond to collect multiple bean object, save it to the database and return the status of the transaction. There can be multiple objects that can be sent from the client. For each object, they are having separate database thus separate controller.</p> <p>So I planned to create a framework that can accept multiple objects from multiple controllers and send only one centralized object. Below is my code:</p> <p>Controller:</p> <pre><code>@RestController @RequestMapping("/stat/player") public class PlayerController { @Autowired private StatService&lt;PlayerValue&gt; statPlayer; @RequestMapping("/number/{number}") public Object findByNumber(@PathVariable String number) { // Here returning Object seem odd return statPlayer.findByNumber(number); } } </code></pre> <p>Service:</p> <pre><code>@Service @Transactional(isolation = Isolation.READ_COMMITTED) public class PlayerServiceImpl implements StatService&lt;PlayerValue&gt; { @Autowired private PlayerRepository repository; @Override public PlayerValue findByNumber(String number) { Optional&lt;PlayerEntity&gt; numberValue = repository.findByNumber(number); return numberValue.map(PlayerEntity::toValue).orElse(null); } } </code></pre> <p>In service I returned the <code>PlayerValue</code> object but I want to wrap this object into a centralized bean ResponseValue. I created an aspect for that</p> <pre><code>@Aspect @Component public class Converter { private static final Logger LOG = LoggerFactory.getLogger(Converter.class); @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)") public void restControllerClassMethod() {} private &lt;T&gt; ResponseValue&lt;T&gt; convert(List&lt;T&gt; results) { String message = results.isEmpty() ? "No result found" : ResponseValueStatus.OK.toString(); return new ResponseValue&lt;&gt;(ResponseValueStatus.OK, message, results); } @Around("restControllerClassMethod()") @SuppressWarnings("unchecked") public &lt;T&gt; ResponseValue&lt;T&gt; convert(ProceedingJoinPoint joinPoint) { ResponseValue value; try { Object findObject = joinPoint.proceed(); List&lt;Object&gt; objects = toList(findObject); value = convert(objects); } catch (NullPointerException e) { throw new StatException(String.format("Exception thrown from %s from %s method with parameter %s", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), joinPoint.getArgs()[0].toString())); //this exception will go in a controller advice and create a response value with this message } catch (Throwable e) { LOG.error("Exception occurred while converting the object", e); throw new StatException(String.format("Exception thrown from %s from %s method with parameter %s with exception message %s", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), joinPoint.getArgs()[0].toString(), e.getMessage())); } return value; } private List&lt;Object&gt; toList(Object findObject) { List&lt;Object&gt; objects = new ArrayList&lt;&gt;(); if (findObject instanceof List) { ((List) findObject).forEach(item -&gt; objects.add(findObject)); } else { objects.add(findObject); } return objects; } } </code></pre> <p>To sum up, There could be multiple entities similar to PlayerValue. I need a way to return the result in a centralized bean. Above process work, BUT for this, I have to give return type as <code>Object</code> in <code>Controller</code>. Does anybody have a design idea how can I use return type as List or T in the controller? Also, I know it can be done by implementing a <code>ValueConverter</code> interface, but this conversion is straightforward. So it would be nice if any other developer doesn't have to implement the <code>ValueConverter</code> everytime he wants to add a different controller.</p> <p>Also feel free to review the implementation and let me know if anyone has some alternative idea or some comments.</p> <p><strong>Note:</strong> I reduce a lot of code in the question so that it can be easier to understand without understanding the actual requirement context. Please do let me know if anyone needs more info.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T13:43:58.107", "Id": "385075", "Score": "0", "body": "You will have a hard time finding out where a NPE happened with the code above. You should always chain exceptions or log them, when you have to throw a new exception (plus some ...
[ { "body": "<p>It seems you're trying to turn Java into REST - i.e. you'd like to strip the types of your results so you can return anything.</p>\n\n<p>If you do that, <code>Object</code> is the common base class unless you introduce a <a href=\"https://en.wikipedia.org/wiki/Marker_interface_pattern\" rel=\"nofo...
{ "AcceptedAnswerId": "200107", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T12:41:34.590", "Id": "200103", "Score": "0", "Tags": [ "java", "design-patterns", "spring" ], "Title": "Convert automatically into a centralized bean for multiple domain objects" }
200103
<p>In some of my <a href="http://docs.peewee-orm.com/en/latest/" rel="nofollow noreferrer">peewee</a>-based ORM models, I need to access the instance as well as the respective class. Since I caught myself always repeating the line <code>cls = self.__class__</code> at the top of each such methods, I wrote a decorator for that:</p> <pre><code>def with_class(function): """Adds the instance's class as second parameter to the wrapped function. """ @wraps(function) def wrapper(self, *args, **kwargs): """Wraps the given function.""" return function(self, self.__class__, *args, **kwargs) return wrapper </code></pre> <p><strong>Example use case:</strong></p> <pre><code>class Location(_TerminalModel): """Location of a terminal.""" address = CascadingFKField(Address, column_name='address') annotation = CharField(255, null=True) … @with_class def save_unique(self, cls, *args, **kwargs): """Saves the location if it is new or returns the appropriate existing record. """ if self.annotation is None: annotation_selector = cls.annotation &gt;&gt; None else: annotation_selector = cls.annotation == self.annotation try: return cls.get((cls.address == self.address) &amp; annotation_selector) except cls.DoesNotExist: self.save(*args, **kwargs) return self </code></pre> <p>I'd like to have critique on this solution and am open to alternatives.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T13:19:10.843", "Id": "385071", "Score": "3", "body": "So, you saved typing a single line at the expense of typing a single line? :-\\" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T13:26:28.363", ...
[ { "body": "<p>I'd recommend not using <code>value.__class__</code>. This is as <a href=\"https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes\" rel=\"nofollow noreferrer\">it's not guaranteed to return the type</a>.</p>\n\n<blockquote>\n <p><code>type(x)</code> is typically the same...
{ "AcceptedAnswerId": "200109", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T12:59:31.123", "Id": "200105", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Decorator to pass instance and class to method" }
200105
<p>When writing asynchronous code in F#, one often needs to call methods in the .NET BCL that return <code>Task</code> or <code>Task&lt;T&gt;</code> rather than the F# native <code>Async&lt;'a&gt;</code> type. While the <code>Async.AwaitTask</code> function can convert a <code>Task&lt;T&gt; into an Async&lt;'a&gt;</code>, there is some cognitive overhead in having to keep track of which functions return <code>Task&lt;T&gt;</code> and which functions are <code>Async</code>. The <code>TaskBuilder.fs</code> library can help with this when using only <code>Task&lt;T&gt;</code> returning functions, but it has the same limitation in requring any <code>Async&lt;'a&gt;</code> values to be converted to Tasks with a function like <code>Async.StartAsTask</code>. </p> <p>To simplify this interoperability, I created a new <code>await</code> computation expression that supports using both <code>Async&lt;'a&gt;</code> and <code>Task</code> or <code>Task&lt;T&gt;</code> inside it. This works by overloading the <code>Bind</code>, <code>ReturnFrom</code>, <code>Combine</code>, and <code>Using</code> methods on the <code>AwaitableBuilder</code> Computation Builder to handle <code>Async&lt;'a&gt;</code>, <code>Task</code>, and <code>Task&lt;T&gt;</code>. I haven't seen many computation builders that overload the methods to support different types, so if this is a bad idea, let me know. Also let me know if there's anything I missed in terms of supporting the interop for <code>Task</code> and <code>Async</code>.</p> <pre><code>open System open System.Threading open System.Threading.Tasks /// A standard representation of an awaitable action, such as an F# Async Workflow or a .NET Task [&lt;Struct&gt;] type Awaitable&lt;'a&gt; = | AsyncWorkflow of async: Async&lt;'a&gt; | DotNetTask of task: Task&lt;'a&gt; [&lt;CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)&gt;] module Awaitable = let private await f g = function | AsyncWorkflow a -&gt; f a | DotNetTask t -&gt; g t /// Convert an F# Async Workflow to an Awaitable let ofAsync = AsyncWorkflow /// Convert a .NET Event into an Awaitable let ofEvent event = Async.AwaitEvent event |&gt; AsyncWorkflow /// Convert a .NET Task&lt;T&gt; into an Awaitable let ofTask = DotNetTask /// Convert a .NET Task into an Awaitable let ofUnitTask (t: Task) = t.ContinueWith(fun (task: Task) -&gt; let tcs = TaskCompletionSource&lt;unit&gt;() if task.Status = TaskStatus.Canceled then tcs.SetCanceled() elif task.Status = TaskStatus.Faulted then tcs.SetException(task.Exception) else tcs.SetResult() tcs.Task).Unwrap() |&gt; DotNetTask /// Start an Awaitable, if it is not already running let start = await Async.Start &lt;| fun t -&gt; if t.Status = TaskStatus.Created then t.Start() /// Create an Awaitable that will sleep for the specified amount of time let sleep = Async.Sleep &gt;&gt; AsyncWorkflow /// Convert an Awaitable into an F# Async Workflow let toAsync&lt;'a&gt; : Awaitable&lt;'a&gt; -&gt; Async&lt;'a&gt; = await id Async.AwaitTask /// Convert an Awaitable into a .NET Task&lt;T&gt; let toTask&lt;'a&gt; : Awaitable&lt;'a&gt; -&gt; Task&lt;'a&gt; = await Async.StartAsTask id /// Construct an Awaitable from an existing value let value&lt;'a&gt; : 'a -&gt; Awaitable&lt;'a&gt; = async.Return &gt;&gt; AsyncWorkflow /// Synchronously wait for the Awaitable to complete and return the result let wait&lt;'a&gt; : Awaitable&lt;'a&gt; -&gt; 'a = await Async.RunSynchronously &lt;| fun t -&gt; t.RunSynchronously(); t.Result /// Run a set of Awaitables in parallel and create a single Awaitable that returns all of the resutls in an array let Parallel&lt;'a&gt; : Awaitable&lt;'a&gt; seq -&gt; Awaitable&lt;'a []&gt; = Seq.map toAsync &gt;&gt; Async.Parallel &gt;&gt; AsyncWorkflow /// Monadic bind, extract the value from inside an Awaitable and pass it to the given function let bind f = function | AsyncWorkflow a -&gt; async.Bind(a, f &gt;&gt; toAsync) |&gt; AsyncWorkflow | DotNetTask t -&gt; t.ContinueWith(fun (c: Task&lt;_&gt;) -&gt; (c.Result |&gt; f |&gt; toTask)).Unwrap() |&gt; DotNetTask /// Delay the evaluation of the given function, wrapping it in an Awaitable let delay f = bind f (value ()) /// Combine an Awaitable&lt;unit&gt; with an Awaitable&lt;'a&gt;, /// running them sequentially and returning an Awaitable&lt;'a&gt; let combine a b = bind (fun () -&gt; b) a /// Evaluate an Awaitable&lt;'a&gt; until the guard condition returns false let rec doWhile guard a = if guard () then bind (fun () -&gt; doWhile guard a) a else Task.FromResult() |&gt; DotNetTask /// Try to evaluate the given Awaitable function, then unconditionally run the `finally` let tryFinally fin (f: unit -&gt; Awaitable&lt;_&gt;) = async.TryFinally(f() |&gt; toAsync, fin) |&gt; AsyncWorkflow /// Try to evaluate the given Awaitable function, running the `catch` if an exception is thrown let tryCatch catch (f: unit -&gt; Awaitable&lt;_&gt;) = async.TryWith(f() |&gt; toAsync, catch &gt;&gt; toAsync) |&gt; AsyncWorkflow /// Scope the given IDisposable resource to the Awaitable function, /// disposing the resource when the Awaitable has completed let using (a: 'a :&gt; IDisposable) (f: 'a -&gt; Awaitable&lt;_&gt;) = let dispose = let mutable flag = 0 fun () -&gt; if Interlocked.CompareExchange(&amp;flag, 1, 0) = 0 &amp;&amp; a |&gt; box |&gt; isNull |&gt; not then (a :&gt; IDisposable).Dispose() tryFinally dispose (fun () -&gt; bind f (value a)) /// Evaluate the given Awaitable function for each element in the sequence let forEach (items: _ seq) f = using (items.GetEnumerator()) (fun e -&gt; doWhile (fun () -&gt; e.MoveNext()) (delay &lt;| fun () -&gt; f e.Current)) /// Ignore the result of an Awaitable&lt;'a&gt; and return an Awaitable&lt;unit&gt; let ignore&lt;'a&gt; : Awaitable&lt;'a&gt; -&gt; Awaitable&lt;unit&gt; = bind (ignore &gt;&gt; value) type AwaitableBuilder () = member inline __.Bind (x, f) = Awaitable.bind f x member inline __.Bind (a, f) = a |&gt; AsyncWorkflow |&gt; Awaitable.bind f member inline __.Bind (t, f) = t |&gt; DotNetTask |&gt; Awaitable.bind f member inline __.Delay f = Awaitable.delay f member inline __.Return x = Awaitable.value x member inline __.ReturnFrom (x: Awaitable&lt;_&gt;) = x member inline __.ReturnFrom a = a |&gt; AsyncWorkflow member inline __.ReturnFrom t = t |&gt; DotNetTask member inline __.Zero () = async.Return() |&gt; AsyncWorkflow member inline __.Combine (a, b) = Awaitable.combine a b member inline __.Combine (a, b) = Awaitable.combine (AsyncWorkflow a) b member inline __.Combine (a, b) = Awaitable.combine (DotNetTask a) b member inline __.While (g, a) = Awaitable.doWhile g a member inline __.For (s, f) = Awaitable.forEach s f member inline __.TryWith (f, c) = Awaitable.tryCatch c f member inline __.TryFinally (f, fin) = Awaitable.tryFinally fin f member inline __.Using (d, f) = Awaitable.using d f member inline __.Using (d, f) = Awaitable.using d (f &gt;&gt; AsyncWorkflow) member inline __.Using (d, f) = Awaitable.using d (f &gt;&gt; DotNetTask) [&lt;AutoOpen&gt;] [&lt;CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)&gt;] module AwaitableBuilder = let await = AwaitableBuilder() </code></pre> <p>Here's an example of using the new computation expression to bind both <code>Task</code> and<code>Async</code> values. </p> <pre><code>// Example Usage: let awaitable = await { let! asyncValue = async.Return(3) let! taskValue = Task.Run(fun () -&gt; 5) return! async { return asyncValue * taskValue } } printfn "Awaitable Result: %d" (awaitable |&gt; Awaitable.wait) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T13:40:51.423", "Id": "385074", "Score": "0", "body": "It may seem that you've removed the cognitive overhead, but that's an illusion. You will find, over time, that you still need to keep track of which is which." } ]
[ { "body": "<p>This is a nice idea, and I'm only going to comment on some of the generic bits of the F#:</p>\n\n<blockquote>\n<pre><code>if task.Status = TaskStatus.Canceled\nthen tcs.SetCanceled()\nelif task.Status = TaskStatus.Faulted\nthen tcs.SetException(task.Exception)\nelse tcs.SetResult()\n</code></pre>\...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T13:16:22.587", "Id": "200106", "Score": "5", "Tags": [ "asynchronous", "f#", "async-await", "task-parallel-library" ], "Title": "Async/Await Computation Expression" }
200106
<p>I have put together some code that creates a tree structure from a large list of nodes (entities) and connections and am looking to speed it up.</p> <p><strong>HierarchyWorker:</strong> Converts the list data into the tree</p> <pre><code>public class HierarchyWorker { public List&lt;int&gt; EntityIDs; public ILookup&lt;int, HierarchyConnection&gt; Connections; public Dictionary&lt;int, HierarchyNode&gt; Hierarchies; public void Initialise(List&lt;int&gt; entityIDs, ILookup&lt;int, HierarchyConnection&gt; connections) { EntityIDs = entityIDs; Connections = connections; Hierarchies = new Dictionary&lt;int, HierarchyNode&gt;(); AddAllEntityHierarchies(); } public void AddAllEntityHierarchies() { foreach (var entityId in EntityIDs) { if (!Hierarchies.ContainsKey(entityId)) { AddHierarchy(entityId); } } } public void AddHierarchy(int sourceEntityId) { var node = new HierarchyNode() { EntityID = sourceEntityId, IsController = true, IsOwner = true, ParentNode = null, ChildNodes = new List&lt;HierarchyNode&gt;() }; Hierarchies.Add(sourceEntityId, node); AddChildren(node); } public void AddChildren(HierarchyNode parent) { var connections = Connections[parent.EntityID].ToList(); foreach (var entity in connections) { if (!parent.WouldCauseInfiniteLoop(entity.EntityID)) { if (Hierarchies.ContainsKey(entity.EntityID)) { var node = new HierarchyNode(Hierarchies[entity.EntityID]) { ParentNode = parent, IsController = entity.IsControllerOfParent, IsOwner = entity.IsOwnerOfParent }; parent.ChildNodes.Add(node); } else { var node = new HierarchyNode() { EntityID = entity.EntityID, IsController = entity.IsControllerOfParent, IsOwner = entity.IsOwnerOfParent, ParentNode = parent, ChildNodes = new List&lt;HierarchyNode&gt;() }; parent.ChildNodes.Add(node); AddChildren(node); if (!Hierarchies.ContainsKey(node.EntityID)) { var newNode = new HierarchyNode(node) { ParentNode = null, IsController = true, IsOwner = true }; Hierarchies.Add(newNode.EntityID, newNode); } } } } } } </code></pre> <p><strong>HierarchyNode:</strong> Models each node and provides methods for certain checks</p> <pre><code>public class HierarchyNode { public int EntityID { get; set; } public HierarchyNode ParentNode { get; set; } public List&lt;HierarchyNode&gt; ChildNodes { get; set; } public bool IsOwner { get; set; } public bool IsController { get; set; } public HierarchyNode() { } public HierarchyNode(HierarchyNode copyFrom) { EntityID = copyFrom.EntityID; ChildNodes = copyFrom.ChildNodes; } public HierarchyNode GetSourceNode() { if (ParentNode == null) { return this; } else { return GetSourceNode(ParentNode); } } private HierarchyNode GetSourceNode(HierarchyNode node) { if (node.ParentNode == null) { return node; } else { return GetSourceNode(node.ParentNode); } } public int GetLevel() { var level = 0; if (ParentNode == null) { return level; } else { level++; return GetLevel(level, ParentNode); } } private int GetLevel(int level, HierarchyNode node) { if (node.ParentNode == null) { return level; } else { level++; return GetLevel(level, node.ParentNode); } } public bool WouldCauseInfiniteLoop(int entityId) { if (ParentNode == null) { return EntityID == entityId; } else { return WouldCauseInfiniteLoop(ParentNode, entityId); } } private bool WouldCauseInfiniteLoop(HierarchyNode node, int entityId) { if (node.EntityID == entityId) { return true; } if (node.ParentNode == null) { return false; } return WouldCauseInfiniteLoop(node.ParentNode, entityId); } public bool IsUnbrokenOwner() { if (ParentNode == null) { return IsOwner; } if (!IsOwner) { return false; } return IsUnbrokenOwner(ParentNode); } private bool IsUnbrokenOwner(HierarchyNode node) { if (node.ParentNode == null) { return IsOwner; } if (!node.IsOwner) { return false; } return IsUnbrokenOwner(node.ParentNode); } public bool IsUnbrokenController() { if (ParentNode == null) { return IsController; } if (!IsController) { return false; } return IsUnbrokenController(ParentNode); } private bool IsUnbrokenController(HierarchyNode node) { if (node.ParentNode == null) { return IsController; } if (!node.IsController) { return false; } return IsUnbrokenController(node.ParentNode); } } </code></pre> <p><strong>HierarchyConnection</strong> Models the connection</p> <pre><code>public class HierarchyConnection { public int EntityID { get; set; } public int ParentID { get; set; } public bool IsOwnerOfParent { get; set; } public bool IsControllerOfParent { get; set; } } </code></pre> <p><strong>Console Program</strong> Generates some sample data (1000 sets of 100 level deep trees) and times how long the Initialise takes.</p> <pre><code>class Program { static void Main(string[] args) { var entityIDs = Enumerable.Range(1, 100000).ToList(); var connections = new List&lt;HierarchyConnection&gt;(); for (int i = 0; i &lt; 1000; i++) { connections.AddRange(entityIDs.Skip((i * 100) + 1).Take(99).Select(x =&gt; new HierarchyConnection() { EntityID = x, ParentID = x - 1, IsControllerOfParent = true, IsOwnerOfParent = true })); } var hierarchyWorker = new HierarchyWorker(); var stopwatch = new Stopwatch(); stopwatch.Start(); hierarchyWorker.Initialise(entityIDs, connections.ToLookup(x =&gt; x.ParentID)); stopwatch.Stop(); Console.WriteLine($"Complete in {stopwatch.ElapsedMilliseconds} milliseconds"); Console.ReadLine(); } } </code></pre> <p>A few notes:</p> <ul> <li>There are some references to dataWorkers in the HierarchyWorker class, those are outside of the scope of this review.</li> <li>The connections represent an "entity" that is an owner or a controller of another entity.</li> <li>Unfortunately our data isn't in the best place and we have instances where infinite loops are caused (e.g. a is owner of b, b is owner of c and c is owner of a). There is a method on the HierarchyNode class that detects whether adding a child would cause an infinite loop.</li> <li>One of the requirements is finding "unbroken" chains of ownership or control. I.e. in the structure of A > owner > B > controller > c > owner > D, the ownership chain would only be A > B.</li> <li>The code creates one hierarchy per entity in order to be able to see the structure for a given entity easily at any time.</li> </ul> <p>I am mostly interested in <strong>performance improvements</strong> (but welcome any comments), I have managed to get HierarchyWorker.Initialise to run in about <del>30</del> 0.5 (I have edited the question with some improvements) seconds on our <em>real</em> dataset but I am sure there are more improvements to be made.</p> <p>The data set I am working with involves about 30,000 entities and 125,000 connections. (I am not sure if providing this data would be helpful, if it would be what would be the best way/format to upload the data?)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T14:39:34.380", "Id": "385086", "Score": "1", "body": "You don't have to provide all this test data - this would be really to much - but it would be great if you could put another couple of lines together and add a small example with...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T14:18:40.547", "Id": "200110", "Score": "3", "Tags": [ "c#", "performance", "recursion" ], "Title": "Creating a series of relationship hierarchies from a list of nodes and connections" }
200110
<p>After searching and reading some threads <sup>(<a href="https://stackoverflow.com/a/15561324">1</a>, <a href="https://stackoverflow.com/a/17171810">2</a>, <a href="https://stackoverflow.com/q/12804488">3</a>, <a href="http://www.vbforums.com/showthread.php?503784" rel="nofollow noreferrer">4</a> and <a href="https://stackoverflow.com/q/10351250">5</a>)</sup> on how to split a big file into smaller ones and then merge them back into the original one I made the following VB.NET code on an empty project with module Module1 and reference to System.Windows.Forms:</p> <pre class="lang-vb prettyprint-override"><code>' &lt;Summary&gt; ' ' 3 files: 1; 2; 3 ' 1 has data ' 2 and 3 are empty ' ' How to split file 1 into files 2 and 3: ' remove 2º comment (leave 1º comment) ' run program (select file 1 in the 1º file system prompt and file 2 in the 2º file system prompt) ' add 2º comment back and remove 1º comment ' run program (select file 1 in the 1º file system prompt and file 3 in the 2º file system prompt) ' ' How to join/merge files 2 and 3 into file 1: ' leave both 1º and 2º comments commented ' run program (select file 3 in the 1º file system prompt and file 2 in the 2º file system prompt) ' file 2 will be the merge of files 2 and 3 (same as file 1) ' ' &lt;/Summary&gt; Imports System.IO Module Module1 Sub Main() With New Windows.Forms.OpenFileDialog() .ShowDialog() Dim inputStream As FileStream = New FileStream(.FileName(), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite) .ShowDialog() Dim outputStream As FileStream = New FileStream(.FileName(), FileMode.Append, FileAccess.Write, FileShare.ReadWrite) 'inputStream.Position = inputStream.Length \ 2 - inputStream.Length \ 2 Mod 10000 Dim buffer As Byte() = New Byte(9999) {} Dim bytesRead As Integer bytesRead = inputStream.Read(buffer, 0, buffer.Length) While bytesRead &gt; 0 'And inputStream.Position &lt;= inputStream.Length \ 2 outputStream.Write(buffer, 0, bytesRead) bytesRead = inputStream.Read(buffer, 0, buffer.Length) End While outputStream.Flush() inputStream.Close() outputStream.Close() End With End Sub End Module </code></pre> <p>I'm looking to know if there's any different way to do this with a noticeable performance improvement. The size of the original file is almost 30 GB, which will be split into 2 files, sent online together with the program and then merged back together.</p> <p>Being of that size it takes some time so performance is the focus here, there's no checks of the user's input, no exception/error handling, no pretty code with forms, options and methods/functions. It's just some quick and dirty code.</p>
[]
[ { "body": "<p>I would suggest, to get performance and still keep the original intact, that .net libraries are probably not the best choice. </p>\n\n<p>One suggestion that would work, if you can allow smaller chunks(8GB), is <a href=\"http://7-zip.org/download.html\" rel=\"nofollow noreferrer\">7-Zip</a>. It's...
{ "AcceptedAnswerId": "200224", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:05:09.113", "Id": "200115", "Score": "1", "Tags": [ "performance", "vb.net" ], "Title": "Split a big file into two and then merge back into the original" }
200115
<p>I got the original problem <a href="https://leetcode.com/problems/top-k-frequent-elements/description/" rel="nofollow noreferrer">from Leetcode</a> for top k frequent elements, But I decide to simplify the problem just top 2 elements to make it simpler to solve.</p> <blockquote> <pre><code>// Given an array, return an array of the top 2 most elements. // Input: [1, 2, 3, 4, 5, 3, 4] | Output: [3, 4] // Input: [2, 2, 3, 2, 4, 3, 4] | Output: [2,4] </code></pre> </blockquote> <hr> <pre><code>const topTwoElement = nums =&gt; { const arr = []; nums.forEach(num =&gt; { arr[num] ? arr[num][1]++ : arr[num] = [num, 1]; }); arr.sort((a, b) =&gt; b[1] - a[1]); return [arr[0][0], arr[1][0]]; }; console.log(topTwoElement([3, 2, 3, 4, 5, 3, 4])); //[3,4] console.log(topTwoElement([2, 2, 3, 2, 4, 3, 4])); //[2,4] </code></pre>
[]
[ { "body": "<h1>Avoid the sort</h1>\n<p>You are almost there. But there is room for some improvements</p>\n<h2>Sparse array</h2>\n<p>Using an array to store number frequency works. Javascript will know to create a sparse array, and will sort such arrays using only the elements in it.</p>\n<p>A spare array is an ...
{ "AcceptedAnswerId": "200167", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:07:28.437", "Id": "200116", "Score": "3", "Tags": [ "javascript", "interview-questions" ], "Title": "Top 2 Frequent Elements in JavaScript" }
200116
<p>I got this interview problem from leetcode for top k frequent elements, <a href="https://leetcode.com/problems/top-k-frequent-elements/description/" rel="nofollow noreferrer">https://leetcode.com/problems/top-k-frequent-elements/description/</a> But I decide to simplify the problem just most common elements to make it simpler to solve. If the 3 item has the same frequentcy, then it's okay to return all 3.</p> <pre><code>"""Given an array, return an array of the top 2 most elements. // Input: [1, 2, 3, 4, 5, 3, 4] | Output: [3, 4] // Input: [2, 2, 3, 2, 4, 3, 4] | Output: [2,4]""" import collections def top2Frequent(nums): """ :type nums: List[int] :type k: int :rtype: List[int] """ if len(nums) &lt; 2: return [] freq = {} for num in nums: if num in freq: freq[num] = freq[num] + 1 else: freq[num] = 1 bucket = collections.defaultdict(list) for key in freq: f = freq[key] bucket[f].append(key) res = [] count = len(nums) # the upper limit for res while len(res) &lt; 2: if bucket[count]: res += bucket[count] count -= 1 return res nums = [1, 4, 3, 4, 5, 3, 4] # [4,3] solution = top2Frequent(nums) print(solution) # [4,3] </code></pre> <p><a href="https://gist.github.com/Jeffchiucp/2e733e57476bd697bc430cdf48f6e180" rel="nofollow noreferrer">https://gist.github.com/Jeffchiucp/2e733e57476bd697bc430cdf48f6e180</a></p> <p>I am also tried to solve this problem without using any python library built in collections.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:39:41.993", "Id": "385107", "Score": "3", "body": "I'm confused, you say you don't want to use the built-in collections, but you used `collections.defaultdict`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": ...
[ { "body": "<p>If you're okay with using the built-in collections module, I'd suggest the following. <code>collections.Counter</code> is ideally suited for this and will make the problem trivial.</p>\n\n<pre><code>from collections import Counter\n\n\ndef top_k(numbers, k=2):\n \"\"\"The counter.most_common([k...
{ "AcceptedAnswerId": "200130", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:25:18.563", "Id": "200117", "Score": "1", "Tags": [ "python" ], "Title": "Top 2 most common elements inside array in Python" }
200117
<p>I'm trying to understand how to work with <code>aiohttp</code> and <code>asyncio</code>. The code below retrieves all websites in <code>urls</code> and prints out the "size" of each response.</p> <ul> <li>Is the error handling within the fetch method correct?</li> <li>Is it possible to remove the result of a specific url from <code>results</code> in case of an exception - making <code>return (url, '')</code> unnecessary?</li> <li>Is there a better way than <code>ssl=False</code> to deal with a potential <code>ssl.SSLCertVerificationError</code>?</li> <li>Any additional advice on how i can improve my code quality is highly appreciated</li> </ul> <ul></ul> <pre><code>import asyncio import aiohttp async def fetch(session, url): try: async with session.get(url, ssl=False) as response: return url, await response.text() except aiohttp.client_exceptions.ClientConnectorError as e: print(e) return (url, '') async def main(): tasks = [] urls = [ 'http://www.python.org', 'http://www.jython.org', 'http://www.pypy.org' ] async with aiohttp.ClientSession() as session: while urls: tasks.append(fetch(session, urls.pop())) results = await asyncio.gather(*tasks) [print(f'{url}: {len(result)}') for url, result in results] if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() </code></pre> <p><strong>Update</strong></p> <ul> <li>Is there a way how i can add tasks to the list from within the "loop"? e.g. add new urls while scraping a website and finding new subdomains to scrape.</li> </ul>
[]
[ { "body": "<blockquote>\n<pre><code>tasks = []\nwhile urls:\n tasks.append(fetch(session, urls.pop()))\n</code></pre>\n</blockquote>\n\n<p>can be largely simplified to</p>\n\n<pre><code>tasks = [fetch(session, url) for url in urls]\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Is it possible to remove the res...
{ "AcceptedAnswerId": "200190", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:58:02.780", "Id": "200122", "Score": "4", "Tags": [ "python", "python-3.x", "web-scraping", "asynchronous" ], "Title": "Scraping urls asynchronous including exception handling" }
200122
<p>Note: this is a more specific form of <a href="https://codereview.stackexchange.com/questions/200060/getting-angle-between-all-points-in-array">this</a></p> <p>I am working on a simulation of some virtual creatures. They all have vision that lets them see other creatures. To do this, I calculate the difference between the creature's current heading and the angles to other creatures. Then, I check if the distance between them is close enough so that the creature can see the other. </p> <p>It works, but it is quite slow. This is because it has complexity O(n<sup>2</sup>). It has to loop through the array and apply the angle function to every combination of creatures. Then, it needs to check distance between some of them.</p> <p>My current code:</p> <pre><code>import math import random def getAngle(pos1,pos2): dx=pos2[0]-pos1[0] dy=pos2[1]-pos1[1] rads=math.atan2(dy,dx) rads%=2*math.pi degs=math.degrees(rads) return degs def getDist(pos1, pos2): return math.hypot(pos1[0] - pos2[0], pos1[1] - pos2[1]) def angleDiff(source,target): a = target - source a = (a + 180) % 360 - 180 return a class Creature(object): """A virtual creature""" def __init__(self): self.pos=[random.randint(0,500) for _ in range(2)] #random x,y self.heading=random.randint(0,360) self.vision=[0,0] #left and right relative to creature's perspective creatures=[Creature() for _ in range(100)] creatureFOV=60 #can look 60 degrees left or right creatureViewDist=100 for creature in creatures: for otherC in creatures: if otherC==creature:continue #don't check own angle ang=angleDiff(creature.heading,getAngle(creature.pos,otherC.pos)) if abs(ang) &lt; creatureFOV: if(getDist(creature.pos,otherC.pos)&lt;creatureViewDist): if ang &lt; 0: creature.vision[0]=1 #left side else: creature.vision[1]=1 #right side if sum(creature.vision)==2: break #if there is already something on both sides, stop checking </code></pre> <p>I feel like it could be greatly sped up by using numPy or some other method. <strong>How can this code be optimized for more speed?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T16:10:22.930", "Id": "385115", "Score": "0", "body": "How do you get a creature that is looking from `(0, 0)` to `(1, 0)`, with a FOV of 180? How do you also make a creature that is looking from `(0, 0)` to `(1, 1)` with a FOV of 30...
[ { "body": "<p>In this case, you should divide your world into a 2D grid, where each grid cell is at least as large as your viewing distance. Lets say that the grid has \\$k\\$ cells. Then, in each step of the iteration you place each creature into its appropriate gridcell \\$(O(n))\\$, then for each cell you it...
{ "AcceptedAnswerId": "200152", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T15:58:54.487", "Id": "200123", "Score": "3", "Tags": [ "python", "performance", "computational-geometry" ], "Title": "Checking where/if another creature lies in a creature's field of view" }
200123
<blockquote> <p><a href="https://docplayer.net/57460785-Croatian-open-competition-in-informatics-contest-3-december-8-2007.html" rel="nofollow noreferrer">Croatian Open Competition in Informatics, contest 3, December 8, 2007<br> <strong>4. DEJAVU</strong></a></p> <p>\$N\$ points are placed in the coordinate plane.</p> <p>Write a program that calculates how many ways we can choose three points so that they form a right triangle with legs parallel to the coordinate axes.</p> <p>A right triangle has one 90-degree internal angle. The legs of a right triangle are its two shorter sides.</p> <h2>Input</h2> <p>The first line of input contains the integer \$N\$, the number of points, where \$3 \le N \le 100000\$. </p> <p>Each of the following \$N\$ lines contains two integers \$X\$ and \$Y (1 \le X, Y \le 100000)\$, the coordinates of one point.</p> <p>No points will share the same pair of coordinates.</p> <h2>Output</h2> <p>Output the number of triangles.</p> <h2>Sample input</h2> <pre><code>3 4 2 2 1 1 3 </code></pre> <h2>Sample output</h2> <pre><code>0 </code></pre> </blockquote> <p>This is my solution:</p> <p>For every point, I checked other point. If two points had matching x coordinates and different y coordinates, I looked through the points to find a point with same y coordinate as the new point and different x. If found, I checked if the right angled hypotenus checks out in the three points.</p> <p>Similarly, I repeated a modification of this for two points with matching y coordinates and different x.</p> <p>The program gets the right result, but needs far too long.</p> <pre><code>#include&lt;iostream&gt; #include&lt;cmath&gt; using namespace std; /* double distwithoutroot(int x1, int y1, int x2, int y2) { //cout &lt;&lt; "Got here for values " &lt;&lt; x1 &lt;&lt; y1 &lt;&lt; x2 &lt;&lt; y2 &lt;&lt; endl; int xdist = pow((x2 - x1),2); int ydist = pow((y2 - y1),2); return xdist + ydist; } */ int main() { int noofpoints; int conditionnotsatisfied = 0; cin &gt;&gt; noofpoints; int xs[100000]; int ys[100000]; int count = 0; for (int i = 0; i &lt; noofpoints; i++) { cin &gt;&gt; xs[i] &gt;&gt; ys[i]; } for (int i = 0; i &lt; noofpoints; i++) { int main_x_point = xs[i]; int main_y_point = ys[i]; for (int j = 0; j &lt; noofpoints; j++) { int checkmatchx = xs[j]; int checkmatchy = ys[j]; if (main_x_point == checkmatchx &amp;&amp; main_y_point != checkmatchy) { for (int k = 0; k &lt; noofpoints; k++) { int secondcheckx = xs[k]; int secondchecky = ys[k]; if (checkmatchy == secondchecky &amp;&amp; checkmatchx != secondcheckx) { // int hypotenus = distwithoutroot(main_x_point, main_y_point, secondcheckx, secondchecky); //hypotenus = pow(hypotenus,2); //int perpendicular = distwithoutroot(main_x_point, main_y_point, checkmatchx, checkmatchy); //perpendicular = pow(perpendicular,2); //int base = distwithoutroot(secondcheckx, secondchecky, checkmatchx, checkmatchy); //base = pow(base,2); //if (hypotenus== ( perpendicular+ base )) { count += 1; //cout &lt;&lt; main_x_point &lt;&lt; " " &lt;&lt; main_y_point &lt;&lt; " " &lt;&lt; checkmatchx &lt;&lt; " " &lt;&lt; checkmatchy &lt;&lt; " " &lt;&lt; secondcheckx &lt;&lt; " " &lt;&lt; secondchecky &lt;&lt; endl; //xs[i] = 0; //ys[i] = 0; //} } } } else if (main_y_point == checkmatchy &amp;&amp; main_x_point != checkmatchx) { for (int k = 0; k &lt; noofpoints; k++) { int secondcheckx = xs[k]; int secondchecky = ys[k]; if (checkmatchx == secondcheckx &amp;&amp; checkmatchy != secondchecky) { // int hypotenus = distwithoutroot(main_x_point, main_y_point, secondcheckx, secondchecky); //hypotenus = pow(hypotenus,2); // int base = distwithoutroot(main_x_point, main_y_point, checkmatchx, checkmatchy); //base = pow(base,2); //int perpendicular = distwithoutroot(secondcheckx, secondchecky, checkmatchx, checkmatchy); //perpendicular = pow(perpendicular,2); //if (hypotenus == (perpendicular + base)) { count += 1; //cout &lt;&lt; main_x_point &lt;&lt; " " &lt;&lt; main_y_point &lt;&lt; " " &lt;&lt; checkmatchx &lt;&lt; " " &lt;&lt; checkmatchy &lt;&lt; " " &lt;&lt; secondcheckx &lt;&lt; " " &lt;&lt; secondchecky &lt;&lt; endl; //xs[i] = 0; //ys[i] = 0; // } } } } } } //cout &lt;&lt; "count value after first check " &lt;&lt; count &lt;&lt; endl; //cout &lt;&lt; "Condition not satisfid " &lt;&lt; conditionnotsatisfied &lt;&lt; endl; /* for (int i = 0; i &lt; noofpoints; i++) { int main_x_point = xs[i]; int main_y_point = ys[i]; for (int j = 0; j &lt; noofpoints; j++) { int checkmatchx = xs[j]; int checkmatchy = ys[j]; if (main_y_point == checkmatchy &amp;&amp; main_x_point != checkmatchx) { for (int k = 0; k &lt; noofpoints; k++) { int secondcheckx = xs[k]; int secondchecky = ys[k]; if (checkmatchx == secondcheckx &amp;&amp; checkmatchy != secondchecky) { int hypotenus = distwithoutroot(main_x_point, main_y_point, secondcheckx, secondchecky); //hypotenus = pow(hypotenus,2); int base = distwithoutroot(main_x_point, main_y_point, checkmatchx, checkmatchy); //base = pow(base,2); int perpendicular = distwithoutroot(secondcheckx, secondchecky, checkmatchx, checkmatchy); //perpendicular = pow(perpendicular,2); if (hypotenus == (perpendicular + base)) { count += 1; //cout &lt;&lt; main_x_point &lt;&lt; " " &lt;&lt; main_y_point &lt;&lt; " " &lt;&lt; checkmatchx &lt;&lt; " " &lt;&lt; checkmatchy &lt;&lt; " " &lt;&lt; secondcheckx &lt;&lt; " " &lt;&lt; secondchecky &lt;&lt; endl; //xs[i] = 0; //ys[i] = 0; } } } } } } */ cout &lt;&lt; count/2; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T17:19:43.560", "Id": "385130", "Score": "3", "body": "In addtion to fixing the title... could you tell us which c++ version this is?" } ]
[ { "body": "<h1>Implementation issues</h1>\n\n<ul>\n<li><p><code>using namespace std;</code> is discouraged.</p></li>\n<li><p>Placing such big arrays as <code>xs</code> and <code>ys</code> on the stack can cause stack overflows. For example, on 64-bit Windows their combined size would be \\$2 * 8 * 100000 = 1600...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T16:03:02.890", "Id": "200125", "Score": "7", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded" ], "Title": "Counting ways to choose vertices that form a right triangle" }
200125
<p>I need to read a value from a text file and put it into a predefined type, in this particular case <code>mode_t</code>. This typedef can have a variety of types underlying it, so what is the portable way to read such a value and assign it to a variable of the predefined type.</p> <p>Since you have no idea how large the type is, I was starting under the assumption that you should read using <code>strtoimax</code>/<code>strtoumax</code> and then range check somehow. What I came up with "works" (seemingly) but looks ugly to my eye.</p> <p>For example:</p> <pre><code>static mode_t parse_mode ( const char * s ) { char * e = NULL; uintmax_t u; uintmax_t x; mode_t m; int c; if ( s == NULL) goto error_no_value; if (*s == '\0') goto error_no_value; if (*s == '-' ) goto error_negative; errno = 0; u = strtoumax(s, &amp;e, 8); /* value is in octal */ if (errno) goto error_range; if (e == s) goto error_bogus; c = *e; if (c &amp;&amp; !isspace(c)) goto error_bogus; /* WS after is OK */ /* now the question part -- better way??? */ if (sizeof(mode_t) == 1) x = UINT8_MAX; else if (sizeof(mode_t) == 2) x = UINT16_MAX; else if (sizeof(mode_t) == 4) x = UINT32_MAX; else if (sizeof(mode_t) == 8) x = UINT64_MAX; else goto error_what_size; if (u &gt; x) goto error_too_big; m = (mode_t)u; return m; error_no_value: fprintf(stderr, "Error: no value\n"); return (mode_t)-1; error_negative: fprintf(stderr, "Error: negative\n"); return (mode_t)-1; error_range: fprintf(stderr, "Error: range\n"); return (mode_t)-1; error_bogus: fprintf(stderr, "Error: bogus\n"); return (mode_t)-1; error_what_size:fprintf(stderr, "Error: what size\n"); return (mode_t)-1; error_too_big: fprintf(stderr, "Error: too big\n"); return (mode_t)-1; } </code></pre> <p>[I've totally glossed over the question of whether or not the type is signed or unsigned and just assumed unsigned here]</p> <p>PS, yes, I have "secret knowledge" that no valid mode is likely to exceed 0177777; please ignore that as it is not necessarily true for other predefined types of its ilk.</p> <p>PPS, junk like <code>time_t</code> which might not even be integral is not a part of this question</p> <p><strong>EDIT</strong> Added in the error goop. Also, note that all leading whitespace has been skipped prior to this being called.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T17:22:25.393", "Id": "385131", "Score": "1", "body": "Please post your code unchanged. Now that you omitted some parts the code is not longer valid `c` code and thus off-topic." } ]
[ { "body": "<blockquote>\n<pre><code>/* now the question part -- better way??? */\n if (sizeof(mode_t) == 1) x = UINT8_MAX;\n else if (sizeof(mode_t) == 2) x = UINT16_MAX;\n else if (sizeof(mode_t) == 4) x = UINT32_MAX;\n else if (sizeof(mode_t) == 8) x = UINT64_MAX;\n</code></pre>\n</blockquote>\n\n<p>...
{ "AcceptedAnswerId": "200129", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T16:28:05.790", "Id": "200126", "Score": "3", "Tags": [ "c", "parsing", "integer", "type-safety", "portability" ], "Title": "Safely & portably read a value into a predefined integral type of varying size like mode_t" }
200126
<p>I was doing some preparation for coding interviews and I came across the following question:</p> <blockquote> <p>Given a list of coordinates "x y" return <code>True</code> if there exists a line containing at least 4 of the points (ints), otherwise return <code>False</code>.</p> </blockquote> <p>The only solution I can think about is in \$O(n^2)\$. It consist of calculating the slope between every coordinate: Given that if \$\frac{y_2-y_1}{x_2 –x_1} = \frac{y_3-y_2}{x_3-x_2}\$ then these three points are on the same line. I have been trying to think about a DP solution but haven't been able to think about one. </p> <p>Here is the current code:</p> <pre><code>def points_in_lins(l): length = len(l) for i in range(0,length -1): gradients = {} for j in range(i+1, length): x1, y1 = l[i] x2, y2 = l[j] if x1 == x2: m = float("inf") else: m = float((y2 -y1) / (x2 - x1)) if m in gradients: gradients[m] += 1 if gradients[m] == 3: return(True) else: gradients[m] = 1 return(False) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T19:37:44.140", "Id": "385356", "Score": "0", "body": "Actually, @W.Chang's suggestion of computing the area can indeed work for four points: if the first three points are collinear, try the first two with the fourth. The equation I...
[ { "body": "<h3>General remarks</h3>\n\n<blockquote>\n<pre><code>def points_in_lins(l):\n</code></pre>\n</blockquote>\n\n<p>The function and argument name can be improved. <code>l</code> is too short and does\nnot indicate at all that this is a list of points, and <code>points_in_lins</code>\n(perhaps you meant ...
{ "AcceptedAnswerId": "200234", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T17:52:02.850", "Id": "200136", "Score": "5", "Tags": [ "python", "algorithm", "python-3.x", "computational-geometry" ], "Title": "Given a list of coordinates check if 4 points make a line" }
200136
<p>Problem statement is</p> <blockquote> <p>Write a method that can take an unordered list of airport pairs visited during a trip and return the list in order.</p> <pre><code>{"ITO", "KOA"}, {"SFO", "SEA"}, {"LGA", "CDG"}, {"KOA", "LGA"}, {"PDX", "ITO"}, {"SEA", "PDX"} </code></pre> <p>should return:</p> <pre><code>(SFO,SEA)(SEA,PDX)(PDX,ITO)(ITO,KOA)(KOA,LGA)(LGA,CDG) </code></pre> </blockquote> <p>I have come up with this O(n^2) algorithm. I wanted to know if it can be done better than this:</p> <pre><code>private static void sortPairs(String[][] input) { for (int i = 0; i &lt; input.length; i++) { int j = 1; for (; j &lt; input.length; j++) { if (input[i][0].equals(input[j][1])) { break; } } if (j == input.length) { swapPairs(i, 0, input); break; } } for (int i = 0; i &lt; input.length; i++) { int j = 1; for (; j &lt; input.length; j++) { if (input[i][1].equals(input[j][0])) { break; } } if (j == input.length) { swapPairs(i, input.length - 1, input); break; } } for (int i = 2; i &lt; input.length - 1; i++) { int j = i - 1; for (; j &gt;= 0; j--) { if (input[j + 1][0].equals(input[j][1])) { break; } swapPairs(j, j + 1, input); if (input[j + 1][0].equals(input[j][1])) { break; } } } } private static void swapPairs(int i, int j, String[][] pairs) { String[] temp = pairs[i]; pairs[i] = pairs[j]; pairs[j] = temp; } </code></pre>
[]
[ { "body": "<p>This kind of problem seems like it could benefit from using a link list. This will shorten your code quite a bit and, if I'm not mistaken improve your time complexity quite a bit too:</p>\n\n<pre><code>class Node {\n\n public String[] pair = new String[2];\n public Node next = null;\n\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T18:12:44.903", "Id": "200138", "Score": "5", "Tags": [ "java", "complexity" ], "Title": "List of Ordered pairs from unordered Pair in Java" }
200138
<p><strong>Background Problem</strong></p> <p>Consider a set of students that we want to place into <code>Ng</code> groups each of which contains <code>Ns</code> students. Let's label the students 1, 2, ... , Ng * Ns, and let an <strong>assignment</strong> of students be an array of shape (Ng, Ns) that encodes the groupings of students. For example, if Ng = 2 and Ns = 3, then an assignment of students could be:</p> <p>[[1, 4, 5], [2, 3, 6]]</p> <p>note that any assignment that differs either in permuting students within groups, or in permuting the groups themselves would be considered an <strong>equivalent</strong> assignment. So for the assignment above, one equivalent assignment would be:</p> <p>[[6, 3, 2], [1, 5, 4]]</p> <p>For a given assignment A, we define a <strong>neighboring assignment</strong> as any inequivalent assignment that differs from A by a single swap of students. For example, a neighbor of the first assignment above is obtained by swapping students 1 and 6 to obtain</p> <p>[[1, 3, 2], [6, 5, 4]]</p> <p>Additionally, we have a <strong>fitness function</strong> <code>f</code> that takes an assignment <code>A</code> as its input, and outputs a real number f(A). The goal is to construct a function which I call <code>fitter_neighbor</code> which takes an assignment A and a fitness function f as its inputs and returns a fitter neighboring assignment provided such an assignment exists. If no such assignment exists, then <code>fitter_neighbor</code> should return A. It is not required that <code>fitter_neighbor</code> returns the fittest neighbor, and in fact, the goal is to have it systematically search through the neighbors and return the first fitter neighbor it comes across.</p> <p><strong>Current seemingly-not-very-pythonic code</strong></p> <pre><code>def fitter_neighbor(A, f): Ng = len(A) #number of groups Ns = len(A[0]) #number of students per group Nn = int(Ns ** 2 * Ng * (Ng - 1) / 2) #number of neighboring assignments A_swap = np.copy(A) #initialize copy of assignment to be changed g1 = 0 #group number of person A in swap n_swaps = 0 #counter for number of swaps considered while g1 &lt; Ng and f(A_swap) &lt;= f(A) and n_swaps &lt; Nn: s1 = 0 while s1 &lt; Ns and f(A_swap) &lt;= f(A) and n_swaps &lt; Nn: g2 = g1 + 1 #ensures that no swaps are repeated while g2 &lt; Ng and f(A_swap) &lt;= f(A) and n_swaps &lt; Nn: s2 = 0 while s2 &lt; Ns and f(A_swap) &lt;= f(A) and n_swaps &lt; Nn: A_swap = np.copy(A) A_swap[g1, s1], A_swap[g2, s2] = A_swap[g2, s2], A_swap[g1, s1] n_swaps += 1 s2 += 1 g2 += 1 s1 += 1 g1 += 1 if n_swaps &lt; Nn: return A_swap else: return A </code></pre> <p>Can <code>fitter_neighbor</code> be written in a more pythonic way? In particular, is it possible to eliminate the nested while loops in some clever way?</p> <p>As an example fitness function for the case Ns = 2, consider</p> <pre><code>def f2(A): return np.sum([(g[1] - g[0]) ** 2 for g in A]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T01:33:38.860", "Id": "385203", "Score": "0", "body": "I thinking doing something with sets, will have a look at it today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T01:37:42.983", "Id": "3852...
[ { "body": "<p>Not a solution but a line of thought you may use for implementation. You can define the group of students as sets and then make tuples of these sets, so for example <code>({1, 3, 5}, {2, 4, 6})</code>, let's call this tuple A and another tuple of sets B: <code>(1, 4, 5}, {2, 3, 6})</code> I assume...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T18:57:58.517", "Id": "200141", "Score": "2", "Tags": [ "python", "python-3.x", "formatting", "combinatorics" ], "Title": "Fitter Nearest-Neighbor function with three nested loops" }
200141
<p>This is version 3 of <a href="https://codereview.stackexchange.com/questions/200051/efficiently-counting-rooms-from-a-floorplan">Efficiently counting rooms from a floorplan</a>. Version 2 is here <a href="https://codereview.stackexchange.com/questions/200054/efficiently-counting-rooms-from-a-floorplan-version-2">Efficiently counting rooms from a floorplan (version 2)</a></p> <p>It also has a comprehensive test facility that is the focus of this question.</p> <p>To recap, the problem (<a href="https://cses.fi/problemset/task/1192/" rel="noreferrer">from here</a>) is this: </p> <blockquote> <p>You are given a map of a building, and your task is to count the number of rooms. The size of the map is \$n \times m\$ squares, and each square is either floor or wall. You can walk left, right, up, and down through the floor squares.</p> <h2>Input</h2> <p>The first input line has two integers \$n\$ and \$m\$: the height and width of the map.</p> <p>Then there are \$n\$ lines of \$m\$ characters that describe the map. Each character is <code>.</code> (floor) or <code>#</code> (wall).</p> <h2>Output</h2> <p>Print one integer: the number of rooms.</p> <h2>Constraints</h2> <p>\$1\le n,m \le 2500\$</p> <h2>Example</h2> <h3>Input:</h3> <pre><code>5 8 ######## #..#...# ####.#.# #..#...# ######## </code></pre> <h3>Output:</h3> <p>3</p> </blockquote> <h2>Strategy</h2> <p>It seemed to me to be possible to solve the problem by processing line at a time, so that's what my code does. Specifically, it keeps a tracking <code>std::vector&lt;std::size_t&gt;</code> named <code>tracker</code> that corresponds to the rooms from the previous row and starts with all zeros.</p> <p>As it reads each line of input, it processes the line character at a time. If it's non-empty (that is, if it's a wall), set the corresponding <code>tracker</code> entry to 0. </p> <p>Otherwise, if the previous row (that is, the matching value from the <code>tracker</code> vector) was a room, then this is part of the same room.</p> <p>If the previous character in the same row was a room, this is the same room.</p> <p>The code also has provisions for recognizing that what it "thought" was two rooms turns out to be one room, and adjusts both the <code>tracker</code> vector and increments the <code>merges</code> variable.</p> <h2>Testing</h2> <p>Because there were a number of false starts, I wanted to make sure this one was entirely accurate before posting it. So to that end, I wrote a generic routine that uses a simple flood fill. It's based on a class I named <code>House</code> that reads and stores the entire input. It's simple and reliable, but slow. I use it to verify the inline version that is implemented as a function. Finally,, there is a <code>TestHouse</code> class for testing one against the other of these. Finally, the <code>main</code> test routine generates all possible test cases of the dimensions given on the command line and tests the two routines against each other using multiple tasks if <code>std::thread::hardware_concurrency()</code> returns a value greater than one. It's also assumed in the code that the value returned is a power of 2, which is strictly true for all of my machines, but might not be for yours.</p> <p>Also, I'm aware that the output from the <code>test</code> routine should use a mutex to control access to <code>std::cout</code> but since, in my testing, there isn't any output anyway, I'm not so concerned about it and didn't bother adding it. </p> <h2>Results</h2> <p>I've tested this exhaustively with sizes up to 5x7. All tests pass.</p> <h2>roomtest.cpp</h2> <pre><code>#include "House.h" #include "Rooms.h" #include &lt;sstream&gt; #include &lt;iterator&gt; #include &lt;future&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;cstddef&gt; class TestHouse { public: TestHouse(std::size_t height, std::size_t width, unsigned bits=0, unsigned chunk=0); explicit operator bool() const { return !overflow; } TestHouse&amp; operator++(); friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const TestHouse&amp; t); void test() const; private: static constexpr char wall{'#'}; static constexpr char empty{'.'}; bool increment(std::size_t n); std::size_t height{0}; std::size_t width{0}; std::vector&lt;std::string&gt; floor; bool overflow{false}; unsigned bits{0}; }; TestHouse::TestHouse(std::size_t height, std::size_t width, unsigned bits, unsigned chunk) : height{height}, width{width}, overflow{false}, bits{bits} { floor.reserve(height); std::string line(width, wall); for (auto i{height}; i; --i) { floor.push_back(line); } for ( ; chunk; --chunk) { bool carry{true}; for (auto n{height * width - bits}; carry &amp;&amp; n &lt; height*width; ++n) { carry = increment(n); } } } // increment a single indicated bit and return carry as appropriate bool TestHouse::increment(std::size_t n) { auto row{n / width}; auto col{n % width}; if (floor[row][col] == wall) { floor[row][col] = empty; return false; } floor[row][col] = wall; return true; } // increment as though the entire array were one big binary value TestHouse&amp; TestHouse::operator++() { bool carry{true}; for (std::size_t n{0}; carry &amp;&amp; n &lt; height*width - bits; ++n) { carry = increment(n); } overflow = carry; return *this; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const TestHouse&amp; t) { out &lt;&lt; t.height &lt;&lt; ' ' &lt;&lt; t.width &lt;&lt; '\n'; for (const auto&amp; line : t.floor) { out &lt;&lt; line &lt;&lt; '\n'; } return out; } void TestHouse::test() const { House h{height, width, floor}; auto good = h.rooms(); auto alt{rooms(height, width, floor)}; if (alt != good) { std::cout &lt;&lt; *this &lt;&lt; alt &lt;&lt; " != " &lt;&lt; good &lt;&lt; '\n'; } } void testing(std::size_t height, std::size_t width, unsigned bits, unsigned chunk) { for (TestHouse t{height, width, bits, chunk}; t; ++t) { t.test(); } } int main(int argc, char *argv[]) { if (argc != 3) { std::cerr &lt;&lt; "Usage: roomtest height width\n"; return 1; } auto height{std::stoul(argv[1])}; auto width{std::stoul(argv[2])}; auto n{std::thread::hardware_concurrency()}; if (n &lt; 2) { n = 2; } auto bits{0u}; // note that this assumes that n is a non-zero power of 2 for (auto i{n}; i; i &gt;&gt;= 1) { ++bits; } std::vector&lt;std::future&lt;void&gt;&gt; chunks; for (auto i{n} ; i; --i) { chunks.push_back(std::async(testing, height, width, bits, n-1)); } for (auto&amp; task : chunks) { task.get(); } } </code></pre> <h2>House.h</h2> <pre><code>#ifndef HOUSE_H #define HOUSE_H #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;cstddef&gt; class House { public: House() : height{0}, width{0}, floor{} {} House(std::size_t height, std::size_t width, std::vector&lt;std::string&gt; plan) : height{height}, width{width}, floor{plan} {} friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const House&amp; h); std::size_t rooms(); private: bool flood(std::vector&lt;std::string&gt;&amp; floorplan); void fill(std::size_t row, std::size_t col, std::vector&lt;std::string&gt;&amp; floorplan); static constexpr char empty{'.'}; static constexpr char explored{'x'}; std::size_t height; std::size_t width; std::vector&lt;std::string&gt; floor; }; #endif // HOUSE_H </code></pre> <h2>Rooms.h</h2> <pre><code>#ifndef ROOMS_H #define ROOMS_H #include &lt;cstddef&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; std::size_t rooms(std::size_t height, std::size_t width, const std::vector&lt;std::string&gt;&amp; plan); #endif // ROOMS_H </code></pre> <h2>House.cpp</h2> <pre><code>#include "House.h" std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const House&amp; h) { for (const auto&amp; row : h.floor) { out &lt;&lt; row &lt;&lt; '\n'; } return out; } // given row and column, fills all empty cells // reachable from that room, where 'reachable' means // that a cell is adjacent to an empty cell in one // of the four compass directions void House::fill(std::size_t row, std::size_t col, std::vector&lt;std::string&gt;&amp;f loorplan) { if (row &gt;= height || col &gt;= width || floorplan[row][col] != empty) { return; } floorplan[row][col] = explored; fill(row+1, col, floorplan); fill(row-1, col, floorplan); fill(row, col+1, floorplan); fill(row, col-1, floorplan); } // finds an empty room and floods it // return false if no empty rooms were found bool House::flood(std::vector&lt;std::string&gt;&amp; floorplan) { for (std::size_t i{0}; i &lt; height; ++i) { for (std::size_t j{0}; j &lt; width; ++j) { if (floorplan[i][j] == empty) { fill(i, j, floorplan); return true; } } } return false; } std::size_t House::rooms() { std::size_t rooms{0}; for ( ; flood(floor); ++rooms) { } return rooms; } </code></pre> <h2>Rooms.cpp</h2> <pre><code>#include "Rooms.h" #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; std::size_t rooms(std::size_t height, std::size_t width, const std::vector&lt;std::string&gt;&amp; plan) { std::size_t roomcount{0}; std::size_t merges{0}; static constexpr char empty{'.'}; std::vector&lt;std::size_t&gt; tracker(width, 0); for (const auto&amp; row : plan) { for (std::size_t j{0}; j &lt; width; ++j) { if (row[j] == empty) { // continuation from line above? if (tracker[j]) { // also from left? if (j &amp;&amp; tracker[j-1] &amp;&amp; (tracker[j-1] != tracker[j])) { auto bigger = tracker[j-1]; auto smaller = tracker[j]; // make sure they're in the right order if (bigger &lt; smaller) { std::swap(smaller, bigger); } // rooms have joined std::replace(tracker.begin(), tracker.end(), bigger, smaller); ++merges; } } else { // continuation from left? if (j &amp;&amp; tracker[j-1]) { tracker[j] = tracker[j-1]; } else { tracker[j] = ++roomcount; } } } else { tracker[j] = 0; } } } return roomcount-merges; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T21:05:36.017", "Id": "385178", "Score": "0", "body": "I would suggest to test also with multiple (randomly generated) houses of larger dimensions (20x20, 100x100, ...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDat...
[ { "body": "<p>The swapping</p>\n\n<pre><code>if (bigger &lt; smaller) {\n std::swap(smaller, bigger);\n}\n</code></pre>\n\n<p>if two rooms are merged seems to be unnecessary. The absolute tracker\nvalues are not important, only that they are identical for connected\nfields. Also</p>\n\n<ul>\n<li>Your test su...
{ "AcceptedAnswerId": "200226", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T20:49:25.533", "Id": "200145", "Score": "6", "Tags": [ "c++", "algorithm", "programming-challenge", "c++14", "rags-to-riches" ], "Title": "Multithreaded testing for counting rooms from a floor plan solution" }
200145
<p>The following is a Haskell backend to a K-means visualisation: </p> <p><a href="https://i.stack.imgur.com/uVz4Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uVz4Q.png" alt="enter image description here"></a></p> <p>I have omitted the API code (exists in a separate module), the relevant endpoints simply call <code>initialState</code> to construct a state from parameters (number of clusters, number of centroids), <code>randomState</code> that generates a state with a random number of centroids &amp; clusters, and <code>iterateKmeans</code> which runs the next step of the algorithm.</p> <p><code>./src/Kmeans.hs</code> </p> <pre><code>module Kmeans ( KmeansState , initialState , randomState , iterateKmeans ) where import Data.Aeson.Types import Protolude import Random data Colour = None | White | Black | Grey | Red | Green | Orange | Blue | Purple | Teal deriving (Show, Eq) instance ToJSON Colour where toJSON None = "transparent" toJSON White = "#ecf0f1" toJSON Black = "#2c3e50" toJSON Grey = "#34495e" toJSON Red = "#c13f2b" toJSON Green = "#55af61" toJSON Orange = "#f39c28" toJSON Blue = "#2980b9" toJSON Purple = "#8f50ad" toJSON Teal = "#49a185" data Point = Point { pointR :: Int , pointX :: Int , pointY :: Int , pointFill :: Colour , pointStroke :: Colour } instance ToJSON Point where toJSON (Point r x y fill stroke) = object [ "r" .= r , "x" .= x , "y" .= y , "fill" .= fill , "stroke" .= stroke ] pointDistance :: Point -&gt; Point -&gt; (Int, Int) pointDistance a b = (pointX a - pointX b, pointY a - pointY b) pointCoords :: Point -&gt; (Int, Int) pointCoords Point{..} = (pointX, pointY) movePoint :: (Int, Int) -&gt; Point -&gt; Point movePoint (x', y') (Point r x y fill stroke) = Point r (x + x') (y + y') fill stroke data KmeansState = KmeansState { kmeansStateClusters :: [Point] , kmeansStateCentroids :: [Point] } instance ToJSON KmeansState where toJSON KmeansState{..} = object [ "clusters" .= kmeansStateClusters , "centroids" .= kmeansStateCentroids ] width :: Int width = 1000 height :: Int height = 700 centreX :: Int centreX = width `div` 2 offsetX :: Int offsetX = 3 * (centreX `div` 4) centreY :: Int centreY = height `div` 2 offsetY :: Int offsetY = 3 * (centreY `div` 4) initialState :: MonadIO m =&gt; Int -&gt; Int -&gt; m KmeansState initialState nClusters nCentroids = runRandomT createState =&lt;&lt; seedFromTime where createState = assignClusters &lt;$&gt; generateState generateState = KmeansState &lt;$&gt; (initialClusters nClusters =&lt;&lt; randomR (400, 1200)) &lt;*&gt; initialCentroids initialCentroids = mapM randomCentroid $ take nCentroids centroidColours centroidColours = [ Red , Green , Orange , Blue , Purple , Teal ] randomState :: MonadIO m =&gt; m KmeansState randomState = runRandomT createState =&lt;&lt; seedFromTime where createState = do clusters &lt;- randomR (2, 5) centroids &lt;- randomR (2, 5) initialState clusters centroids initialClusters :: MonadIO m =&gt; Int -&gt; Int -&gt; RandomT m [Point] initialClusters numClusters totalPoints = (&lt;&gt;) &lt;$&gt; noise &lt;*&gt; clusters where perCluster = totalPoints `div` (numClusters + 2) numNoisePoints = totalPoints - (perCluster * numClusters) randomCluster = generateCluster (perCluster - 1) =&lt;&lt; randomPoint clusters = join &lt;$&gt; replicateM numClusters randomCluster noise = replicateM numNoisePoints randomPoint generateCluster :: MonadIO m =&gt; Int -&gt; Point -&gt; RandomT m [Point] generateCluster numPoints pt = generate where generate = if numPoints == 0 then pure [pt] else (:) &lt;$&gt; groupedPoint &lt;*&gt; recurr originX = pointX pt originY = pointY pt spreadX = width `div` numPoints * 3 spreadY = height `div` numPoints * 3 xR = ( max 1 $ originX - spreadX , min width $ originX + spreadX ) yR = ( max 1 $ originY - spreadY , min height $ originY + spreadY ) groupedPoint = Point &lt;$&gt; pure 2 &lt;*&gt; randomR xR &lt;*&gt; randomR yR &lt;*&gt; pure Red &lt;*&gt; pure None recurr = generateCluster (numPoints - 1) pt assignClusters :: KmeansState -&gt; KmeansState assignClusters KmeansState{..} = KmeansState clusters kmeansStateCentroids where clusters = (\pt -&gt; assignColour (nearestColour pt) pt) &lt;$&gt; kmeansStateClusters assignColour fill (Point r x y _ stroke) = Point r x y fill stroke nearestColour pt = pointFill $ minimumBy (compare `on` calcDistance pt) kmeansStateCentroids calcDistance a b = (xs ^ 2) + (ys ^ 2) where (xs, ys) = pointDistance a b iterateKmeans :: KmeansState -&gt; KmeansState iterateKmeans KmeansState{..} = assignClusters $ KmeansState kmeansStateClusters centroids where centroids = (\c -&gt; shiftCentroid (matchingClusters c) c) &lt;$&gt; kmeansStateCentroids matchingClusters c = filter (matchingCluster c) kmeansStateClusters matchingCluster centroid point = pointFill centroid == pointFill point shiftCentroid :: [Point] -&gt; Point -&gt; Point shiftCentroid cluster centroid = maybe centroid (performShift . calculateShift . pointCoords) firstPoint where firstPoint = listToMaybe cluster performShift shift = movePoint shift centroid calculateShift initialCoords = centroidDistance . reduceTuple (length cluster) . foldr takeAverage (0, 0) $ cluster takeAverage point acc = sumTuples acc . pointCoords $ point centroidDistance avg = subTuples avg (pointCoords centroid) reduceTuple n (x, y) = (x `div` n, y `div` n) sumTuples (ax, ay) (bx, by) = (ax + bx, ay + by) subTuples (ax, ay) (bx, by) = (ax - bx, ay - by) randomPoint :: MonadIO m =&gt; RandomT m Point randomPoint = generate where generate = Point &lt;$&gt; pure 2 &lt;*&gt; randomR (centreX - offsetX, centreX + offsetX) &lt;*&gt; randomR (centreY - offsetY, centreY + offsetY) &lt;*&gt; pure None &lt;*&gt; pure None randomCentroid :: MonadIO m =&gt; Colour -&gt; RandomT m Point randomCentroid colour = Point &lt;$&gt; pure 5 &lt;*&gt; randomR (centreX - offsetX, centreX + offsetX) &lt;*&gt; randomR (centreY - offsetY, centreY + offsetY) &lt;*&gt; pure colour &lt;*&gt; pure Black </code></pre> <p><code>./src/Random.hs</code></p> <pre><code>module Random ( RandomT , seedFromTime , runRandomT , random , randomR ) where import Data.Time.Clock.POSIX (getPOSIXTime) import Protolude import qualified System.Random as R import System.Random (Random, StdGen, mkStdGen) type RandomT = StateT StdGen seedFromTime :: MonadIO m =&gt; m StdGen seedFromTime = liftIO $ mkStdGen . round &lt;$&gt; getPOSIXTime runRandomT :: MonadIO m =&gt; RandomT m a -&gt; StdGen -&gt; m a runRandomT = evalStateT random :: (MonadIO m, Random a) =&gt; RandomT m a random = do (n, rand) &lt;- R.random &lt;$&gt; get _ &lt;- put rand pure n randomR :: (MonadIO m, Random a) =&gt; (a, a) -&gt; RandomT m a randomR (from, to) = do (n, rand) &lt;- R.randomR (from, to) &lt;$&gt; get _ &lt;- put rand pure n </code></pre>
[]
[ { "body": "<p><code>initialState</code> and <code>randomState</code> together create two <code>RandomT</code> layers.</p>\n\n<pre><code>import Data.NumInstances\n\ndata Point = Point\n { pointR :: Int\n , pointFill :: Colour\n , pointStroke :: Colour\n , pointXY :: (Int, Int)\n }\n\nrandomState :: MonadIO ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T20:55:56.747", "Id": "200146", "Score": "6", "Tags": [ "haskell", "random", "clustering", "data-visualization" ], "Title": "Haskell K-means implementation" }
200146
<p>I just recently finished going through all of learncpp.com's and Lazy Foo's SDL2 tutorials. This is my first program written outside of the tutorials so I assume there's plenty of room for improvement. Any constructive criticism for what can be improved would be greatly appreciated.</p> <p>The gist of the game is that it generates a random number, and the player must guess what it is. If they guess correctly, they win, if not they are told whether the guess is too high or too low and allowed to guess again for a predetermined amount of guesses.</p> <pre><code>#include &lt;SDL.h&gt; #include &lt;SDL_image.h&gt; #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;SDL_ttf.h&gt; #include &lt;string&gt; const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; SDL_Window* gWindow = NULL; SDL_Renderer* gRenderer = NULL; TTF_Font* gFont; SDL_Color textColor = { 0,0,0 }; const int min = 1; int max; int numberofGuesses; int randomNumber; bool quit = false; bool willPlayAgain = false; int guessCount = 0; bool menuPressed = false; void mainMenu(); int getRandomNumber(int x, int y) { std::random_device rd; std::mt19937 mersenne(rd()); std::uniform_int_distribution&lt;&gt; number(x, y); int rng = number(mersenne); return rng; } class LTexture { public: LTexture(); ~LTexture(); void free(); void loadfromSurface(std::string path); void loadfromText(std::string text, SDL_Color); void render(int x, int y); SDL_Texture * mTexture; int mWidth; int mHeight; SDL_Rect mButton; }; LTexture::LTexture() { mTexture = NULL; mWidth = 0; mHeight = 0; } LTexture::~LTexture() { SDL_DestroyTexture(mTexture); mTexture = NULL; mWidth = 0; mHeight = 0; } void LTexture::loadfromSurface(std::string path) { SDL_Surface *surface = IMG_Load(path.c_str()); mTexture = SDL_CreateTextureFromSurface(gRenderer, surface); mWidth = surface-&gt;w; mHeight = surface-&gt;h; } void LTexture::loadfromText(std::string text, SDL_Color color) { free(); SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(gFont, text.c_str(), color, 250); mTexture = SDL_CreateTextureFromSurface(gRenderer, textSurface); mWidth = textSurface-&gt;w; mHeight = textSurface-&gt;h; SDL_FreeSurface(textSurface); textSurface = NULL; } void LTexture::render(int x, int y) { SDL_Rect destRect = { x, y, mWidth, mHeight }; SDL_RenderCopy(gRenderer, mTexture, NULL, &amp;destRect); //create a rectangle that coincides with texture to check for button presses mButton = { x, y, mWidth, mHeight }; } void LTexture::free() { SDL_DestroyTexture(mTexture); mTexture = NULL; } //declare the Textures I will be using LTexture yesButton; LTexture noButton; LTexture tenButton; LTexture hundredButton; LTexture thousandButton; LTexture highLowTexture; LTexture menuTexture; void buttonPress(SDL_Event &amp;e, SDL_Rect &amp;button, int buttonNum) { int x, y; SDL_GetMouseState(&amp;x, &amp;y); //if mouse is not inside of the button, go back if (x &lt; button.x || x &gt; button.x + button.w || y &lt; button.y || y &gt; button.y + button.h) { return; } else { if (e.type == SDL_MOUSEBUTTONDOWN) { //if yesButton if (buttonNum == 0) { willPlayAgain = true; guessCount = 0; mainMenu(); } //if noButton if (buttonNum == 1) { quit = true; } //if 1-10 Button if (buttonNum == 2) { numberofGuesses = 5; max = 10; menuPressed = true; randomNumber = getRandomNumber(min, max); //used to make sure game works correctly std::cout &lt;&lt; randomNumber; } //if 1-100 Button if (buttonNum == 3) { numberofGuesses = 7; max = 100; menuPressed = true; randomNumber = getRandomNumber(min, max); std::cout &lt;&lt; randomNumber; } //if 1-1000 Button if (buttonNum == 4) { numberofGuesses = 9; max = 1000; menuPressed = true; randomNumber = getRandomNumber(min, max); std::cout &lt;&lt; randomNumber; } } } } int compare(int randomNumber, int guess) { if (randomNumber == guess) { return 0; } //if player has run out of guesses else if (guessCount == numberofGuesses) { return 3; } else if (randomNumber &lt; guess) { return 1; } else if (randomNumber &gt; guess) { return 2; } } void playAgain(int x) { willPlayAgain = false; SDL_Event e; while (!quit &amp;&amp; !willPlayAgain) { while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { quit = true; } buttonPress(e, yesButton.mButton, 0); buttonPress(e, noButton.mButton, 1); } std::string dialogue; if (x == 1) { dialogue = "YOU WON!!! The correct answer was " + std::to_string(randomNumber) + "."; } else { dialogue = "You lose. The correct answer was " + std::to_string(randomNumber) + "."; } SDL_RenderClear(gRenderer); highLowTexture.render(0, 0); LTexture winlose; winlose.loadfromText(dialogue, textColor); winlose.render(335, 70); LTexture playAgain; playAgain.loadfromText("Play again?", textColor); playAgain.render(325, 300); yesButton.render(300, 350); noButton.render(300 + yesButton.mWidth + 10, 350); SDL_RenderPresent(gRenderer); } } void renderScene(std::string guessInput, int compare) { std::string dialogue; //starting dialogue if (guessCount == 0) { dialogue = "I'm thinking of a number between " + std::to_string(min) + " and " + std::to_string(max) + ". You have " + std::to_string(numberofGuesses) + " guesses."; } //if answer is correct else if (compare == 0) { //1 indicates has won playAgain(1); return; } else if (compare == 1) { dialogue = "Your guess was too high."; } else if (compare == 2) { dialogue = "Your guess was too low."; } // if ran out of guesses else if (compare == 3) { // 0 indicates has lost playAgain(0); return; } SDL_RenderClear(gRenderer); highLowTexture.render(0, 0); LTexture bubbleText; bubbleText.loadfromText(dialogue, textColor); bubbleText.render(335, 70); LTexture guessPrompt; guessPrompt.loadfromText("Enter a number:", textColor); guessPrompt.render(350, 250); LTexture guessCounter; guessCounter.loadfromText("Guesses remaining: " + std::to_string(numberofGuesses - guessCount), textColor); guessCounter.render(350, 200); LTexture inputTexture; //if input is not empty if (guessInput != "") { inputTexture.loadfromText(guessInput, textColor); } //else add a space so it can render else { inputTexture.loadfromText(" ", textColor); } inputTexture.render(350 + guessPrompt.mWidth, 250); SDL_RenderPresent(gRenderer); } void gameLoop() { SDL_Event e; //start with empty string std::string guessInput = " "; //comparison code to indicate which text is generated. int comparison = 0; SDL_StartTextInput(); while (!quit) { while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { quit = true; } if (e.type == SDL_TEXTINPUT) { //if input is a numeric value, add to string. if (e.text.text[0] == '0' || e.text.text[0] == '1' || e.text.text[0] == '2' || e.text.text[0] == '3' || e.text.text[0] == '4' || e.text.text[0] == '5' || e.text.text[0] == '6' || e.text.text[0] == '7' || e.text.text[0] == '8' || e.text.text[0] == '9') { guessInput += e.text.text; } } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_RETURN || e.key.keysym.sym == SDLK_KP_ENTER) { //if input is not empty if (guessInput != " ") { //convert string to int int input = stoi(guessInput); //reset string guessInput = " "; //update counter ++guessCount; //compare guess with generated number comparison = compare(randomNumber, input); } } else if (e.key.keysym.sym == SDLK_BACKSPACE &amp;&amp; guessInput.length() &gt; 0) { guessInput.pop_back(); } } } renderScene(guessInput, comparison); } SDL_StopTextInput(); } void mainMenu() { menuPressed = false; while (!quit &amp;&amp; !menuPressed) { SDL_Event e; while (SDL_PollEvent(&amp;e) != 0) { if (e.type == SDL_QUIT) { quit = true; } //check for each button and give number to indicate which button was pressed. buttonPress(e, tenButton.mButton, 2); buttonPress(e, hundredButton.mButton, 3); buttonPress(e, thousandButton.mButton, 4); } SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(gRenderer); menuTexture.render(0, 0); ; tenButton.render((SCREEN_WIDTH / 2) - (tenButton.mWidth / 2), 175); hundredButton.render((SCREEN_WIDTH / 2) - (tenButton.mWidth / 2), 225); thousandButton.render((SCREEN_WIDTH / 2) - (tenButton.mWidth / 2), 275); SDL_RenderPresent(gRenderer); } } //create window, renderer, etc. void init() { SDL_Init(SDL_INIT_VIDEO); gWindow = SDL_CreateWindow("HiLo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); IMG_Init(IMG_INIT_PNG); TTF_Init(); } //loadTextures and font. void loadMedia() { highLowTexture.loadfromSurface("Resources/HiLo.png"); yesButton.loadfromSurface("Resources/HiLoYes.png"); noButton.loadfromSurface("Resources/HiLoNo.png"); tenButton.loadfromSurface("Resources/HiLo10.png"); hundredButton.loadfromSurface("Resources/HiLo100.png"); thousandButton.loadfromSurface("Resources/HiLo1000.png"); menuTexture.loadfromSurface("Resources/HiLoMenu.png"); gFont = TTF_OpenFont("Resources/opensans.ttf", 20); } void close() { highLowTexture.free(); noButton.free(); yesButton.free(); tenButton.free(); hundredButton.free(); thousandButton.free(); menuTexture.free(); TTF_CloseFont(gFont); gFont = NULL; SDL_DestroyWindow(gWindow); gWindow = NULL; SDL_DestroyRenderer(gRenderer); gRenderer = NULL; TTF_Quit(); IMG_Quit(); SDL_Quit(); } int main(int argc, char* args[]) { init(); loadMedia(); mainMenu(); gameLoop(); close(); return 0; } </code></pre> <p>For reference if it makes it easier to understand which each texture represents;</p> <ul> <li><code>highLowTexture</code> is just a background texture with a stick figure and a speech bubble to render text to</li> <li><code>menuTexture</code> is a background that just says "HighLow"</li> <li><code>yesButtons/noButtons</code> just say yes or no</li> <li><code>ten/hundred/thousandButtons</code> are rectangles that say "1-(10/100/1000). (5/7/9) guesses." So that the player may change the difficulty.</li> </ul> <p>I also have one specific question. On Lazy Foo's tutorials everything done is on one file. When is it recommended to make use of other cpp or header files? Maybe for this simple of a game it's fine, but when I get into more complicated games, I would assume it gets to be fairly overwhelming to have the entire game in one file.</p>
[]
[ { "body": "<p>Definitely not bad for a first attempt! Let's start at the top.</p>\n\n<pre><code>#include &lt;SDL.h&gt;\n#include &lt;SDL_image.h&gt;\n#include &lt;iostream&gt;\n#include &lt;random&gt;\n#include &lt;SDL_ttf.h&gt;\n#include &lt;string&gt;\n</code></pre>\n\n<p>It's generally wise to organize your ...
{ "AcceptedAnswerId": "200174", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T21:43:55.717", "Id": "200150", "Score": "5", "Tags": [ "c++", "sdl" ], "Title": "SDL/C++ High-Low Guessing Game" }
200150
<p>Are the final templated functions <code>allocate</code> and <code>deallocate</code> thread safe? The <code>Cache</code> object is a <code>thread_local</code> and that also makes <code>FreeList</code> a <code>thread_local</code>, the only parts that I'm still in doubt are the calls to <code>std::malloc</code> and <code>std::free</code>. Are they always thread safe or that depends on the implementation? Is it better to put a lock on them?</p> <p>I think that the cached memory doesn't need locks since all the objects here are <code>thread_local</code> and each thread has a local copy of it. The only problem really are <code>std::malloc</code> and <code>std::free</code>, are they already synchronized?</p> <p>Here's a self contained example of all of my code:</p> <pre><code>#include &lt;iostream&gt; class FreeList { struct Node { Node * next; }; Node * this_head; public: static constexpr auto const NODE_SIZE = sizeof(Node); FreeList() noexcept : this_head() { } FreeList(FreeList &amp;&amp;) = delete; FreeList(FreeList const &amp;) = delete; FreeList &amp; operator =(FreeList &amp;&amp;) = delete; FreeList &amp; operator =(FreeList const &amp;) = delete; void push(void * const address) noexcept { auto const head = static_cast&lt;Node *&gt;(address); head-&gt;next = this_head; this_head = head; } auto pop() noexcept { void * const head = this_head; if (head) { this_head = this_head-&gt;next; } return head; } }; template &lt;uint64_t const SIZE&gt; class Cache { static_assert(SIZE &gt;= FreeList::NODE_SIZE); FreeList this_free_list; public: Cache() noexcept : this_free_list() { } Cache(Cache &amp;&amp;) = delete; Cache(Cache const &amp;) = delete; ~Cache() noexcept { while (auto const address = this_free_list.pop()) { // Do I need a lock here? std::free(address); } } Cache &amp; operator =(Cache &amp;&amp;) = delete; Cache &amp; operator =(Cache const &amp;) = delete; auto allocate() { if (auto const address = this_free_list.pop()) { return address; } // Do I need a lock here? if (auto const address = std::malloc(SIZE)) { return address; } throw std::bad_alloc(); } void deallocate(void * const address) noexcept { if (address) { this_free_list.push(address); } } }; template &lt;typename TYPE&gt; auto &amp; get() noexcept { thread_local TYPE local; return local; } template &lt;typename TYPE&gt; auto &amp; get_cache() noexcept { return get&lt;Cache&lt;sizeof(TYPE)&gt;&gt;(); } // Are these thread safe? template &lt;typename TYPE&gt; auto allocate() { auto const address = get_cache&lt;TYPE&gt;().allocate(); return static_cast&lt;TYPE *&gt;(address); } template &lt;typename TYPE&gt; void deallocate(void * const address) noexcept { get_cache&lt;TYPE&gt;().deallocate(address); } int main() { auto x = allocate&lt;int64_t&gt;(); *x = 5; std::cout &lt;&lt; *x &lt;&lt; '\n'; deallocate&lt;int64_t&gt;(x); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T23:44:36.353", "Id": "385187", "Score": "0", "body": "Which C++ version is this targeting? C++11? C++14? C++17?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T23:49:36.147", "Id": "385188", "...
[ { "body": "<blockquote>\n <p>Are the final templated functions <code>allocate</code> and <code>deallocate</code> thread safe?</p>\n</blockquote>\n\n<p>As every other state used is thread-local, the answer hinges on this:<br>\nIs the <code>malloc()</code>/<code>free()</code> memory-management-system thread-safe...
{ "AcceptedAnswerId": "200157", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T23:29:42.987", "Id": "200156", "Score": "4", "Tags": [ "c++", "linked-list", "thread-safety", "cache", "c++17" ], "Title": "Thread-safe cache using a linked list" }
200156
<p>I've written a basic website status checker in Python/Flask which reads a list of URLs from a json file and cycles through them every x seconds to check they're online. It displays the results as a webpage:</p> <p><a href="https://i.stack.imgur.com/fnI4V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fnI4V.png" alt="Screenshot"></a></p> <p>It was written to help me learn Python (at the end of my third week) on my phone in my spare time rather than out of any real necessity so I'd love any feedback on improvements that could be made... both stylistically and programmatically :)</p> <p>To keep things brief I won't include my very basic css but that's on the github repo: <a href="https://github.com/emojipeach/webpagestatuscheck/tree/18d70ad5821935870138114823e58496152cc602" rel="noreferrer">https://github.com/emojipeach/webpagestatuscheck</a></p> <p><strong>Files/Folders:</strong></p> <pre><code>Project | +-- app.py +-- checkurls.json +-- settings.py +-- unittests.py | +-- templates | | | +-- layout.html | +-- returned_statuses.html </code></pre> <p><strong>app.py</strong></p> <pre><code>import requests import json import threading from socket import gaierror, gethostbyname from multiprocessing.dummy import Pool as ThreadPool from urllib.parse import urlparse from flask import Flask, render_template, jsonify from time import gmtime, strftime from settings import refresh_interval, filename, site_down def is_reachable(url): """ This function checks to see if a host name has a DNS entry by checking for socket info.""" try: gethostbyname(url) except (gaierror): return False else: return True def get_status_code(url): """ This function returns the status code of the url.""" try: status_code = requests.get(url, timeout=30).status_code return status_code except requests.ConnectionError: return site_down def check_single_url(url): """This function checks a single url and if connectable returns the status code, else returns UNREACHABLE.""" if is_reachable(urlparse(url).hostname) == True: return str(get_status_code(url)) else: return site_down def check_multiple_urls(): """ This function checks through urls specified in the checkurls.json file and returns their statuses as a dictionary every 60s.""" statuses = {} temp_list_urls = [] temp_list_statuses = [] global returned_statuses global last_update_time t = threading.Timer t(refresh_interval, check_multiple_urls).start() for group, urls in checkurls.items(): for url in urls: temp_list_urls.append(url) pool = ThreadPool(8) temp_list_statuses = pool.map(check_single_url, temp_list_urls) for i in range(len(temp_list_urls)): statuses[temp_list_urls[i]] = temp_list_statuses[i] last_update_time = strftime("%Y-%m-%d %H:%M:%S", gmtime()) returned_statuses = statuses app = Flask(__name__) @app.route("/", methods=["GET"]) def display_returned_statuses(): return render_template( 'returned_statuses.html', returned_statuses = returned_statuses, checkurls = checkurls, last_update_time = last_update_time ) @app.route("/api", methods=["GET"]) def display_returned_api(): return jsonify( returned_statuses ),200 with open(filename) as f: checkurls = json.load(f) returned_statuses = {} last_update_time = 'time string' if __name__ == '__main__': check_multiple_urls() app.run() </code></pre> <p><strong>settings.py</strong></p> <pre><code># Interval to refresh status codes in seconds refresh_interval = 60.0 # File containing groups ofurls to check in json format. See included example 'checkurls.json' filename = 'checkurls.json' # Message to display if sites are not connectable site_down = 'UNREACHABLE' </code></pre> <p><strong>checkurls.json</strong></p> <pre><code>{ "BBC": [ "https://www.bbc.co.uk", "http://www.bbc.co.uk", "https://doesnotexist.bbc.co.uk", "https://www.bbc.co.uk/sport", "https://www.bbc.co.uk/404", "https://www.bbc.co.uk" ], "Google": [ "https://www.google.com", "https://support.google.com", "http://localhost:8080" ] } </code></pre> <p><strong>templates/layout.html</strong></p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;A Simple Website Status Checker&lt;/title&gt; &lt;link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheet.css') }}"&gt; &lt;/head&gt; &lt;body&gt; {% block body %}{% endblock %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>templates/returned_statuses.html</strong></p> <pre><code>{% extends "layout.html" %} {% block body %} &lt;div class="time_updated"&gt;Last updated: {{ last_update_time }} UTC&lt;/div&gt; {% for group, urls in checkurls.items() %} &lt;h1 class="group"&gt;{{ group }}&lt;/h1&gt; {% for url in urls %} {% if returned_statuses.get(url) == "200" %} &lt;p class="good-url"&gt;{{ url }} &lt;font color="green"&gt; {{ returned_statuses.get(url) }}&lt;/font&gt;&lt;/p&gt; {% endif %} {% endfor %} {% for url in urls %} {% if returned_statuses.get(url) == "200" %} {% else %} &lt;p class="bad-url"&gt;{{ url }} &lt;font color="red"&gt; {{ returned_statuses.get(url) }}&lt;/font&gt;&lt;/p&gt; {% endif %} {% endfor %} {% endfor %} {% endblock %} </code></pre> <p><strong>unittests.py</strong></p> <pre><code>import unittest from test import is_reachable, get_status_code, check_single_url class IsReachableTestCase(unittest.TestCase): """Tests the is_reachable function.""" def test_is_google_reachable(self): result = is_reachable('www.google.com') self.assertTrue(result) def test_is_nonsense_reachable(self): result = is_reachable('ishskbeosjei.com') self.assertFalse(result) class GetStatusCodeTestCase(unittest.TestCase): """Tests the get_status_code function.""" def test_google_status_code(self): result = get_status_code('https://www.google.com') self.assertEqual(result, 200) def test_404_status_code(self): result = get_status_code('https://www.bbc.co.uk/404') self.assertEqual(result, 404) class CheckSingleURLTestCase(unittest.TestCase): """Tests the check_single_url function""" def test_bbc_sport_url(self): result = check_single_url('http://www.bbc.co.uk/sport') self.assertEqual(result, '200') def test_nonsense_url(self): result = check_single_url('https://ksjsjsbdk.ievrygqlsp.com') self.assertEqual(result, 'UNREACHABLE') def test_timeout_url(self): result = check_single_url('https://www.bbc.co.uk:90') self.assertEqual(result, 'UNREACHABLE') def test_connrefused_url(self): result = check_single_url('http://127.0.0.1:8080') self.assertEqual(result, 'UNREACHABLE') unittest.main() </code></pre>
[]
[ { "body": "<p>I like the unittests part in your code, and learn something about it from you too.</p>\n\n<p>I noticed that you used <code>global</code> in your <code>check_multiple_urls</code> which is really bad style <a href=\"https://stackoverflow.com/questions/19158339/why-are-global-variables-evil\">Why are...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T00:18:20.557", "Id": "200159", "Score": "13", "Tags": [ "python", "beginner", "python-3.x", "flask", "status-monitoring" ], "Title": "A website status monitor in Python/Flask" }
200159
<p>I recently had a problem whereby I wanted to filter objects in an array by comparing the values of nested properties of each object to see if there were duplicates. </p> <p>I have tried to explain as clearly as possible the scenario below and the solution I came up with. I wondering if it's possible to improve this solution and if so, how? </p> <p>Example:</p> <pre><code>let articles = [{dateAdded: "31-5-1989", readId: 123, article: { id: 1}}, {dateAdded: "31-5-1989", readId: 124, article: { id: 2}}, {dateAdded: "31-5-1989", readId: 125, article: { id: 1}}] </code></pre> <p>In this array, you can see each object has a <code>readId</code> and an <code>articleId</code>. The first and last objects in the array have a different <code>readId</code> but a matching <code>articleId</code>. We want to return every object in this array <strong>unless</strong> we have already returned an object with the same <code>articleId</code>.</p> <p>Here is my solution:</p> <pre><code>const removeDuplicatesbyArticleId = articles =&gt; { let articleIdsArray = []; let finalArray = []; articleResponse.reading.map(element =&gt; { if (!articleIdsArray.includes(element.article.id)) { articleIdsArray.push(element.article.id); finalArray.push(element); } }); let filteredArticleResponse = articles; filteredArticleResponse.reading = finalArray; return filteredArticleResponse; }; </code></pre> <p>All I'm doing here is looping through the array, checking if the <code>articleId</code> exists in the <code>articleIdsArray</code> and if not, pushing this onto <code>finalArray</code> and then repeating before returning finalArray at the end of the loop.</p> <p>This solution feels a little crude, I'd be really grateful if anyone could suggest an alternative(s) solution(s) that is easier to read, better for performance, or both!</p> <p>I apologise if this is a repeat, from much searching I couldn't find a question and answer that matched my specific case.</p>
[]
[ { "body": "<blockquote>\n <p>We want to return every object in this array unless we have already returned an object with the same <code>articleId</code>.</p>\n</blockquote>\n\n<p>I would use a <code>Set</code> object to keep track of which <code>articleId</code> values we've already used and then use <code>.fi...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T21:25:08.597", "Id": "200164", "Score": "0", "Tags": [ "javascript", "algorithm", "ecmascript-6" ], "Title": "Filter array of objects by comparing nested object properties" }
200164
<p>I learned javascript from some tutorials and as per advice, I thought of creating some task by my self. I wrote the following code and as I expected I saw the answer. If someone can assist me with how to code better? (The below code will create a table and update rows with input data which user enter)</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>// Javascript var input = document.getElementById("input"); var btn = document.getElementById("btn"); var table = document.getElementById("table"); btn.addEventListener('click', function(){ var updateTask = input.value; // Now create row and add all the inputs value to a table var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var allRows = table.querySelectorAll("tr"); cell2.innerHTML = updateTask; // Update the Number/Order var rowLength = allRows.length; if (rowLength &gt; 0){ cell1.innerHTML = rowLength - 1; } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;To Do List&lt;/h1&gt; &lt;div class="list-wrapper"&gt; &lt;input id="input" class="input" type="text" placeholder="Enter here!!!" onfocus="this.value=' ' "&gt; &lt;input id="btn" type="submit" value="ADD"&gt; &lt;table id="table"&gt; &lt;tr&gt;&lt;th&gt;Number&lt;/th&gt;&lt;th&gt;Task&lt;/th&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T06:05:25.810", "Id": "385210", "Score": "2", "body": "Welcome to Code Review. The current question title, which states your programming language, applies to too many questions on this site to be useful. The site standard is for the ...
[ { "body": "<h3>Querying for row elements</h3>\n<p>The original code queries for elements with tag name <code>tr</code>:</p>\n<blockquote>\n<pre><code>var allRows = table.querySelectorAll(&quot;tr&quot;); \n</code></pre>\n</blockquote>\n<p>Just as the code utilizes table methods like <a href=\"https://developer....
{ "AcceptedAnswerId": "200286", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T04:39:31.980", "Id": "200169", "Score": "2", "Tags": [ "javascript", "html", "event-handling", "dom", "to-do-list" ], "Title": "To Do List using basic JS" }
200169
<p>I'd like to improve my <a href="https://parceljs.org/getting_started.html" rel="nofollow noreferrer">Parcel.js</a> build but I'm not sure how to do it.</p> <p>You can find the source code <a href="https://github.com/AWolf81/electron-react-parcel-boilerplate" rel="nofollow noreferrer">here</a>.</p> <h1>Build process to improve <code>yarn start</code></h1> <p>At the moment, Electron starts in parallel with the build process and displays a blank page until parcel finished.</p> <p>But I'd like to wait for first bundle before starting Electron.</p> <h1>What I've tried</h1> <ul> <li>Changed <code>npm-run-all</code> to run <code>dev</code> then <code>start:electron</code> sequentially but parcel is blocking the following thread, so Electron was not starting</li> <li>Spawn <code>start:electron</code> from build script (see <code>scripts/dev.js</code>) but app doesn't start correctly. I'll describe this in more details below. It would be great if it would work with-out that custom script but I'm not sure if that's possible</li> <li>Also tested the code mentioned <a href="https://github.com/parcel-bundler/parcel/issues/1458" rel="nofollow noreferrer">here</a> or <a href="https://github.com/parcel-bundler/parcel/issues/800" rel="nofollow noreferrer">here</a> with the same result.</li> </ul> <h1>Dev script</h1> <p>In the repo the scripts are 'commented' <code>in package.json</code>. Just change <code>commented_dev</code> and <code>commented_start</code> to dev &amp; start to test my current version of the script.</p> <p>The script is correctly running sequentially but Electron is unable to load from the server (see screenshot below)</p> <p>I've also tried to run <code>start:electron</code> with <code>npm run</code> and <code>execSync</code> but that wasn't working. It seems like parcel is not correctly starting the dev server - maybe that's related to a configuration that's missing because the server starts correctly with the parcel command from CLI. (<code>localhost:1234</code> is also not accessible from a web browser.)</p> <p>Here is the script:</p> <pre><code>const Bundler = require("parcel-bundler"); const Path = require("path"); const { spawn, execSync, fork } = require("child_process"); // Entrypoint file location const file = Path.join(__dirname, "./src/index.html"); console.log("file", file); const options = { //outDir: './dist', // The out directory to put the build files in, defaults to dist //outFile: 'index.html', // The name of the outputFile publicUrl: "./" // The url to server on, defaults to dist }; async function runBundle() { // Initializes a bundler using the entrypoint location and options provided const bundler = new Bundler(file, options); bundler.on("bundled", bundle =&gt; { // bundler contains all assets and bundles, see documentation for details // gets called once after first bundle }); // bundler.bundle(); // this is in the script but I would comment this // Run the bundler, this returns the main bundle // Use the events if you're using watch mode as this promise will only trigger once and not for every rebuild const bundle = bundler.serve().then(server =&gt; { console.log("server listen"); spawn("yarn", ["start:electron"], { stdio: "inherit", shell: true }); }); await bundle; } runBundle(); </code></pre> <p><a href="https://i.stack.imgur.com/lYX3x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lYX3x.png" alt="screenshot"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T23:27:16.843", "Id": "385396", "Score": "0", "body": "OK, I've found why the server wasn't starting correctly. After changing `const file = Path.join(__dirname, \"./src/index.html\");` to `const file = \"./src/index.html\"` it's wor...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T06:35:37.407", "Id": "200172", "Score": "1", "Tags": [ "javascript", "electron" ], "Title": "Start Electron after Parcel.js started development server" }
200172
<p>Working from a CSV of about 14.000 lines, I need to match dates in the CSV against some API. I'm reading the CSV using Pandas (for various other reasons). Most often, the date is just a year, i.e. an integer, which Pandas converts to a float. Other date formats also occur (see <code>main</code> in the code below). 12-10-1887 is the 12th of October, not the 10th of December. </p> <p>The API also returns date strings, often also incomplete, for example when only year but not month and/or day of birth are known. Single-digit days and months do get a leading zero, and format is as close to ISO-date as possible, e.g. March 1675 will be "1675-03". </p> <p>I think my best bet is not to convert to type <code>datetime</code>, but to try to match strings. </p> <p><strong>EDIT</strong>: because this way I can let the API do more work. </p> <pre><code>http://baseURL/name:Gupta,Anil&amp;date:1956 </code></pre> <p>Without the date, I get all Anil Gupta's. <em>With</em> it, I get all Anil Gupta's with either born year (most likely), death year, of year of activity 1956. All in all, this is MUCH less work than writing dateconverters for fields that are empty in 90% of the cases. In general, name + exact date of birth is a pretty unique identifier. </p> <p>So I wrote this <strong>dateclean.py</strong> (Python 3.7): </p> <pre><code>import re from datetime import datetime as dt def cleanup(date): patterns = [# 0) 1-12-1963 r'(\d{1,2})-(\d{1,2})-(\d{4})$', # 1) 1789-7-14 r'(\d{4})-(\d{1,2})-(\d{1,2})$', # 2) '1945-2' r'(\d{4})-(\d{1,2})$', # 3) 2-1883 r'(\d{1,2})-(\d{4})$' ] try: return str(int(date)) except ValueError: pass for pat in patterns: q = re.match(pat, date) if q: if pat == patterns[0]: year = re.sub(patterns[0], r'\3', date) month = re.sub(patterns[0], r'\2', date) day = re.sub(patterns[0], r'\1', date) return '{0}-{1:0&gt;2}-{2:0&gt;2}'.format(year, month, day) if pat == patterns[1]: year = re.sub(patterns[1], r'\1', date) month = re.sub(patterns[1], r'\2', date) day = re.sub(patterns[1], r'\3', date) return '{0}-{1:0&gt;2}-{2:0&gt;2}'.format(year, month, day) if pat == patterns[2]: year = re.sub(patterns[2], r'\1', date) month = re.sub(patterns[2], r'\2', date) return '{0}-{1:0&gt;2}'.format(year, month) if pat == patterns[3]: year = re.sub(patterns[3], r'\2', date) month = re.sub(patterns[3], r'\1', date) return '{0}-{1:0&gt;2}'.format(year, month) else: return date def main(): dates = 1858.0, '1-12-1963', '1945-2', '7-2018', '1789-7-14', for date in dates: print('in: {} out: {}'.format(date, cleanup(date))) if __name__ == "__main__": main() </code></pre> <p>The list <code>dates</code> in <code>main()</code> contains all formats known until now. On the plus side, by using this method, adding new formats is easy. </p> <p>There are a lot of <code>patterns[x]</code>, which is not at all DRY, yet I don't see how I can avoid that: I <em>have</em> to split each input string into year, month and day, if any (using <code>r'\1'</code> etc.)</p> <p>Also, I know flat is better than nested, but I don't see how I can improve on that. I do try to <a href="https://en.wikibooks.org/wiki/Computer_Programming/Coding_Style/Minimize_nesting" rel="noreferrer">return as early</a> as possible. </p> <p>Readability is more important to me than performance, because the API is a bottleneck anyway. Then again, serious slowing-downers should be avoided. </p>
[]
[ { "body": "<p>For starter, congratulations, the code is clean and uses rather good constructs. I just have two nitpicks about the layout:</p>\n\n<ul>\n<li><p>I prefer to indent lists before the first row:</p>\n\n<pre><code>patterns = [\n # 0) 1-12-1963\n r'(\\d{1,2})-(\\d{1,2})-(\\d{4})$',\n ...
{ "AcceptedAnswerId": "200179", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T07:52:11.487", "Id": "200176", "Score": "13", "Tags": [ "python", "python-3.x", "datetime", "regex", "formatting" ], "Title": "Cleaning up date strings in Python" }
200176
<p>I'm looking for a function to take a list of generic classes, and map it to different layout of datatable.</p> <p>That means, I can't just directly map my class property names and values to grid, I need to convert it to the new values.</p> <p>The solution that I came up with works, but it feels ... sloppy. Can anyone recommend a better way of doing it?</p> <pre><code>class Program { static void Main(string[] args) { var list = new List&lt;InputClass&gt;() { new InputClass {SomeField = "A", OtherField = 1}, new InputClass {SomeField = "B", OtherField = 2}, new InputClass {SomeField = "C", OtherField = 3}, new InputClass {SomeField = "D", OtherField = 4} }; var dict = new Dictionary&lt;string, Func&lt;InputClass, object&gt;&gt;() { {"ColA", (f) =&gt; $"{f.SomeField}ABCD"}, {"ColB", (f) =&gt; DateTime.Now} }; var dt = ToDataTable(list, dict); Console.ReadKey(); } public static DataTable ToDataTable&lt;T&gt;(List&lt;T&gt; list, Dictionary&lt;string, Func&lt;T, object&gt;&gt; columns) where T : class { var dt = new DataTable(); foreach (var key in columns.Keys) { var func = columns[key]; Type[] funcParams = (func.GetType()).GenericTypeArguments; dt.Columns.Add(key, funcParams[1]); } foreach (var record in list) { var objects = new List&lt;object&gt;(); foreach (var key in columns.Keys) { objects.Add(columns[key](record)); } dt.Rows.Add(objects.ToArray()); } return dt; } } class InputClass { public string SomeField { get; set; } public int OtherField { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T14:29:49.787", "Id": "385276", "Score": "1", "body": "Do you have a concrete example of your implementation? It would help a lot for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T15:04:51.38...
[ { "body": "<p>Cases like this I would hide the \"sloppy\" </p>\n\n<p>I would create a class that holds the mappings from the class to the table and create methods to build the mappings. This way there is no need for reflection and we can save the funcs to be reused. </p>\n\n<pre><code>public class Mapper&lt;TS...
{ "AcceptedAnswerId": "200205", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T09:36:09.990", "Id": "200189", "Score": "4", "Tags": [ "c#", "generics", ".net-datatable" ], "Title": "List of classes to datatable" }
200189
<p>The code below draws the mandelbrot set for { z | z&in; ℂ, -2.2 &leq; Re(z) &leq; 0.6, -1.4 &leq; Im(z) &leq; 1.4} into a 300&times;300px png image. For each pixel, if the sequence {z<sub>i</sub>} is found to diverge on its nth iteration, the pixel shall have a colour based on ln(n)/ln(Max(n)), where Max(n) denotes to the maximum iteration found throughout the image. </p> <p>After reading the corresponding <a href="https://doc.rust-lang.org/book/second-edition/ch16-00-concurrency.html" rel="nofollow noreferrer">chapter</a> in “the book”, I decided I should try some parallelism. In the code, I make 3 threads, each of which processes every 3 pixels (The first thread processes 0, 3, ... -th pixel, the second 1, 4..., etc.). I save the results reported from the workers, then assemble them to one picture. I make the limit to three because I want one of my CPUs to be free for other tasks.</p> <p>I haven't written many codes with concurrency nor parallelism, so I'd especially appreciate any comments regarding how I treat that aspect. Especially;</p> <ul> <li>I couldn't think of a smarter way of making 3 threads. I'm especially uncertain about how I treat the first thread (from which other senders are <code>clone</code>d).</li> <li>It'll be easily rewritten to read the <code>MAX_JOBS</code> from the command arguments, but is it the right way to limit the number of CPUs the program can use? What I do now is to create exactly specified number of threads, but I feel it could be too crude a resolution.</li> </ul> <p>Thank you in advance, and any kind of comments will help me and will greatly be appreciated.</p> <pre><code>extern crate image; extern crate num; use num::complex::Complex; use std::cmp::max; use std::sync::mpsc; use std::thread; // |z_MAX_ITER|^2 &lt; DIVERGE_CRITERIA then we decide the sequence doen't diverge const MAX_ITER: u32 = 10000; const DIVERGE_CRITERIA: f64 = 16.0; const IMG_X: usize = 300; // image width in pixels const IMG_Y: usize = 300; // image height in pixels const XVIEWWIDTH: f64 = 2.8; // viewport size. See XVIEWLEFT belpow const YVIEWWIDTH: f64 = 2.8; const XVIEWLEFT: f64 = -2.2; // XVIEWLEFT &lt;= Re(z) &lt; XVIEWLEFT + XVIEWWIDTH const YVIEWTOP: f64 = -YVIEWWIDTH / 2.0; const GRID_WIDTH: f64 = XVIEWWIDTH / (IMG_X as f64); // each pixel corresponds to this width const GRID_HEIGHT: f64 = YVIEWWIDTH / (IMG_Y as f64); const MAX_JOBS: usize = 3; // TODO: get the number from command argument const VERBOSE: bool = false; fn main() { let mut dat: Vec&lt;u32&gt; = vec![0; (IMG_X * IMG_Y) as usize]; // Spawn MAX_JOBS jobs for calculation let (tx, rx) = mpsc::channel(); for i in 1..MAX_JOBS { let tx1 = mpsc::Sender::clone(&amp;tx); mk_calc_worker(tx1, i); } mk_calc_worker(tx, 0); // TODO: this doesn't feel right // save results sent from the workers for (loc, result) in rx { if let Some(n) = result { if VERBOSE { println!("{}\t{}", n, loc); } if let Some(p) = dat.get_mut(loc) { *p = n; } } } save(&amp;dat, "frac.png"); } fn mk_calc_worker(tx: mpsc::Sender&lt;(usize, Option&lt;u32&gt;)&gt;, modulo: usize) -&gt; () { thread::spawn(move || { for i in (modulo..IMG_X * IMG_Y).step_by(MAX_JOBS) { tx.send((i, calc_val(get_loc(i)))).unwrap(); } }); } // i_th pixel corresponds to this square in C fn get_loc(i: usize) -&gt; Complex&lt;f64&gt; { let block_x = f64::from((i % IMG_X) as u32); let block_y = f64::from((i / IMG_X) as u32); Complex::new( XVIEWLEFT + GRID_WIDTH * block_x, YVIEWTOP + GRID_HEIGHT * block_y, ) } // n: iterations it took for the sequence to diverge. m: maximum in the picture fn to_colour(n: u32, m: u32) -&gt; image::Rgba&lt;u8&gt; { if n == 0 { image::Rgba([0, 0, 0, 220]) } else { // normalised logarithm let v = (255.0 * f64::from(n).ln() / f64::from(m).ln()).floor() as u8; image::Rgba([0, v / 2, v, 255]) } } // None if the sequence doen't diverge there; Some(n) if it diverges in its n-th iteratation fn calc_val(c: Complex&lt;f64&gt;) -&gt; Option&lt;u32&gt; { let mut z = Complex::new(0.0, 0.0); for iteration in 0..MAX_ITER { z = z * z + c; if z.norm_sqr() &gt; DIVERGE_CRITERIA { return Some(iteration + 1); } } None } fn save(dat: &amp;Vec&lt;u32&gt;, f_name: &amp;str) -&gt; () { let img_buf = draw_picture(&amp;dat); img_buf.save(f_name).unwrap(); } fn draw_picture(dat: &amp;Vec&lt;u32&gt;) -&gt; image::ImageBuffer&lt;image::Rgba&lt;u8&gt;, Vec&lt;u8&gt;&gt; { let maximum = dat.iter().fold(0, |m, &amp;v| max(m, v)); if VERBOSE { println!("MAX={}", maximum); } let mut img_buf = image::ImageBuffer::new(IMG_X as u32, IMG_Y as u32); for (x, y, pixel) in img_buf.enumerate_pixels_mut() { let val = dat[x as usize + y as usize * IMG_X]; *pixel = to_colour(val, maximum); } img_buf } </code></pre> <p>Result: </p> <p><a href="https://i.stack.imgur.com/OJ8fP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OJ8fP.png" alt="Resulting mandelbrot"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T10:48:19.657", "Id": "200193", "Score": "4", "Tags": [ "image", "concurrency", "rust" ], "Title": "Drawing the Mandelbrot with multiple threads in rust" }
200193
<p>I wrote a ROW (<a href="https://gist.github.com/IlyaGazman/6208c1ac82137b409d2a2caec9b83b36" rel="nofollow noreferrer">Race of work</a>) simulation, the idea contains a mathematical bug and, I asked a question about it <a href="https://math.stackexchange.com/questions/2861270/how-to-to-equally-distribute-pool-reword-in-rowrace-of-work">here</a>.</p> <p>I would also like to make this code more readable and, this is why I am sharing it here. Please review it and tell me how I can style it better or improve performance.</p> <p>I posted it in a <a href="https://gist.github.com/IlyaGazman/6208c1ac82137b409d2a2caec9b83b36" rel="nofollow noreferrer">gist on GitHub</a>.</p> <pre><code>import java.math.BigDecimal; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Random; import java.util.UUID; /** * This is an experimental proof that in * &lt;a href="https://confidence-coin.com/race-of-work-blockchain-without-forks/"&gt;ROW&lt;/a&gt;, * Race of work have, your chances to mine a block are equal to your * computational power percentage from the entire network, or in other words, the chance to win are equally distributed. * * @author Ilya Gazman */ public class RowTest { private MessageDigest sha256; private RowTest() throws NoSuchAlgorithmException { sha256 = MessageDigest.getInstance("SHA-256"); } public static void main(String... args) throws NoSuchAlgorithmException { new RowTest().start(); } private void start() { ArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;(); Random random = new Random(); list.add(10); while (sum(list) &lt; 100) { int value = random.nextInt(100 - sum(list) + 1); if (value == 0 || list.contains(value)) { continue; } list.add(value); } System.out.println(sum(list) + " " + list.size()); byte[][] players = new byte[list.size()][]; int[] score = new int[list.size()]; double[] reword = new double[list.size()]; String guid = UUID.randomUUID().toString(); float totalGames = 1_000; for (int i = 0; i &lt; totalGames; i++) { for (int j = 0; j &lt; list.size(); j++) { int player = list.get(j); byte[] min = null; for (int k = 0; k &lt; player; k++) { byte[] hash = hash(i, guid, k, player); if (hash.length != 32) { throw new Error("Hash error"); } if (min == null || compare(hash, min) == -1) { min = hash; } } players[j] = min; } score[findWinner(players)]++; rewordPlayers(players, reword); } for (int i = 0; i &lt; score.length; i++) { System.out.println(list.get(i) + " won\t" + score[i] / totalGames * 100 + "%\tof the times, he earned\t" + reword[i]); } double totalReword = 0; for (double v : reword) { totalReword += v; } System.out.println("\nTotal reword " + totalReword + " / " + totalGames); } private void rewordPlayers(byte[][] players, double[] reword) { int rounding = BigDecimal.ROUND_CEILING; int scale = 32; BigDecimal total = BigDecimal.ZERO; for (byte[] player : players) { BigDecimal playerReword = new BigDecimal(new BigInteger(player)); total = total.add(BigDecimal.ONE.divide(playerReword, scale, rounding)); } for (int j = 0; j &lt; players.length; j++) { BigDecimal playerReword = new BigDecimal(new BigInteger(players[j])); BigDecimal a = BigDecimal.ONE.divide(playerReword, scale, rounding); BigDecimal b = a.divide(total, scale, rounding); reword[j] += b.doubleValue(); } } private int findWinner(byte[][] players) { byte[] min = null; int winner = -1; for (int i = 0; i &lt; players.length; i++) { byte[] hash = players[i]; if (min == null || compare(hash, min) == -1) { min = hash; winner = i; } } return winner; } /** * if a &gt; b return 1 else if a &lt; b return -1 else return 0 */ private static int compare(byte[] a, byte[] b) { int aLength = a.length; int bLength = b.length; for (int i = a.length - 1; i &gt;= 0 &amp;&amp; a[i] == 0; i--) { aLength--; } for (int i = b.length - 1; i &gt;= 0 &amp;&amp; b[i] == 0; i--) { bLength--; } if (aLength &gt; bLength) { return 1; } else if (bLength &gt; aLength) { return -1; } for (int k = 0; k &lt; aLength; k++) { int A = a[k] &amp; 0xff; int B = b[k] &amp; 0xff; if (A &gt; B) { return 1; } if (A &lt; B) { return -1; } } return 0; } private byte[] hash(int i, String value, int k, int player) { value = i + "," + value + "," + k + "," + player; return sha256.digest(value.getBytes()); } private int sum(Iterable&lt;Integer&gt; list) { int total = 0; for (Integer value : list) { total += value; } return total; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T12:52:49.927", "Id": "385257", "Score": "2", "body": "\"the idea contains a mathematical bug\" Broken code is off-topic, does it work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T12:54...
[ { "body": "<p>Very quick review here, formatting is good, so I focused on good practices, reuse of standard Java libraries (Streams), naming etc.</p>\n\n<p>To have this code more organized I would embrace Objects and create a Player class, maybe a Game class. But given the short-lived nature of these objects an...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T12:35:21.403", "Id": "200196", "Score": "2", "Tags": [ "java", "performance", "simulation" ], "Title": "ROW (Race of work) simulation" }
200196
<p>I'm working on a Random Quote Generator Project, and as part of the project, the second instruction is to create a getRandomQuote Function which</p> <ul> <li>should take in one parameter that will later get passed into this function when it is invoked will be the array of quotes.</li> <li>The body of the function should select and return a random quote object from the quotesarray. </li> </ul> <p>I'm kinda confused with my code, I want a review on my code as to whether its fits the instruction. Below is my code, thanks!!</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>// An array of Objects with the quote and source as properties var quotes = [ { quote: "In the end, it’s not the years in your life that count. It’s the life in your years", source: "Abraham Lincoln", }, { quote: "Don’t gain the world and lose your soul, wisdom is better than silver or gold", source: "Bob Marley", }, { quote: "Lighten up, just enjoy life, smile more, laugh more, and don’t get so worked up about things", source: "Kenneth Branagh", }, { quote: "Don’t cry because it’s over, smile because it happened", source: "Ludwig Jacobowski", }, { quote: "Do stuff. Be clenched, curious. Not waiting for inspiration’s shove or society’s kiss on your forehead. Pay attention. It’s all about paying attention. Attention is vitality. It connects you with others. It makes you eager. Stay eager", source: "Susan Sontag", } ]; // getRandomQuote function selects and returns a random quote object function getRandomQuote(array) { for (var i = 0; i &lt; quotes.length; i++) { var quoteIndex = Math.floor(Math.random() * quotes.length); var randomQuote = quoteIndex; } return randomQuote; }</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>Random item from array</h2>\n\n<p>You don't need the for loop to select a random item from an array.</p>\n\n<p>Just get an index using <code>Math.floor(Math.random() * array.length)</code></p>\n\n<pre><code>function getRandomQuote(array) {\n return array[Math.floor(Math.random() * array.length...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T13:11:07.000", "Id": "200197", "Score": "1", "Tags": [ "javascript" ], "Title": "Select a quote from a list randomly" }
200197
<p>I have a macro comprised of this and similar Subs. They work, but I feel like it's slowing it down. Two workbooks are open, and various ranges are copied from one that is hidden (wbSource) and pasted into the other (mainWB), which is not hidden. There is formatting in all the cells that need to be copied, not just the values. Is there a way to do this better?</p> <pre><code>Sub CopyData() Dim mainWB As Workbook Dim mainWS As Worksheet Set mainWB = ActiveWorkbook Set mainWS = mainWB.Sheets(1) Dim wbSource As Workbook Set wbSource = Workbooks.Open(Filename:="H:\Formatting.xlsx") ActiveWindow.Visible = False wbSource.Sheets(1).Range("A10:CX15").Copy mainWS.Paste Range("A1").Select wbSource.Sheets(1).Range("A25:M26").Copy mainWS.Paste mainWS.Range("AF8").Select wbSource.Sheets(1).Range("D49").Copy mainWS.Paste mainWS.Range("AF10").Select wbSource.Sheets(1).Range("D51").Copy mainWS.Paste wbSource.Close End Sub </code></pre>
[]
[ { "body": "<p>Yes, there is a way to do this better.</p>\n\n<p>Always <code>Option Explicit</code>.</p>\n\n<p>No need (almost always) for <code>.Select</code>, this is a human activity and explicitly referencing the ranges in VBA is more efficient. This also creates extra work for the VBA engine.</p>\n\n<p>You ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T14:00:27.610", "Id": "200199", "Score": "0", "Tags": [ "vba", "excel" ], "Title": "Pasting from another workbook" }
200199
<p>I am learning C++ and currently playing with variadic template functions and formatting string, So here is my small attempt to write a formatting function and provide a simple iostream-like interface for std::FILE, I am using '%' as a format specifier f.e </p> <blockquote> <p>format("const CharT *str") == "const CharT *str"<br/> format("HelloWorld - %", 10) == "HelloWorld - 10"</p> </blockquote> <p>here is the code:</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;string&gt; namespace gupta { using string_t = std::string; using CharT = string_t::value_type; inline string_t format(const CharT *str) { return str; } template &lt;typename T&gt; inline string_t to_string(const T &amp;f) { return std::to_string(f); } inline string_t to_string(const char *str) { return std::string{str}; } inline string_t to_string(string_t s) { return (s); } template &lt;typename T, typename... Ts&gt; string_t format(const CharT *str, const T &amp;arg, const Ts &amp;... args) { string_t res; for(; *str; str++) { if(*str == '%') { if(*(str + 1) == '%') { str++; } else { res += to_string(arg); return res += format(str + 1, args...); } } res += *str; } return res; } template &lt;typename... Ts&gt; auto fprint(std::FILE *f, const char *str, Ts &amp;&amp;... args) { auto s = std::move(format(str, std::forward&lt;Ts&gt;(args)...)); return fwrite(s.data(), 1, s.size(), f); } template &lt;typename... Ts&gt; inline auto print(const char *str, Ts &amp;&amp;... args) { return fprint(stdout, str, std::forward&lt;Ts&gt;(args)...); } template &lt;typename... Ts&gt; inline auto debug(const char *str, Ts &amp;&amp;... args) { return fprint(stderr, str, std::forward&lt;Ts&gt;(args)...); } namespace detail { class _stdout_object {}; class _stderr_object {}; } // namespace detail namespace printing_shortcuts { template &lt;typename T&gt; detail::_stdout_object operator&lt;&lt;(detail::_stdout_object f, const T &amp;arg) { auto s = to_string(arg); fwrite(s.data(), 1, s.size(), stdout); return f; } template &lt;typename T&gt; detail::_stderr_object operator&lt;&lt;(detail::_stderr_object f, const T &amp;arg) { auto s = to_string(arg); fwrite(s.data(), 1, s.size(), stderr); return f; } detail::_stdout_object print() { return {}; } detail::_stderr_object debug() { return {}; } } // namespace printing_shortcuts using namespace printing_shortcuts; } // namespace gupta using namespace gupta::printing_shortcuts; class test {}; std::string to_string(const test &amp;) { return "test"; } #include &lt;assert.h&gt; int main() { using namespace gupta; assert(format("const CharT *str") == "const CharT *str"); assert(format("HelloWorld - %", 10) == "HelloWorld - 10"); print("%s\n", format("HelloWorld - %,%", 10, test{})); assert(format("HelloWorld - %,%", 10, test{}) == "HelloWorld - 10,test"); } </code></pre> <p>also, does it make sense to replace <code>class _stdout_object</code> while their pointers with something like</p> <pre><code>namespace detail { class _stdout_object; class _stderr_object; } // namespace detail namespace printing_shortcuts { template &lt;typename T&gt; detail::_stdout_object *operator&lt;&lt;(detail::_stdout_object *, const T &amp;arg) { auto s = to_string(arg); fwrite(s.data(), 1, s.size(), stdout); return nullptr; } template &lt;typename T&gt; detail::_stderr_object *operator&lt;&lt;(detail::_stderr_object *, const T &amp;arg) { auto s = to_string(arg); fwrite(s.data(), 1, s.size(), stderr); return nullptr; } detail::_stdout_object *print() { return nullptr; } detail::_stderr_object *debug() { return nullptr; } } // namespace printing_shortcuts </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T14:23:07.030", "Id": "385272", "Score": "0", "body": "Last part of your question sounds hard to answer without additional context. Is there a specific reason you want pointers?" }, { "ContentLicense": "CC BY-SA 4.0", "Cr...
[ { "body": "<p>I don't think there's a good reason for renaming <code>std::string</code> like this:</p>\n\n<pre><code>using string_t = std::string;\n</code></pre>\n\n<p>It just serves to make the code harder to read (because I have to <em>remember</em> this alias). Just use <code>std::string</code> as is. Simi...
{ "AcceptedAnswerId": "200208", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T14:06:58.613", "Id": "200200", "Score": "6", "Tags": [ "c++", "formatting", "c++14", "template", "variadic" ], "Title": "Small Formatting Library" }
200200
<p>I was sent here from StackOverflow to get some insight on how I can improve my code. I'm a beginner and the program is not streamlined at all. </p> <p>What the program does:</p> <ol> <li>Takes an input of the Retail Price</li> <li>Takes an input of Supplier Price</li> <li>Takes an input of Cost per acquisition</li> <li>Takes an input of number of installments the store offers with no interest for the customer</li> </ol> <p>What to take into consideration: The installments don't follow exact increments. The numbers are as follows: 0 (doesn't offer finance), 2 to 12, 15, 18 and 24 installments. What I would like the program to do is to either allow the person to pick the number of installments from a list OR if for example they input a number of installments that doesn't exist (like 13) it would show them only the closest available number of installments (in the case of 13 or 14 it would be from 0 to 12, skipping 1 as 1 is the same as 0. 16-23 would only show up to 15 and else would show 24 as that is the maximum number of installments).</p> <p>I took into account that a lot of these print statements can be generated from a list or a dict but as a beginner the concepts are still a little confusing to me, hence I'm asking for your help.</p> <pre><code>#Product Retail Price product_retail_price = float(input("Valor do produto na loja em Reais (Formato 00.00): ")) #Costs product_cost = float(input("Valor do produto no fornecedor em Reais (Formato 00.00): ")) cpa = float(input("Custo por aquisição (Formato 00.00): ")) fee_shopify = (product_retail_price / 100)*2 fee_mercadopago = (product_retail_price / 100)*4.99 fee_finance_2 = (product_retail_price / 100)*2.03 fee_finance_3 = (product_retail_price / 100)*4.06 fee_finance_4 = (product_retail_price / 100)*6.09 fee_finance_5 = (product_retail_price / 100)*7.64 fee_finance_6 = (product_retail_price / 100)*8.92 fee_finance_7 = (product_retail_price / 100)*10.06 fee_finance_8 = (product_retail_price / 100)*10.62 fee_finance_9 = (product_retail_price / 100)*11.23 fee_finance_10 = (product_retail_price / 100)*12.41 fee_finance_11 = (product_retail_price / 100)*13.60 fee_finance_12 = (product_retail_price / 100)*14.80 fee_finance_15 = (product_retail_price / 100)*18.47 fee_finance_18 = (product_retail_price / 100)*22.23 fee_finance_24 = (product_retail_price / 100)*23.83 #Calculations parcelas = int(input("Número de parcelas sem juros (Formato: 0-24): ")) base_profit = round(product_retail_price - product_cost - fee_shopify - fee_mercadopago - cpa, 2) profit_2 = round(base_profit - fee_finance_2 - cpa, 2) profit_3 = round(base_profit - fee_finance_3 - cpa, 2) profit_4 = round(base_profit - fee_finance_4 - cpa, 2) profit_5 = round(base_profit - fee_finance_5 - cpa, 2) profit_6 = round(base_profit - fee_finance_6 - cpa, 2) profit_7 = round(base_profit - fee_finance_7 - cpa, 2) profit_8 = round(base_profit - fee_finance_8 - cpa, 2) profit_9 = round(base_profit - fee_finance_9 - cpa, 2) profit_10 = round(base_profit - fee_finance_10 - cpa, 2) profit_11 = round(base_profit - fee_finance_11 - cpa, 2) profit_12 = round(base_profit - fee_finance_12 - cpa, 2) profit_15 = round(base_profit - fee_finance_15 - cpa, 2) profit_18 = round(base_profit - fee_finance_18 - cpa, 2) profit_24 = round(base_profit - fee_finance_24 - cpa, 2) #Print Values print("\n") if parcelas in [0,1]: print(f"Lucro à vista: R${base_profit}") elif parcelas == 2: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") elif parcelas == 3: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") elif parcelas == 4: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") elif parcelas == 5: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") elif parcelas == 6: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") elif parcelas == 7: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") elif parcelas == 8: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") elif parcelas == 9: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") elif parcelas == 10: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") print(f"Lucro parcelado 10x: R${profit_10}") elif parcelas == 11: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") print(f"Lucro parcelado 10x: R${profit_10}") print(f"Lucro parcelado 11x: R${profit_11}") elif parcelas in [12,13,14]: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") print(f"Lucro parcelado 10x: R${profit_10}") print(f"Lucro parcelado 11x: R${profit_11}") print(f"Lucro parcelado 12x: R${profit_12}") elif parcelas in [15,16,17]: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") print(f"Lucro parcelado 10x: R${profit_10}") print(f"Lucro parcelado 11x: R${profit_11}") print(f"Lucro parcelado 12x: R${profit_12}") print(f"Lucro parcelado 15x: R${profit_15}") elif parcelas in [18,19,20,21,22,23]: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") print(f"Lucro parcelado 10x: R${profit_10}") print(f"Lucro parcelado 11x: R${profit_11}") print(f"Lucro parcelado 12x: R${profit_12}") print(f"Lucro parcelado 15x: R${profit_15}") print(f"Lucro parcelado 18x: R${profit_18}") else: print(f"Lucro à vista: R${base_profit}") print(f"Lucro parcelado 2x: R${profit_2}") print(f"Lucro parcelado 3x: R${profit_3}") print(f"Lucro parcelado 4x: R${profit_4}") print(f"Lucro parcelado 5x: R${profit_5}") print(f"Lucro parcelado 6x: R${profit_6}") print(f"Lucro parcelado 7x: R${profit_7}") print(f"Lucro parcelado 8x: R${profit_8}") print(f"Lucro parcelado 9x: R${profit_9}") print(f"Lucro parcelado 10x: R${profit_10}") print(f"Lucro parcelado 11x: R${profit_11}") print(f"Lucro parcelado 12x: R${profit_12}") print(f"Lucro parcelado 15x: R${profit_15}") print(f"Lucro parcelado 18x: R${profit_18}") print(f"Lucro parcelado 24x: R${profit_24}") print("\n") print("AVISO: Lucro calculado usando as taxas atuais do MercadoPago (23/07/2018)") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T15:13:59.790", "Id": "385291", "Score": "3", "body": "Aaaaaaaaaaa! Have you missed the chapter about loops? :-o" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T21:10:53.743", "Id": "385378", "...
[ { "body": "<p>I'd use a code like this:</p>\n\n<pre><code>#Message table \nMESSAGES = {\"StoreValueRequest\": \"Valor do produto na loja em Reais (Formato 00.00): \", \n \"SupplyValueRequest\": \"Valor do produto no fornecedor em Reais (Formato 00.00): \", \n \"AcquisitionCostRequest\": \"...
{ "AcceptedAnswerId": "200271", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T14:55:39.397", "Id": "200207", "Score": "2", "Tags": [ "python", "beginner", "calculator", "finance" ], "Title": "Profit Margin Calculator in Python (with installments)" }
200207
<p>Using Pandas to read a 14k lines CSV with many empty cells - what I call "Emmenthaler data", lots of holes :-) . A very short, simplified sampler (<code>urlbuilder.csv</code>): </p> <pre><code>"one","two","three" "","foo","bacon","" "spam","bar","" </code></pre> <p>The cells contain information to match against this web API, like this: </p> <pre><code>http://base_URL&amp;two="foo"&amp;three="bacon" http://base_URL&amp;one="spam"&amp;two="bar" </code></pre> <p>Leaving values empty in the URL (``...one=""&amp;two="bar"`) would give wrong results. So I want to use just the non-empty fields in each row. To illustrate the method:</p> <pre><code>import pandas as pd def buildurl(row, colnames): URL = 'http://someAPI/q?' values = row.one, row.two, row.three # ..ugly.. for value,field in zip(values, colnames): if not pd.isnull(value): URL = '{}{}:{}&amp;'.format(URL, field, value) return URL df = pd.read_csv('urlbuilder.csv', encoding='utf-8-sig', engine='python') colnames = list(df.columns) for row in df.itertuples(): url = buildurl(row, colnames) print(url) </code></pre> <p>It works and it's probably better than a cascade of <code>if not isnull</code>'s. But I still have this loud hunch that there are much more elegant ways of doing this. Yet I can't seem to find them, probably I'm not googling for the right jargon. </p> <p>Please comment </p>
[]
[ { "body": "<p>For anything related to building URL query strings from key-values pairs, you should let <a href=\"https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode\" rel=\"nofollow noreferrer\"><code>urllib.parse.urlencode</code></a> do the work for you. It can also handle quoting and ot...
{ "AcceptedAnswerId": "200211", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T15:31:48.467", "Id": "200209", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Selecting only non-empty cells in a row" }
200209
<p>The following function removes text inside parenthesis, also checks for balanced brackets. Example: <code>RemoveTextInsideParenthesis('Yahoo (Inc)')</code> will return <code>'Yahoo'</code> Any suggestions in how to improve readability/simplify it?</p> <pre><code>def RemoveTextInsideParenthesis(text: str) -&gt; str: """Remove text inside brackets or nested brackets. Creates an array: ['(',')'...], then for each character in text string we compare if character is a bracket, if it is we update a status array. Based on status array we can evaluate if brackets are open and close correctly and then capture text outside parenthesis. Using divmod function we extract index of brackets array. Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder. Documentation for brackets: https://www.unicode.org/charts/nameslist/n_2000.html Args: text: Text to be clean up. Returns: Text inside parenthesis """ openers = (u'(&lt;[{\u0f3a\u0f3c\u169b\u2045\u207d\u208d\u2329\u2768' u'\u276a\u276c\u276e\u2770\u2772\u2774\u27c5\u27e6\u27e8\u27ea' u'\u27ec\u27ee\u2983\u2985\u2987\u2989\u298b\u298d\u298f\u2991' u'\u2993\u2995\u2997\u29d8\u29da\u29fc\u2e22\u2e24\u2e26\u2e28' u'\u3008\u300a\u300c\u300e\u3010\u3014\u3016\u3018\u301a\u301d' u'\u301d\ufd3e\ufe17\ufe35\ufe37\ufe39\ufe3b\ufe3d\ufe3f\ufe41' u'\ufe43\ufe47\ufe59\ufe5b\ufe5d\uff08\uff3b\uff5b\uff5f\uff62' u'\xab\u2018\u201c\u2039\u2e02\u2e04\u2e09\u2e0c\u2e1c\u2e20' u'\u201a\u201e\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d' u'\u2e1d\u2e21\u201b\u201f') closers = (u')&gt;]}\u0f3b\u0f3d\u169c\u2046\u207e\u208e\u232a\u2769' u'\u276b\u276d\u276f\u2771\u2773\u2775\u27c6\u27e7\u27e9\u27eb' u'\u27ed\u27ef\u2984\u2986\u2988\u298a\u298c\u298e\u2990\u2992' u'\u2994\u2996\u2998\u29d9\u29db\u29fd\u2e23\u2e25\u2e27\u2e29' u'\u3009\u300b\u300d\u300f\u3011\u3015\u3017\u3019\u301b\u301e' u'\u301f\ufd3f\ufe18\ufe36\ufe38\ufe3a\ufe3c\ufe3e\ufe40\ufe42' u'\ufe44\ufe48\ufe5a\ufe5c\ufe5e\uff09\uff3d\uff5d\uff60\uff63' u'\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d\u2e1d\u2e21' u'\u201b\u201f\xab\u2018\u201c\u2039\u2e02\u2e04\u2e09\u2e0c' u'\u2e1c\u2e20\u201a\u201e') # Interleave openers and closers: ['(',')'...] brackets = [value for pair in zip(openers, closers) for value in pair] count = [0] * (len(brackets) // 2) # Count open/close brackets as array. clean_string = [] for character in text: for i, bracket in enumerate(brackets): if character == bracket: # Found a bracket in text. # Take index(i) of brackets and 2 as arguments, return a tuple # consisting of their quotient and remainder (a, b). # When index is even, reminder = 0 is an open bracket. # ['(',')','[',']',...] = [0, 1, 2, 3,...] bracket_kind, is_close = divmod(i, 2) # Keep track of brackets in string via count array by adding 1 when an # open bracket is seen or substracting 1 when is closed. # (-1)**0 = 1, (-1)**1 = -1. Balanced brackets, sum will be 0. count[bracket_kind] += (-1)**is_close if count[bracket_kind] &lt; 0: # Unbalanced bracket. count[bracket_kind] = 0 break else: # Character is not a bracket. if not any(count): # Outside brackets. clean_string.append(character) # Return text outside brackets or text if after removing brackets is empty. return ''.join(clean_string).strip() if clean_string else text.strip() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-25T07:06:19.800", "Id": "385424", "Score": "1", "body": "Could you give a few more examples of what the function needs to do? I'm not really understanding the idea behind..." }, { "ContentLicense": "CC BY-SA 4.0", "Creation...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T15:35:04.457", "Id": "200210", "Score": "3", "Tags": [ "python", "unicode", "balanced-delimiters" ], "Title": "Removing text inside brackets" }
200210
<p>I have over 260k lines of data. This code is likely to take more than 30hrs to run. Would like help to speed this up. Or is there a way to use something else like PowerQuery to accomplish this? I am very new so please break it down clearly. </p> <p>There are 260k rows of student achievement data. Some students may have multiple lines with the same school, meaning that they have math, reading, science achievement at one school (3 rows of data, 1 student, 1 school). But then if they transfer schools, they will have two groups of data (1 student, 2 schools). I need to keep only the information for the most recent school. I want to delete based on date. </p> <p><a href="https://i.stack.imgur.com/Apk0S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Apk0S.png" alt="enter image description here"></a></p> <pre><code>Sub RecentEnrollment() Dim lrow As Long, lcol As Long, frow As Long Dim i As Integer, r As Long, c As Long Dim num As Long, pos As Long Dim myrng As Variant Dim namerng As Variant Dim schrange As Variant Dim RowFirst As Double, _ RowLast As Double ' Double is used here to handle the large number of 'rows. Integer and Long are small Bit sizes. Application.ScreenUpdating = False With Worksheets(1) 'Find the last non-blank cell in Column "Student ID" lrow = .Cells(Rows.Count, 1).End(xlUp).Row lcol = .Cells(1, Columns.Count).End(xlToLeft).Column MsgBox "Last Row: " &amp; lrow 'Define the range to search for duplicates. myrng is student id-name 'combos and schrange is studentID-sch combos. You may need to change the 'sheet name. For r = 2 To lrow 'Define the range for the studentId-Name column to search for number of 'times each appears 'num and it's position in the list 'pos Set namerng = .Range(Cells(r, 5), Cells(lrow, 5)) 'Find the first instance of the student name in the file RowFirst = .Cells.Find(What:=.Cells(r, 2), LookAt:=xlWhole,SearchDirection:=xlNext, MatchCase:=False).Row 'Find the last instance of the student name in the file RowLast = .Cells.Find(What:=.Cells(r, 2), LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False).Row Set myrng = .Range(Cells(RowFirst, 5), Cells(RowLast, 5)) Set schrange = .Range(Cells(RowFirst, 3), Cells(RowLast, 3)) For c = 1 To 12 If Application.WorksheetFunction.CountIf(myrng, Cells(r, 5).Value) &gt;= 1 Then 'How many times does the student name-school combo appear? schs = Application.WorksheetFunction.CountIf(schrange, Cells(r, 3).Value) 'How many times does the student name appear in the file? num = Application.WorksheetFunction.CountIf(myrng, Cells(r, 5).Value) 'What is the position of this student record relative to the duplicated records pos = Application.WorksheetFunction.CountIf(namerng, Cells(r, 5).Value) 'For every student record, print the most recent exit date for all enrollments MaxDate = WorksheetFunction.Max(.Range(.Cells(RowFirst, 9), .Cells(RowLast, 9))) Cells(r, 10) = MaxDate Else 'Print most recent exit date Cells(r, 10) = MaxDate End If If num &gt; schs Then If Cells(r, 9) = MaxDate Then Cells(r, 11) = "Keep" Else Cells(r, 11) = "Delete" End If End If Cells(r, 24) = Time Next c Next r End With Application.ScreenUpdating = True End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T16:27:41.677", "Id": "385306", "Score": "0", "body": "As a start, disable screen rendering while your macro works: https://stackoverflow.com/questions/12391786/effect-of-screen-updating . If it is still too slow, try finding bottlen...
[ { "body": "<p>I had some difficulty in getting your code to run. There are a few variables that weren't defined (see comment #1 below). Additionally, you're working <code>With Worksheets(1)</code>, but there are places where you're referencing <code>Cells</code> instead of <code>.Cells</code>. The former refere...
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T16:07:46.893", "Id": "200212", "Score": "3", "Tags": [ "performance", "vba" ], "Title": "VBA script too slow - Checks for duplicate school enrollments and keeps more recent enrollment" }
200212
<p>I'm trying to write some mod rewrite code to redirect pages on a site to <em>always</em> use <strong>www</strong> and this has been working fine:</p> <pre><code>RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] </code></pre> <p>However, I now want to make sure this doesn't happen on my dev environment, which uses the <code>.local</code> domain extension...</p> <p>So I changed it to this:</p> <pre><code>RewriteCond %{HTTP_HOST} !\.local$ RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] </code></pre> <p>Does that seem correct?</p> <p>As I understand it, it states: "If it doesn't END with <code>.local</code> AND it doesn't START with <code>www.</code> THEN do the RewriteRule"?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T16:46:00.873", "Id": "385316", "Score": "0", "body": "`Does that seem correct?` Does it work? Did you test it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T17:12:06.320", "Id": "385322", "S...
[ { "body": "<p>Yes! That is indeed correct. From the docs <a href=\"https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond\" rel=\"nofollow noreferrer\">for <code>RewriteCond</code></a>:</p>\n\n<blockquote>\n <h2>'<code>ornext|OR</code>' (or next condition)</h2>\n \n <p>Use this to combine rul...
{ "AcceptedAnswerId": "200367", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T16:20:21.787", "Id": "200214", "Score": "1", "Tags": [ "regex", ".htaccess" ], "Title": "Rewriting domain only if not on local dev enviroment and forcing www with Mod Rewrite" }
200214
<p>The task: Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.</p> <p>and my solution:</p> <pre><code>import itertools letters_stack = list('abcdefghijklmnopqrstuvwxyz') keypad_dict = {} for num in range(2, 10): size = 3 if num in [7, 9]: size = 4 keypad_dict[str(num)] = letters_stack[:size] letters_stack = letters_stack[size:] def aux(numbers): if len(numbers) == 1: return keypad_dict[numbers[0]] return itertools.product(keypad_dict[numbers[0]], iletters(numbers[1:])) def iletters(numbers): assert len(numbers) &gt; 0 return [''.join(x) for x in aux(numbers)] print list(iletters('234')) # ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi'] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T19:54:54.853", "Id": "385364", "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": "<p>Python allows indexing of strings, for instance <code>'abcdefghijklmnopqrstuvwxyz'[3]</code> returns <code>'d'</code>, so you don't need to turn your string into a list. I would just hardcode the keys: <code>keypad = {1:'abc',2:'def' ...]</code>. You spent more code generating <code>keypad_dict</c...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T17:00:24.390", "Id": "200218", "Score": "7", "Tags": [ "python", "python-2.x", "combinatorics" ], "Title": "Generate Letter Combinations of a Phone Number" }
200218
<p>Here's how my json looks like. I'm trying to write a function which filters based on <em>participantCriteria.criteriaType</em> <em>&amp; participantCriteria._id</em></p> <pre><code>participantCriteria ": [ { "_id": "9be6c6299cca48f597fe71bc99c37b2f", "caption": "XXXXXXXXXXX", "criteriaType": "YYYYYY", "inputSources": [{ "_id": "66be4486ffd3431eb60e6ea6326158fe", "caption": "docId", "participantCriteriaId": "9be6c6299cca48f597fe71bc99c37b2f", "referenceId": null, "type": "identifier" }, { "_id": "1ecdf410b3314865be2b52ca9b4c8539", "caption": "limit", "participantCriteriaId": "9be6c6299cca48f597fe71bc99c37b2f", "referenceId": null, "type": "number" } ] }, </code></pre> <p>Here is the function I have written to filter out the JSON above. </p> <pre><code>filterFunction(id) // returns the above JSON .then((criteria) =&gt; { let filteredCriteria = (participantType ? criteria.filter(({ criteriaType }) =&gt; criteriaType === participantType) : criteria); // if participantType is provided, filter the JSON where criteriaType === participantType filteredCriteria = (participantCriteriaId ? filteredCriteria.filter(({ _id }) =&gt; _id === participantCriteriaId) : filteredCriteria) // if participantCriteriaId is provided, filter the json where _id === participantCriteriaId .map(({ _objectId: _id, caption, criteriaType, inputSources }) =&gt; ({ _id, caption, criteriaType, inputSources: inputSources .map(({ _objectId, caption: inputCaption, isLookup, lookupId, picklistId, type }) =&gt; { let inputSourceType = type; if (type === 'identifier') { inputSourceType = (isLookup &amp;&amp; lookupId) ? 'lookup' : 'key'; } return { _id: _objectId, caption: inputCaption, participantCriteriaId: _id, referenceId: (lookupId || picklistId) || null, type: inputSourceType, }; }), })); res.json({ data: { participantCriteria: filteredCriteria, }, }); return undefined; }) </code></pre> <p>Is there a better way to achieve this filtering ? or Maybe a way to chain the two filters I have added above (the lines where I have added comments). </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T19:03:38.537", "Id": "385343", "Score": "0", "body": "To begin with, your code snippet is invalid. Second, it's very hard to tell that is *code* and what is an object literal. Third, maybe you should put some comments in your code e...
[ { "body": "<p>Is this what you're after?</p>\n\n<pre><code>criteria.filter({ _id, criteriaType } =&gt; (\n (!participantType || participantType === criteriaType)\n &amp;&amp;\n (!participantCriteriaId || participantCriteriaId === _id)\n));\n</code></pre>\n\n<p>If <code>participantType</code> is empty, ...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T18:19:09.460", "Id": "200220", "Score": "6", "Tags": [ "javascript", "node.js", "api", "ecmascript-6" ], "Title": "Filter by multiple options - also only if not empty" }
200220
<p>I have following problem statement</p> <blockquote> <p>A lazy employee works at a multi-national corporation with N offices spread across the globe.</p> <p>They want to work as few days over k weeks as possible.</p> <p>Their company will pay for them to fly up to once per week (on weekends) to a remote office with a direct flight from their current office. Once in an office, they must stay there until the end of the week.</p> <p>If an office observes a holiday while the employee is working there, they get that day off.</p> <p>Find the path that maximizes the employee's vacation over k weeks.</p> <p>Assume they start at a home office H on a weekend (so in the first week, they can be in any office connected to the home office).</p> <p>For example:</p> <p>H&lt;---&gt;A (It means there is a flight path from H to A and vice versa)</p> <p>H&lt;---&gt;B</p> </blockquote> <p>Here is my solution in Python.</p> <pre><code>vacation = [ {&quot;H&quot;: 1, &quot;A&quot;: 0, &quot;B&quot;: 2}, # week 1 {&quot;H&quot;: 0, &quot;A&quot;: 2, &quot;B&quot;: 0} ] flights = [(&quot;H&quot;, &quot;A&quot;), (&quot;H&quot;, &quot;B&quot;)] def get_optimal_path(): all_possible_paths = [] for offices in list(itertools.product(*vacation)): total_cost = 0 week_level = 0 for office in offices: vac_level = vacation[week_level] total_cost += vac_level[office] week_level += 1 if checkIfValidPath(offices[0], offices[1]): all_possible_paths.append((offices, total_cost)) print(max(all_possible_paths, key=lambda x: x[1])) def checkIfValidPath(source, destination): return any(i for i in flights if i[0] == source and i[1] == destination or i[0] == destination and i[1] == source) get_optimal_path() </code></pre> <p>In this example best answer is for the employee to stay at office H in the first week and then move to office A in the second week so the total vacation days will be (1+2)=3. B and A cannot be the answer here because there is no path between them.</p> <p>How can I optimize this code to increase its efficiency? Right now its complexity is n<sup>k</sup> (since we have k weeks).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T18:47:26.380", "Id": "385338", "Score": "0", "body": "Do you have any idea which combinatorial optimization problem this is (or can be reduced to)? This will let you to easily find the best algorithm known today. This seems like a p...
[ { "body": "<p>With this kind of problems it is important to build good mathematical model. After that, the best algorithm known to science can be easily found.</p>\n\n<p>The problem in question seems to be <a href=\"https://en.wikipedia.org/wiki/Longest_path_problem#Acyclic_graphs_and_critical_paths\" rel=\"nof...
{ "AcceptedAnswerId": "200228", "CommentCount": "20", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T18:37:05.253", "Id": "200221", "Score": "8", "Tags": [ "python", "performance", "python-3.x", "graph", "memory-optimization" ], "Title": "Maximize a traveling employee's vacation over k weeks" }
200221