body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm new at this and need assistance with shortening/streamlining the 2 pieces of code that is repeated three times each (this is a shortened version as these pieces of code is repeated many more times).</p> <pre><code>Sub CreateWordDocTest() Dim wApp As Word.Application Dim wDoc As Word.Document Dim myStoryRange As Word.Range Dim InsName, InsNumber, CurrentYear, Industry, AnalysisToolPath, AnalysisToolName, FileNameFragment2, TodaysDate, TemplatePath As String If RADType = "Full" Then TemplatePath = Sheets("Metadata").Range("D8").Value NotificationWhenDone = "Full RAD done" TodaysDate = Now() 'Variable called TodaysDate would now contain the current system date and time Else TemplatePath = Sheets("Metadata").Range("D6").Value NotificationWhenDone = "Summary RAD done" TodaysDate = Now() End If Set wApp = CreateObject("Word.Application") wApp.Visible = True 'Creates an instance of Word an makes it visible Set wDoc = wApp.Documents.Open(TemplatePath, False) 'Opens the chosen full or summary RAD template With wDoc 'Use the With statement to not repeat wDoc many times 'Start at the beginning of the Word document .Application.Selection.HomeKey Unit:=wdStory 'Moves the selection to the beginning of the current story InsName = Sheets("Parameters").Range("D4").Value InsNumber = Sheets("Parameters").Range("D5").Value CurrentYear = Sheets("Parameters").Range("D6").Value Industry = Sheets("Parameters").Range("D7").Value AnalysisToolPath = Sheets("Metadata").Range("D2").Value FileNameFragment2 = InsNumber &amp; " - " &amp; InsName &amp; " " &amp; CurrentYear &amp; ".xlsm" AnalysisToolName = AnalysisToolPath &amp; FileNameFragment2 'Write insurer name For Each myStoryRange In ActiveDocument.StoryRanges With myStoryRange.Find .Text = "&lt;&lt;InsurerName&gt;&gt;" 'Find the exact text in the Word document .Replacement.Text = InsName 'Replace this text with the insurername as defined .Wrap = wdFindContinue 'The find operation continues when the beginning or end of the search range is reached .Execute Replace:=wdReplaceAll 'Finds all occurences and executes the replacement End With Next myStoryRange .Application.Selection.EndOf 'Selects until the end of the document 'Write insurer class For Each myStoryRange In ActiveDocument.StoryRanges With myStoryRange.Find .Text = "&lt;&lt;InsurerClass&gt;&gt;" .Replacement.Text = Industry .Wrap = wdFindContinue .Execute Replace:=wdReplaceAll End With Next myStoryRange .Application.Selection.EndOf 'Write financial year For Each myStoryRange In ActiveDocument.StoryRanges With myStoryRange.Find .Text = "&lt;&lt;CurrentYear&gt;&gt;" .Replacement.Text = CurrentYear .Wrap = wdFindContinue .Execute Replace:=wdReplaceAll End With Next myStoryRange .Application.Selection.EndOf 'Write significant classes For Each myStoryRange In ActiveDocument.StoryRanges With myStoryRange.Find .Text = "&lt;&lt;SignificantClasses&gt;&gt;" .Replacement.Text = SignificantclassesTxt .Wrap = wdFindContinue .Execute Replace:=wdReplaceAll End With Next myStoryRange .Application.Selection.EndOf 'Write insurer number .Application.Selection.Find.Text = "&lt;&lt;InsurerNumber&gt;&gt;" .Application.Selection.Find.Execute .Application.Selection = Sheets("Parameters").Range("D5").Value .Application.Selection.EndOf 'Write analyst name .Application.Selection.Find.Text = "&lt;&lt;AnalystName&gt;&gt;" .Application.Selection.Find.Execute .Application.Selection = UserFullName .Application.Selection.EndOf 'Write RiBS Wording .Application.Selection.Find.Text = "&lt;&lt;RiBSWording&gt;&gt;" .Application.Selection.Find.Execute .Application.Selection = SignificantclassesRiBSTxt .Application.Selection.EndOf End With End Sub </code></pre>
[]
[ { "body": "<p>To streamline this and remove the abundant code duplication, you could extract the two distinct parts you repeat into <code>Sub</code>s taking parameters and then call those. </p>\n\n<pre><code>Private Sub ReplacePlaceholderInDocument(document As Word.Document, placeholder As String, replacement A...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T09:44:35.903", "Id": "197052", "Score": "2", "Tags": [ "performance", "beginner", "vba" ], "Title": "Find and replace placeholders in Word with values from Excel" }
197052
<p>I am looking to simplify this code as it is to bulky for what it is doing. I do not need to stick to jQuery. </p> <p>Simple checkbox in html relates to adding underline to some text:</p> <pre><code>$("#houseOrCar").on("change", function () { if ($(this).is(":checked") ) { $("#houseChosen").css("text-decoration", "none"); $("#carChosen").css("text-decoration", "underline"); } else { $("#houseChosen").css("text-decoration", "underline"); $("#carChosen").css("text-decoration", "none"); }; }); </code></pre>
[]
[ { "body": "<p>You could use a class that would only hold the property for the active element, in our case <code>text-decoration: underline;</code>. Then simply toggle each of the two labels to set on and off this \"active\" class (here called <code>underline</code>).\nSo you don't need to know which label is wh...
{ "AcceptedAnswerId": "197060", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T11:13:43.940", "Id": "197059", "Score": "3", "Tags": [ "javascript" ], "Title": "Add class based on checked checkbox" }
197059
<p>I'm working on a large VBA project for work (around 1000+ lines of vba code) This module is called within another module where I disable everything possible like screen updating, events and setting calculation to manual to improve speed, yet this still seems to run slowly when I'm working with sheets with over 60,000 rows.</p> <p>What this code does, is filter a row in one sheet and copy paste it into another sheet. Then use the data from this to vlookup onto another sheet. I don't understand the syntax of index match, otherwise I could have eliminated the cut/paste option to move the column on the right for the vlookup to speed it up.</p> <p>I suspect a few other elements in this code chunk are slowing it down too. Could you please help me identify what is causing the issue? Is it the autofilter?</p> <pre><code>Sub AdgroupName() Dim LrowBlk As Long LrowBlk = Sheets("Bulk Sheet").Cells(Rows.Count, "H").End(xlUp).Row Sheets("Bulk Sheet").AutoFilterMode = False Sheets("Bulk Sheet").Range("H3:I3").AutoFilter field:=2, Criteria1:="AdGroup" ActiveWorkbook.Sheets("Bulk Sheet").Range("H3:K3" &amp; LrowBlk).SpecialCells(xlCellTypeVisible).Copy Worksheets("Adgroup List").Paste Destination:=Worksheets("Adgroup List").Range("A1") ActiveWorkbook.Sheets("Bulk Sheet").Range("P3:P" &amp; LrowBlk).SpecialCells(xlCellTypeVisible).Copy Worksheets("Adgroup List").Paste Destination:=Worksheets("Adgroup List").Range("E1") With Sheets("Adgroup List") .Columns("C:C").Cut .Columns("E:E").Insert Shift:=xlToRight End With Application.CutCopyMode = False Dim ws As Worksheet Dim LrowSTR As Long Set ws = ThisWorkbook.Sheets("Search Term Report") LrowSTR = Sheets("Search Term Report").Cells(Rows.Count, "H").End(xlUp).Row Dim Strformulas(1 To 3) As Variant With ws Strformulas(1) = "=VLOOKUP($K4,'Adgroup List'!$C:$D,2,0)" Strformulas(2) = "=VLOOKUP($K4,'Adgroup List'!$C:$E,3,0)" .Range("AJ4:AK4").Formula = Strformulas .Range("AJ4:AK" &amp; LrowSTR).FillDown .Range("AJ3").Value = "Campaign ID" .Range("AK3").Value = "AdGroup Name" End With Sheets("Bulk Sheet").AutoFilterMode = False Sheets("Adgroup List").AutoFilterMode = False End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T12:57:39.923", "Id": "379683", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ...
[ { "body": "<p><em>ooh wee</em> Because of the below statement, I'll do this in little steps which may not be the best approach, but should be easy to follow.</p>\n\n<blockquote>\n <p>I don't understand the syntax of index match, otherwise I could have eliminated ...</p>\n</blockquote>\n\n<p><sub><a href=\"http...
{ "AcceptedAnswerId": "197089", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T12:50:53.417", "Id": "197065", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Auto filter data from worksheet and create vlookup using a different worksheet" }
197065
<p>Each day I receive a CSV that contains data concerning a patient record and a related appointment record, each on the same row of the CSV. My code is designed to:</p> <ol> <li>Parse the entered CSV for two separate but related records per row</li> <li>Validate some data (email)</li> <li>Generate some data (duration)</li> <li>Insert the patient record - this returns the ID of the newly created record</li> <li>Add that ID to the appointment record</li> <li>Insert the appointment record</li> </ol> <p>I've left out the parts where I am actually inserting the records because I've been testing a lot and don't feel like going in and deleting thousands of records each day, but ultimately I know the code works. I feel confident in some parts of the code but mostly I do not feel like this is the most sensible way to approach it - primarily the size of <code>PatientHandler.run_csv()</code> and the heavy use of <code>kwargs.pop()</code> cause me to hesitate.</p> <h2>main.py</h2> <pre><code>from patient_handler import PatientHandler from simple_salesforce import Salesforce from secret import * # salesforce credentials def connectToSF(): try: sf = Salesforce(username=sandbox_username, domain='test', password=sandbox_password, security_token=sandbox_token, client_id='PythonUploader') if sf: print('Connection to Salesforce successful\n') return sf except: raise Exception('Connection to Salesforce failed\n') def main(): csv_path = input('Enter full CSV Path:\n') sf = connectToSF() p = PatientHandler(sf) appointments = p.run_CSV(open(csv_path, newline='\n')) appointments = p.dedupe(appointments) if __name__ == '__main__': main() </code></pre> <h2>patient_handler.py</h2> <p><code>fieldMap.py</code> has just a single dict (fieldMap) with the names of the Salesforce fields mapped to the csv column headers I am looking for. The CSV does not change much but the goal was to make this agnostic of the number and order of columns.</p> <pre><code>from validate_email import validate_email from fieldMap import fieldMap from patient import Patient from appointment import Appointment import csv class PatientHandler(object): def __init__(self, sf_instance): self.__record_count = 0 self.__unique_appointments = 0 self.__valid_email_count = 0 self.sf = sf_instance @staticmethod def dedupe(appointments): unique_ids = [] final_list = [] for appt in appointments: if appt['ApptID'] not in unique_ids: unique_ids.append(appt['ApptID']) final_list.append(appt) print('{0} unique appointments found'.format(str(len(final_list)))) return final_list def run_CSV(self, ed): with ed as ed_file: patient_appts = [] header_row = True # prepare to skip to data rows ed_reader = csv.reader(ed_file, delimiter=',', quotechar='"') for row in ed_reader: if not row[0] and not row[1]: # blank or end of document print('\n%i records found' % self.__record_count + '\n%i valid emails found' % self.__valid_email_count) break elif header_row: headers = list(row) i_fname = headers.index(fieldMap['FirstName']) i_mname = headers.index(fieldMap['MiddleName']) i_lname = headers.index(fieldMap['LastName']) i_email = headers.index(fieldMap['Email']) i_start = headers.index(fieldMap['StartTime']) i_end = headers.index(fieldMap['EndTime']) i_location = headers.index(fieldMap['Location']) i_type = headers.index(fieldMap['Type']) i_appt_id = headers.index(fieldMap['ApptID']) i_provider = headers.index(fieldMap['Provider']) header_row = False else: valid_email = validate_email(row[i_email]) a = Appointment(Type=row[i_type], Location=row[i_location], StartTime=row[i_start], EndTime=row[i_end], Provider=row[i_provider], sf_instance=self.sf) p = Patient(FirstName=row[i_fname], MiddleName=row[i_mname], LastName=row[i_lname], Email=row[i_email], ValidEmail=valid_email, LeadSource='Call Center', Appointment=a.__dict__, sf_instance=self.sf) if valid_email: self.__valid_email_count += 1 self.__record_count += 1 patient_id = p.insert() a.setSFID(patient_id) a.insert() entry = {'ApptID': row[i_appt_id], 'Patient': p.__dict__} patient_appts.append(entry) return patient_appts </code></pre> <h2>patient.py</h2> <pre><code>import json class Patient(object): def __init__(self, **kwargs): self.firstName = str(kwargs.pop('FirstName')).title() self.middleName = str(kwargs.pop('MiddleName')).title() self.lastName = str(kwargs.pop('LastName')).title() self.email = kwargs.pop('Email') self.validEmail = kwargs.pop('ValidEmail') self.appointment = kwargs.pop('Appointment') self.leadsource = kwargs.pop('LeadSource') self.sf = kwargs.pop('sf_instance') def insert(self): payload = self.__dict__ payload.pop('appointment') if not payload['validEmail']: payload.pop('email') # remove field with no data payload.pop('validEmail') # perform insert operation, return id to be used in appointment record # self.setSFID(self.sf.Lead.create(payload['id'])) # for now, simulate record insert and assignment of record ID self.setSFID('00Q123456789123') print(json.dumps(payload, indent=4)) def setSFID(self, the_id): self.sfid = the_id </code></pre> <h2>appointment.py</h2> <pre><code>from datetime import datetime, timedelta import json class Appointment(object): def __init__(self, sf_instance, **kwargs): self.provider = kwargs.pop('Provider') self.type = kwargs.pop('Type') self.location = kwargs.pop('Location') self.start = kwargs.pop('StartTime') self.end = kwargs.pop('EndTime') self.duration = self.getDuration(self.start, self.end) self.sf = sf_instance def getDuration(self, start_time, end_time): fmt = '%I:%M %p' tdelta = datetime.strptime( end_time, fmt) - datetime.strptime(start_time, fmt) # time will always be under 1 hour duration = str(tdelta).split(':')[1] return duration def insert(self): # perform insert operation, return id to be used in appointment record # self.setSFID(self.sf.Inquiry__c.create(payload['appointment'])) # for now, simulate record insert payload = self.__dict__ print(json.dumps(payload, indent=4)) def setSFID(self, the_id): self.sfid = the_id </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T14:22:29.553", "Id": "379705", "Score": "1", "body": "I'm pretty sure I'm inserting the records before deduping, so there's that :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T15:18:25.977", "...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T14:09:55.237", "Id": "197068", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Patient Appointment CSV to insert records using simple_salesforce" }
197068
<p>I've managed to create a function that checks whether arrays 'a' and 'b' can 'swap' corresponding values to 'increase' - e.g.:</p> <pre><code>var a = [1,2,3,4,5] // is increasing var a = [1,4,6,7,36] // is increasing var a = [1,6,3,6,5] // not increasing </code></pre> <p>Some successful tests:</p> <pre><code>increaser([5,3,7,7],[1,6,6,9]) - should return 2; a = [1,3,6,7] &amp; b = [5,6,7,9] increaser([1,5,6],[-2,0,2]) - should return 0; already increasing increaser([5,-3,6,4,8],[2,6,-5,1,0]) - should return -1; cannot increase increaser([5,3,7,7,10],[1,6,6,9,9]) - should return 3; a = [1,3,6,7,9], b = [5,6,7,9,10] increaser([2,1,2,3,4,5],[0,1,7,5,2,3]) - should return -1; cannot increase </code></pre> <p>And the function returns 0 if the values in each array are 'already increasing', and returns -1 if the values can't be swapped in order to increase.</p> <p>However, I belive I've written way overcomplex code, particularly for the parts that push checks if the conditions allow the array values to swap, and pushes the new values into the array - e.g.:</p> <pre><code>if(((b[i] &gt;= b[i+1] || b[i] &lt;= finalB[i-1]) &amp;&amp; (a[i] &lt; b[i+1] &amp;&amp; a[i] &gt; finalB[i-1]) &amp;&amp; (b[i] &lt; a[i+1]) &amp;&amp; b[i] &gt; finalA[i-1]) &amp;&amp; ((a[i] &gt;= a[i+1] || a[i] &lt;= finalA[i-1]) &amp;&amp; (b[i] &lt; a[i+1] &amp;&amp; b[i] &gt; finalA[i-1]))) </code></pre> <p>So my question is, how could I have written this to be much simpler? Any advice on writing better code would also be appreciated, as I'm relatively new to JavaScript. Thanks a lot</p> <p>The solution below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function increaser(a, b) { function isAlreadyIncreasing(c, i, arr) { // c = currentValue; i = index; arr = array return ((i == arr.length - 1 &amp;&amp; c &gt; arr[i - 1]) || c &lt; arr[i + 1]); } if (!(a.every(isAlreadyIncreasing) &amp;&amp; b.every(isAlreadyIncreasing))) { console.log('Arrays are not already increasing'); // continue with function var finalA = [], finalB = []; var counter = 0; // no. of changes // for every element, check if each element needs changing for (i = 0; i &lt; a.length; i++) { // for first elements, if conditions match, push elements into new array if (i == 0) { if ((a[0] &gt;= a[1] &amp;&amp; b[0] &lt; a[1] &amp;&amp; a[0] &lt; b[1]) || (b[0] &gt;= b[1] &amp;&amp; a[0] &lt; b[1] &amp;&amp; b[0] &lt; a[1])) { finalA.push(b[0]); finalB.push(a[0]); counter++; } else { finalA.push(a[0]); finalB.push(b[0]); } } // for 2nd - n-1th elements if (i &gt; 0 &amp;&amp; i &lt; a.length - 1) { if (((b[i] &gt;= b[i + 1] || b[i] &lt;= finalB[i - 1]) &amp;&amp; (a[i] &lt; b[i + 1] &amp;&amp; a[i] &gt; finalB[i - 1]) &amp;&amp; (b[i] &lt; a[i + 1]) &amp;&amp; b[i] &gt; finalA[i - 1]) &amp;&amp; ((a[i] &gt;= a[i + 1] || a[i] &lt;= finalA[i - 1]) &amp;&amp; (b[i] &lt; a[i + 1] &amp;&amp; b[i] &gt; finalA[i - 1]))) { finalA.push(b[i]); finalB.push(a[i]); counter++; } else { finalA.push(a[i]); finalB.push(b[i]); } } // for last elements, if conditions match, push elements into new array if (i == a.length - 1) { if ((a[i] &lt;= finalA[i - 1] &amp;&amp; b[i] &gt; finalA[i - 1] &amp;&amp; a[i] &gt; finalB[i - 1]) || (b[i] &lt;= finalB[i - 1] &amp;&amp; a[i] &gt; finalB[i - 1] &amp;&amp; b[i] &gt; finalA[i - 1])) { finalA.push(b[i]); finalB.push(a[i]); counter++; } else { finalA.push(a[i]); finalB.push(b[i]); } } } console.log("Original A: " + a); console.log("Original B: " + b); console.log("Final A: " + finalA); console.log("Final B: " + finalB); console.log("Counter: " + counter); // if counter is 0, return -1, otherwise return counter if (counter == 0) { console.log('But arrays cannot increase'); return -1; } else { return counter; } } else { console.log('Arrays are already increasing'); return 0; } }</code></pre> </div> </div> </p>
[]
[ { "body": "<p>One way to improve the code would be to format the really long conditional statements which seem completely unreadable so they are visually structured.</p>\n\n<p>For example, change</p>\n\n<pre><code>// for 2nd - n-1th elements\n if (i &gt; 0 &amp;&amp; i &lt; a.length-1) {\n if(((b[i] &...
{ "AcceptedAnswerId": "197090", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T15:25:11.470", "Id": "197071", "Score": "4", "Tags": [ "javascript", "algorithm" ], "Title": "Determine whether corresponding elements of two arrays can be swapped to make both arrays increasing" }
197071
<p>I think this is a good solution to finding the largest numeric palindrome that can be formed from the product of two 3-digit numbers... But it seems like there are some improvements that we could make which I haven't thought of...</p> <p>Given <code>int inputs[899]</code> which is initialized by: <code>iota(begin(inputs), end(inputs), 100)</code>, Do you guys have any thoughts on this code:</p> <pre><code>for(auto it = crbegin(inputs); it != crend(inputs) &amp;&amp; *it * *it &gt; max_product; ++it) { const auto rhs = find_if(it, crend(inputs), [lhs = *it](const auto rhs){ const auto input = to_string(lhs * rhs); return equal(cbegin(input), next(cbegin(input), size(input) / 2U), crbegin(input)); }); if(crend(inputs) != rhs) { const auto product = *it * *rhs; if(product &gt; max_product) { max_product = product; max[0] = *it; max[1] = *rhs; } } } </code></pre> <p><a href="https://ideone.com/ObCuXO" rel="nofollow noreferrer"><kbd>Live Example</kbd></a></p> <p>This will correctly find 993 and 913 as the pair of 3-digit numbers that would form the largest numeric palindrome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T18:13:09.310", "Id": "379738", "Score": "0", "body": "@πάνταῥεῖ So I assume that you're asking for like a tag: programming-challenge perhaps? Maybe performance? Sorry I'm just not familiar with posting here. I thought this was on to...
[ { "body": "<p>The main thing I'd suggest is to use functions more to break up your code into more clearly defined subtasks - <em>especially</em> if those subtasks are reusable.</p>\n\n<p>For example, the lambda in your <code>find_if()</code> is:</p>\n\n<pre><code>[lhs = *it](const auto rhs){\n const auto inp...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T16:55:26.663", "Id": "197073", "Score": "0", "Tags": [ "c++", "programming-challenge", "palindrome" ], "Title": "Find largest palindrome from the product of two 3-digit numbers" }
197073
<p>I will write code for all scheduling algorithm in future that is why scheduling.h will contain common data members and member functions. Please help me to improve and optimise this code.</p> <p>scheduling.h</p> <pre><code>#ifndef SCHEDULING_H_ #define SCHEDULING_H_ #include &lt;vector&gt; typedef unsigned int uint; class Scheduling { uint currActiveProcessID; uint timeCounter = 0; std::vector&lt;uint&gt; arrivalTime; //When process start to execute std::vector&lt;uint&gt; burstTime; //process wait to execute after they have arrived std::vector&lt;uint&gt; waitingTime; public: Scheduling(uint); Scheduling() = default; Scheduling(const Scheduling&amp;) = delete; Scheduling &amp;operator=(const Scheduling&amp;) = delete; Scheduling(Scheduling&amp;&amp;) = delete; Scheduling &amp;operator=(Scheduling&amp;&amp;) = delete; ~Scheduling() = default; void calcWaitingTime(); void printInfo(); }; #endif </code></pre> <p>sjf_preemptive.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;array&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::find #include &lt;iterator&gt; // std::begin, std::end #include &lt;limits&gt; //std::numeric_limits #include "scheduling.h" typedef unsigned int uint; Scheduling::Scheduling(uint n) { for ( int i = 0; i &lt; n; i++) { arrivalTime.reserve(n); burstTime.reserve(n); waitingTime.reserve(n); uint val; std::cout &lt;&lt; "Enter arrival time for process " &lt;&lt; i+1 &lt;&lt; "\n"; std::cin &gt;&gt; val; arrivalTime.push_back(val); std::cout &lt;&lt; "Enter burst time for process " &lt;&lt; i+1 &lt;&lt; "\n"; std::cin &gt;&gt; val; burstTime.push_back(val); waitingTime.push_back(0); } } bool isAllZeroes(std::vector&lt;uint&gt;&amp; burstTimeCopy) { for (int i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0) { return false; } else { return true; } } } void Scheduling::calcWaitingTime() { std::vector&lt;uint&gt; burstTimeCopy; burstTimeCopy.reserve(burstTime.size()); uint index = 0; std::vector&lt;uint&gt;::iterator it; while (isAllZeroes(burstTimeCopy) == false) { auto max = std::max_element(arrivalTime.begin(), arrivalTime.end()); if (timeCounter &lt;= *max) { it = arrivalTime.end(); it = std::find(arrivalTime.begin(), arrivalTime.end(), timeCounter); if (it != arrivalTime.end()) { index = std::distance(arrivalTime.begin(), it); } if (burstTimeCopy.empty() == true || index != currActiveProcessID) { burstTimeCopy.push_back(burstTime[index]); } uint minBurstTime = std::numeric_limits&lt;uint&gt;::max(); //Find index with minimum burst Time remaining for (int i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; burstTimeCopy[i] &lt; minBurstTime) { minBurstTime = burstTimeCopy[i]; index = i; } } currActiveProcessID = index; burstTimeCopy[currActiveProcessID] -= 1; for (int i = 0; i &lt; arrivalTime.size(); i++) { if (timeCounter &gt;= arrivalTime[i] &amp;&amp; i != currActiveProcessID &amp;&amp; burstTimeCopy[i] != 0) { waitingTime[i] += 1; } } timeCounter++; } else { uint minBurstTime = std::numeric_limits&lt;uint&gt;::max(); //Find index with minimum burst Time remaining for (int i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; burstTimeCopy[i] &lt; minBurstTime) { minBurstTime = burstTimeCopy[i]; index = i; } } currActiveProcessID = index; burstTimeCopy[index] -= minBurstTime; for (int i = 0; i &lt; arrivalTime.size(); i++) { if (i != currActiveProcessID &amp;&amp; burstTimeCopy[i] != 0) { waitingTime[i] = waitingTime[i] + minBurstTime; } } timeCounter += minBurstTime; } } } void Scheduling::printInfo() { std::cout &lt;&lt; "ProcessID\tArrival Time\tBurst Time\tWaiting Time\n"; for (int i = 0; i &lt; arrivalTime.size(); i++) { std::cout &lt;&lt; i+1 &lt;&lt; "\t\t" &lt;&lt; arrivalTime[i] &lt;&lt; "\t\t" &lt;&lt; burstTime[i]; std::cout &lt;&lt; "\t\t" &lt;&lt; waitingTime[i] &lt;&lt; "\n"; } } int main() { int num; std::cout &lt;&lt; "Enter the number of processes\n"; std::cin &gt;&gt; num; Scheduling shortestJobFirst(num); shortestJobFirst.calcWaitingTime(); shortestJobFirst.printInfo(); } </code></pre>
[]
[ { "body": "<p>Code looks clean overall and quite easy to digest. But there are some issues.</p>\n\n<p>1) isAllZeroes() is not correctly implemented.</p>\n\n<p>2) You make a copy of the burstTime vector but the original doesn't seem to be updated. Why a copy then?</p>\n\n<p>3) The copy is not actually done, only...
{ "AcceptedAnswerId": "197177", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T17:59:03.390", "Id": "197076", "Score": "0", "Tags": [ "c++", "c++11" ], "Title": "Shortest Job First Preemptive" }
197076
<p>This is my first time posting so hopefully I manage to get my question across in a clear and concise manner. I'm not sure this is the right place but someone on StackOverflow suggested I ask here.</p> <p>I am running a cross-validation experiment which involves training a model on a subset of a data set and then validating it against the rest of the data set. This is done by randomly subsetting the data into "folds" and then running the model for each fold. This is then replicated in order to produce standard errors. This is the code I have written in R:</p> <pre><code>reps = 10 folds = 10 rep.Res&lt;-list() for(i in 1:reps){ #i=1 phen2&lt;-phen phen2$fold&lt;-sample(1:folds,nrow(phen),replace=T) fold.Res&lt;-list() for(j in 1:folds){ #j=1 print(paste(i," ",j)) phen3&lt;-phen2 phen3[which(phen3$fold==j),2]&lt;-NA ETA&lt;-list(list(X = geno_centred, model = 'BayesA')) model &lt;- BGLR(y = phen3[,2], ETA = ETA, nIter = 20000, burnIn = 1500, thin=10) model.output&lt;-data.frame(ID = phen3[which(phen2$fold == j), 1], PBV = as.numeric(model$yHat[which(phen2$fold == j)]), phen = phen2[which(phen2$fold == j), 2], rep = i, fold = j) fold.Res[[j]]&lt;-model.output } rep.Res[[i]]&lt;-do.call(rbind,fold.Res) } </code></pre> <p>"phen" is a data frame with a a column of IDs and a column of values. For each replicate, each sample is assigned to a fold randomly. Then, for each fold individuals in the fold are given an NA value, i.e. excluded from the model. </p> <p>The model is run using the Bayesian Generalised Linear Regression (BGLR) package. Unfortunately, I can't really give a reproducible example. X is a scaled centred genotype matrix of -1's, 0's and 1's (not critical for my problem here). The output of the model is then written out for each fold, and then finally for each replicate.</p> <p>My question is, is it possible to vectorize these loops? Using 10 folds and 10 reps means that the model runs 100 time, at 20 000 MCMC iterations each time. This causes the system to slow down significantly before it's even half done. I know that there are many possible approaches using basic R or packages in the tidyverse suite, but I am really a bit lost with such a complex loop. I can imagine that I would try to write at least one of the loops into a function enclosing the other loop but I'm not even sure how that would work...</p> <p>Again, first time posting so please let me know if I need to add anything to my question! Thanks!</p> <p>Edit: Here are a small, random centred genotype matrix (X in the call to BGLR) and an accompanying phen file.</p> <p>X (rows are sample IDs matching those in phen, columns are genomic locations (SNPs)): </p> <pre><code> A B C D E F G H I J K L M N O P Q R S T 1 1 1 1 -1 -1 0 -1 -1 0 1 -1 0 0 0 0 -1 0 0 1 1 2 -1 1 0 -1 0 0 1 -1 1 0 -1 1 -1 0 0 0 -1 -1 -1 -1 3 -1 -1 1 -1 0 0 1 0 0 -1 -1 0 -1 0 0 -1 1 -1 0 -1 4 0 0 -1 1 -1 0 -1 1 1 1 -1 0 0 0 1 1 -1 -1 0 1 5 1 0 1 1 0 0 1 1 0 0 -1 1 1 1 1 -1 -1 0 -1 0 6 1 -1 -1 0 1 -1 1 1 1 -1 0 0 0 -1 0 1 0 -1 -1 0 7 1 -1 -1 1 1 0 -1 1 -1 1 0 -1 1 1 -1 -1 -1 1 -1 1 8 0 1 0 1 -1 -1 0 -1 -1 -1 1 -1 0 0 0 0 0 -1 0 -1 9 -1 1 -1 -1 1 0 0 0 0 0 1 0 -1 -1 -1 0 1 -1 0 -1 10 0 0 -1 1 0 0 -1 0 -1 1 1 1 0 0 1 1 0 -1 0 0 </code></pre> <p>Phen:</p> <pre><code>ID phenotype 1 1000 2 1500 3 1200 4 500 5 700 6 2000 7 1500 8 1000 9 1300 10 900 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T22:18:51.373", "Id": "379768", "Score": "0", "body": "Welcome to Code Review! I hope you get some great answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T01:34:58.080", "Id": "379783", ...
[ { "body": "<p>I'm not familiar with BGLR but I think I can give some pointers.</p>\n\n<p>First to your direct question - yes you can vectorise. A simple approach is to use one of the apply functions. <code>lapply</code> usually is a good fit for such loops. However this is not a magic bullet and I would stro...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T22:05:23.173", "Id": "197085", "Score": "4", "Tags": [ "r", "vectorization" ], "Title": "Vectorizing a complex nested for loop in R (running models on different subsets of a data set, subsetting the data differently for each loop)" }
197085
<h2>Introduction</h2> <p>I implemented a restricted version of the sorting algorithm, the one that works only with unsigned integers. I wanted to try using <code>std::stable_partition</code> with bitmask, as I chose base 2. The reason partition works here is because there are only two "bins", thus it is somewhat like partitioning. I mandated customizing the maximum power of two that is encountered in the sequence.</p> <hr> <h2>Code</h2> <pre><code>#include &lt;iterator&gt; #include &lt;algorithm&gt; namespace shino { template &lt;typename BidirIterator&gt; void radix_sort(BidirIterator first, BidirIterator last, unsigned upper_power_bound) { using category = typename std::iterator_traits&lt;BidirIterator&gt;::iterator_category; using value_type = typename std::iterator_traits&lt;BidirIterator&gt;::value_type; static_assert(std::is_base_of_v&lt;std::bidirectional_iterator_tag, category&gt;, "At least bidirectional iterators are required"); static_assert(std::is_integral_v&lt;value_type&gt; and std::is_unsigned_v&lt;value_type&gt;, "Only unsigned integers are supported for radix sort"); value_type mask = 1; for (auto power = 0u; power &lt;= upper_power_bound; ++power) { auto predicate = [mask](const auto&amp; value) { return !(value &amp; mask); }; std::stable_partition(first, last, predicate); mask &lt;&lt;= 1; } } } </code></pre> <hr> <h2>Weird results</h2> <p>The algorithm has a lottle of wiggle regarding the constant factor, though it is linear. The picture below is for highest power of 16, x-axis is element count, and y-axis is nanoseconds (sorry I'm not on good terms with gnuplot). So it takes ~1.6 <em>milliseconds</em> to sort 30'000 elements, which is I think quite a lot for linear sorting algorithm.</p> <p><a href="https://i.stack.imgur.com/ALOyL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ALOyL.png" alt="Performance of radix sort"></a></p> <p>I believe those spikes are context switches, but I couldn't verify that. It seems like there is no way to reliably track them and correspond to the spike.</p> <hr> <h2>Full code</h2> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;random&gt; std::vector&lt;unsigned&gt; generate_vector(std::size_t size, unsigned power_limit) { auto generator = [power_limit] { static std::mt19937 twister{}; static std::uniform_int_distribution&lt;unsigned &gt; dist{0u, (1u &lt;&lt; power_limit)}; return dist(twister); }; std::vector&lt;unsigned&gt; v(size); std::generate(v.begin(), v.end(), generator); return v; } #include &lt;iterator&gt; #include &lt;algorithm&gt; namespace shino { template &lt;typename BidirIterator&gt; void radix_sort(BidirIterator first, BidirIterator last, unsigned upper_power_bound) { using category = typename std::iterator_traits&lt;BidirIterator&gt;::iterator_category; using value_type = typename std::iterator_traits&lt;BidirIterator&gt;::value_type; static_assert(std::is_base_of_v&lt;std::bidirectional_iterator_tag, category&gt;, "At least bidirectional iterators are required"); static_assert(std::is_integral_v&lt;value_type&gt; and std::is_unsigned_v&lt;value_type&gt;, "Only unsigned integers are supported for radix sort"); value_type mask = 1; for (auto power = 0u; power &lt;= upper_power_bound; ++power) { auto predicate = [mask](const auto&amp; value) { return !(value &amp; mask); }; std::stable_partition(first, last, predicate); mask &lt;&lt;= 1; } } } #include &lt;chrono&gt; #include &lt;atomic&gt; namespace shino { template &lt;typename Clock = std::chrono::high_resolution_clock&gt; class stopwatch { const typename Clock::time_point start_point; public: stopwatch() : start_point(Clock::now()) {} template &lt;typename Rep = typename Clock::duration::rep, typename Units = typename Clock::duration&gt; Rep elapsed_time() const { std::atomic_thread_fence(std::memory_order_relaxed); auto counted_time = std::chrono::duration_cast&lt;Units&gt;(Clock::now() - start_point).count(); std::atomic_thread_fence(std::memory_order_relaxed); return static_cast&lt;Rep&gt;(counted_time); } }; using precise_stopwatch = stopwatch&lt;&gt;; using system_stopwatch = stopwatch&lt;std::chrono::system_clock&gt;; using monotonic_stopwatch = stopwatch&lt;std::chrono::steady_clock&gt;; } #include &lt;stdexcept&gt; #include &lt;fstream&gt; int main() { std::ofstream measurings("measurings.csv"); if (!measurings) throw std::runtime_error("measurings file opening failed"); for (unsigned power = 4; power &lt;= 16; ++power) { for (auto size = 0ull; size &lt;= 20'000; ++size) { std::cout &lt;&lt; "radix sorting vector of size " &lt;&lt; size &lt;&lt; '\n'; auto input = generate_vector(size, power); shino::precise_stopwatch stopwatch; shino::radix_sort(input.begin(), input.end(), power); auto elapsed_time = stopwatch.elapsed_time(); measurings &lt;&lt; power &lt;&lt; ',' &lt;&lt; size &lt;&lt; ',' &lt;&lt; elapsed_time &lt;&lt; '\n'; if (not std::is_sorted(input.begin(), input.end())) throw std::logic_error("radix sort doesn't work correctly on size " + std::to_string(size)); } } } </code></pre> <p>The code records performance and checks if sort actually worked correctly. So if you make any changes, just run the code to test it. <code>stopwatch</code> code is taken from <a href="https://codereview.stackexchange.com/a/196253/93301">here</a>. In fact, I believe it deserves a review on its own.</p> <p>I couldn't get gnuplot to plot 3d graphs, sorry no pics for the changes related to maximum power.</p> <hr> <h2>Concerns</h2> <ul> <li>Is algorithm implemented well?</li> </ul> <p>Are there points to improve performance? Make a better use of standard library?</p> <ul> <li>Will the inner lambda cause code bloat?</li> </ul> <p>Lambdas are anonymous classes, so will be instantiated for every version of radix sort itself. I'm unsure if using lambda was a wise choice.</p> <ul> <li>Anything else that comes to mind</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T01:42:26.410", "Id": "379784", "Score": "1", "body": "One issue is when you calculate the elapsed time. This should be done right after the sorting is done, _before_ you start doing any output. That output will have variable amoun...
[ { "body": "<p>I'll focus <em>just</em> on the algorithm (not the timing code), and the questions.</p>\n\n<pre><code>static_assert(std::is_base_of_v&lt;std::bidirectional_iterator_tag, category&gt;,\n \"At least bidirectional iterators are required\");\nstatic_assert(std::is_integral_v&lt;value_type&gt; and s...
{ "AcceptedAnswerId": "197116", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T22:53:57.030", "Id": "197087", "Score": "8", "Tags": [ "c++", "sorting", "c++17", "benchmarking" ], "Title": "Implementing and benchmarking Radix Sort on unsigned integers" }
197087
<p>I'm dealing with design layers of an application. Basically what I've so far are:</p> <ul> <li>Business </li> <li>Architecture: Client-Server</li> <li>Techonologies: PHP+MySQL, HTML5, JS, 3rd parties APIs</li> </ul> <p>My app</p> <ul> <li>Data Sources: MySql databases, 3rd party APIs</li> <li>Data Layer: Interface with CRUD operations, PDO for accessing DBs, Classes implementing CRUD interface, Classes for communication with APIs</li> <li>Repository: Classes &amp; Interfaces with bussiness methods for accessing datasource.</li> <li>Business object: value objects and business rules</li> <li>Application layer: controls flow between Data Layer and Presentation.</li> <li>Presentation layer: html design with javascript &amp; ajax &amp; php code. Interacts with application layer for data retrieval</li> </ul> <p>Implementation</p> <p>Data Source</p> <p>1x MySQL Database</p> <p>1x 3rd party api</p> <p>Data Layer</p> <pre><code>interface DSOps { /* * @return array */ function read($sql); /* * @return array */ function readAll($sql); /* * @return boolean */ function save($sql); /* * @return boolean */ function delete($sql); } use PDO; class DSSql implements DSOps { private $bd; public function __construct( PDO $bd) { $this-&gt;bd = $bd; } public function read($sql) { $stmt=$this-&gt;bd-&gt;prepare($sql); $stmt-&gt;execute(); $response = $stmt-&gt;fetch(PDO::FETCH_ASSOC); return $response; } public function readAll($sql) { $stmt=$this-&gt;bd-&gt;prepare($sql); $stmt-&gt;execute(); $response = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC); return $response; } public function save($sql, $params) { $stmt=$this-&gt;bd-&gt;prepare($sql); return $stmt-&gt;execute($params); } public function borrar($sql, $params) { $stmt=$this-&gt;bd-&gt;prepare($sql); return $stmt-&gt;execute($params); } } </code></pre> <p>Repositories:</p> <pre><code>interface QueryClients { /* * @return Client */ public function searchById($id); /* * @return array() */ public function searchAll(); /* * @return int */ public function count(); } class RepoClients implements QueryClients { private $ds; public function __construct(DSOps $_ds) { $this-&gt;ds = $_ds; } /* * @return array */ public function searchById($id) { $sql = " SELECT * FROM clients WHERE id=$id;"; $response=$this-&gt;ds-&gt;read($sql); return $response; } /* * @return array() */ public function searchAll() { $sql = " SELECT * FROM clients; "; $response=$this-&gt;searchAll($sql); return $response; } .... } </code></pre> <p>I've multiple modules that implements the same design. When implementing these design I have the following doubts:</p> <ol> <li>Is correct to form queries at repository classes?</li> <li>Where should I handle SQL errors? Having an SQLError </li> <li>How should I handle access to APIs?</li> <li>As my app has role based access for users, how does this impacts my design/implementation? Based on logged user role I've create different classes using same interface but implementing different queries to database.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T08:07:05.247", "Id": "379795", "Score": "0", "body": "Is this part of a larger framework like laravel ?" } ]
[ { "body": "<h3>SQL injection</h3>\n\n<p>First of all, your PDO code is a <a href=\"https://en.wikipedia.org/wiki/Cargo_cult_programming\" rel=\"nofollow noreferrer\">straw plane that never flies</a>. Using <code>prepare()</code> like that makes very little sense, leaving all your queries widely exposed to SQL i...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T02:43:40.807", "Id": "197095", "Score": "4", "Tags": [ "php", "object-oriented", "design-patterns", "mysql", "n-tier" ], "Title": "PHP Application layers" }
197095
<p>I just made this link please check this out <strong><a href="https://mrnewtoa8.000webhostapp.com/" rel="nofollow noreferrer">Online Results</a></strong></p> <p>I need to select data between 2 values from a table by using MAX because each SID has different VID.</p> <p>My code:</p> <pre><code>$sql = mysqli_query($con, "SELECT * FROM `tests` WHERE `VID` BETWEEN (SELECT MAX(`VID`) FROM `tests`)-6 AND (SELECT MAX(`VID`) FROM `tests`)-3 ORDER BY `SID` ASC, `VID` ASC;"); </code></pre> <p>it works on a small table:</p> <pre><code>INSERT INTO `tests` (`ID`, `SID`, `VID`, `Text`) VALUES (1, 1, 1, 'test'), (2, 1, 2, 'test'), (3, 1, 3, 'test'), (4, 1, 4, 'test'), (5, 1, 5, 'test'), (6, 1, 6, 'test'), (7, 1, 7, 'test'), (8, 1, 8, 'test'), (9, 1, 9, 'test'), (10, 1, 10, 'test'), (11, 1, 11, 'test'), (12, 2, 1, 'test'), (13, 2, 2, 'test'), (14, 2, 3, 'test'), (15, 2, 4, 'test'), (16, 2, 5, 'test'), (17, 2, 6, 'test'), (18, 2, 7, 'test'), (19, 2, 8, 'test'), (20, 3, 1, 'test'), (21, 3, 2, 'test'), (22, 3, 3, 'test'), (23, 4, 1, 'test'), (24, 4, 2, 'test'), (25, 4, 3, 'test'), (26, 4, 4, 'test'), (27, 4, 5, 'test'), (28, 4, 6, 'test'), (29, 4, 7, 'test'), (30, 4, 8, 'test'), (31, 4, 9, 'test'); </code></pre> <p>However, on <a href="https://ufile.io/qyxnb" rel="nofollow noreferrer">a table with over 6000 rows</a> it does not complete in any reasonable time.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T12:39:06.497", "Id": "379889", "Score": "1", "body": "Does your table have any indexes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T06:45:51.043", "Id": "379980", "Score": "2", "body":...
[ { "body": "<p>First ID appears to be monotonically increasing, and appears to be the primary key. If so then when you declare ID in the table definition you can use auto increment and you don't need to include it in the insert statement values. This may improve the performance of the insert statements because t...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T02:51:16.100", "Id": "197097", "Score": "-1", "Tags": [ "php", "sql", "mysql", "time-limit-exceeded", "database" ], "Title": "MySQL select between MAX-n1 AND MAX-n2" }
197097
<p>As <a href="https://codereview.stackexchange.com/q/196934">before</a>, I am moving into C++ and would like to learn about its idioms. I have moved from Project Euler to CodeKata as the former is based on algorithms, rather than language constructs (as suggested by <a href="https://codereview.stackexchange.com/u/162379">bruglesco</a> in the comments).</p> <p><a href="http://codekata.com/kata/kata02-karate-chop/" rel="noreferrer">Description</a> (slightly modified):</p> <blockquote> <p>Write a binary search method that takes an integer search target and a sorted array of integers. It should return the integer index of the target in the array, or -1 if the target is not in the array.</p> </blockquote> <p>main.cpp:</p> <pre><code>#include &lt;assert.h&gt; #include &lt;math.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; int binarySearch(int needle, std::vector&lt;int&gt; values); unsigned int middleOf(int leftBound, int rightBound); void testBinarySearch(); int main() { testBinarySearch(); return 0; } int binarySearch(int needle, std::vector&lt;int&gt; values) { constexpr int NOT_FOUND = -1; const unsigned int length = values.size(); // If empty, needle will never be found if (length == 0) { return NOT_FOUND; } // Bracket the needle with [leftBound, rightBound] unsigned int leftBound = 0; unsigned int rightBound = length - 1; // Start at middle of bracket // If even number of entries, use the one on the left unsigned int position = middleOf(leftBound, rightBound); // Binary search ends in at most ceil of log base 2 of length + 1 const unsigned int maxIterations = ceil(log(length) / log(2)) + 1; int value; for (unsigned int iteration = 0; iteration &lt; maxIterations; ++iteration) { value = values.at(position); if (value == needle) { return position; } else if (value &lt; needle) { leftBound = position; rightBound = rightBound; position = position + middleOf(leftBound, rightBound); } else if (value &gt; needle) { leftBound = leftBound; rightBound = position; position = position - middleOf(leftBound, rightBound); } } return NOT_FOUND; } unsigned int middleOf(int leftBound, int rightBound) { return (rightBound - leftBound + 1) / 2; } // Test cases given on website void testBinarySearch() { std::vector&lt;int&gt; values; assert(-1 == binarySearch(3, values)); values.push_back(1); assert(-1 == binarySearch(3, values)); assert( 0 == binarySearch(1, values)); values.push_back(3); values.push_back(5); assert( 0 == binarySearch(1, values)); assert( 1 == binarySearch(3, values)); assert( 2 == binarySearch(5, values)); assert(-1 == binarySearch(0, values)); assert(-1 == binarySearch(2, values)); assert(-1 == binarySearch(4, values)); assert(-1 == binarySearch(6, values)); values.push_back(7); assert( 0 == binarySearch(1, values)); assert( 1 == binarySearch(3, values)); assert( 2 == binarySearch(5, values)); assert( 3 == binarySearch(7, values)); assert(-1 == binarySearch(0, values)); assert(-1 == binarySearch(2, values)); assert(-1 == binarySearch(4, values)); assert(-1 == binarySearch(6, values)); assert(-1 == binarySearch(8, values)); std::cout &lt;&lt; "All tests passed!"; } </code></pre> <p>I will add files to GitLab <a href="https://gitlab.com/FromTheStackAndBack/CodeKata/tree/master" rel="noreferrer">here</a> and make changes to them as I receive feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T09:26:54.217", "Id": "379808", "Score": "0", "body": "The problem statement itself goes against the normal C++ idioms, so I wonder about its suitability for the stated purpose. You would implement something with the same kind of AP...
[ { "body": "<p>Honestly, there's nothing wrong with this code. It's quite good how it is. There are a few minor things you could add, but if this came by me in a code review at work, I probably wouldn't have much to say. So here's what I can say:</p>\n<h1>Use <code>const</code> for Things that Won't Change</h1>\...
{ "AcceptedAnswerId": "197105", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T03:17:24.217", "Id": "197099", "Score": "8", "Tags": [ "c++", "programming-challenge" ], "Title": "CodeKata 02 in C++" }
197099
<p>Is there any way to make this program run in better time ? While running, it is taking 1 second for the sample test case to pass and 5-10 seconds for the rest of the test cases.</p> <p><strong>Problem statement</strong> </p> <blockquote> <p>A smart-set is a set of distinct numbers in which all the elements have the same number of <code>1</code>s in their binary form. The set of all smallest elements from each smart-set that can be formed from a given array of distinct positive numbers is known as the smartest-set.</p> <p>So given an array of distinct numbers, outline the elements of the smartest-set in ascending sorted order.</p> </blockquote> <p>Example</p> <blockquote> <p>Let the array be <code>{6 , 2 , 11 , 1 , 9 , 14 , 13 , 4 , 18}</code>. </p> <p>In binary form the set is <code>{110, 010, 1011, 0001, 1001, 1110, 1101, 0100, 10010}</code>. </p> <p>The smart-sets are <code>{1, 2, 4}, {6, 9, 18}, {11, 13, 14}</code>.</p> <p>The smartest-set is <code>{1,6,11}</code> as each element is the smallest element from each smart-set.</p> </blockquote> <p><strong>Input Format</strong></p> <p>The first line of input consists of an integer <code>t</code>. This is the number of test cases. For each test case, the first line of input contains an integer <code>n</code>. Here <code>n</code> is the number of elements in the array. The next line contains <code>n</code> space separated distinct integers which are the elements of the array.</p> <p><strong>Output Format</strong></p> <p>The output will space separated integer elements of the smartest-set in ascending order.</p> <p><strong>Constraints</strong></p> <blockquote> <pre><code>0 &lt; t &lt; 1000 (This is the number of test cases ) 2 &lt; n &lt; 10000 (This is the number of integer elements of the array) 1 &lt; Xi &lt; 100000 (This is the size of each element of the array) SAMPLE STDIN 1 3 9 6 2 11 1 9 14 13 4 18 3 7 3 1 3 1 2 4 SAMPLE STDOUT 1 6 11 1 3 7 1 </code></pre> </blockquote> <p><strong>Code</strong></p> <pre><code>test_case=input() for case_num in range(int(test_case)): num_of_elements=input() arr=input() dictn={} #print (num_of_elements,arr) for bin_values in list(map(int,arr.split())): count=0 for occurence in [int(x) for x in list('{0:0b}'.format(bin_values))]: if occurence==1: count=count+1 dictn[bin_values]=count v = {} for key, value in sorted(dictn.items()): v.setdefault(value, []).append(key) lst=[] for key,value in (v.items()): x=min(value) lst.append(str(x)) s= ' ' s = s.join(lst) print (s) </code></pre>
[]
[ { "body": "<h1>Review</h1>\n\n<ol>\n<li>Don't <code>print()</code> but <code>return</code> variables, so other functions can reuse the outcome.</li>\n<li>Split up your code into functions, for re usability and to easier test parts of your code.</li>\n<li>Write test cases using the <code>unittest</code> module r...
{ "AcceptedAnswerId": "197124", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T05:14:55.923", "Id": "197102", "Score": "3", "Tags": [ "python", "programming-challenge", "array" ], "Title": "Finding the smartest set from an array of numbers" }
197102
<p>I have coded the following quick sort implementation. There are few things that still makes this code ugly and redundant.</p> <p><strong>1. Handling Arrays of Primitives</strong> I have to write a separate implementation of QuickSort to handle each of the 7 primitive types. Is there a way, this could be done in a much better way?</p> <p><strong>2. Usage of "private static" - nested classes</strong> Is it okay to model the nested classes that encapsulates the quicksort logic for each variant of the input type as 'private static'. Will there be any other better way to code them yet having them in the same java file.</p> <p><strong>3. <code>Comparator&lt;? super T&gt;</code></strong> <br> In the below snippet,</p> <pre><code>private static &lt;T&gt; int partition(T[] values, int start, int end, Comparator&lt;? super T&gt; comparator) { T pivot = values[end]; int partitionIndex = 0; for (int i = 0; i &lt; end; ++i) { if (comparator != null) { if (comparator.compare(values[i], pivot) &lt;= 0) { swap(values, i, partitionIndex); } } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } </code></pre> <p>Have declared a Comparator whose parameterized type could be just T or it's sub types. Is it okay and conventional to accept a child class comparator to compare base class types. I borrowed this logic from </p> <pre><code>Arrays.sort(T[], Comparator&lt;? super T&gt;) </code></pre> <p>Just wanted to know the rationale behind specifying '? super T' instead of just T.</p> <p><strong>4. <code>&lt;T extends Comparable&lt;T&gt;&gt;</code></strong> <br> In the below snippet, </p> <pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(T[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } </code></pre> <p>I have tried to make sure at the compile time itself, the array elements are supposed to be implementing Comparable interface. Is the above one > is okay or can it be made better.</p> <p>Here's the complete compilable code of QuickSort.</p> <pre><code>//QuickSort.java package com.gnanavad.dsa; import java.util.Comparator; public class QuickSort { // QuickSort API - for arrays of all 7 primitive types // in java except boolean. public static void sort(byte[] values) { QuickSortPrimitives_Byte.sort(values); } public static void sort(short[] values) { QuickSortPrimitives_Short.sort(values); } public static void sort(int[] values) { QuickSortPrimitives_Int.sort(values); } public static void sort(long[] values) { QuickSortPrimitives_Long.sort(values); } public static void sort(float[] values) { QuickSortPrimitives_Float.sort(values); } public static void sort(double[] values) { QuickSortPrimitives_Double.sort(values); } public static void sort(char[] values) { QuickSortPrimitives_Char.sort(values); } // QuickSort API for arrays of POJOs which doesn't implement Comparable // interface. // Hence, appropriate Comparator has to be supplied as one of the inputs. public static &lt;T&gt; void sort(T[] values, Comparator&lt;? super T&gt; comparator) { QuickSortNonPrimitives_ExternalComparator.sort(values, comparator); } // QuickSort API for arrays of Boxed Types and POJOs that are Comparable. public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(T[] values) { QuickSortNonPrimitives_ImplicitComparator.sort(values); } private static void validateInputArray(Object values) { if (values == null) { throw new IllegalArgumentException("Input array is null."); } } /* * Implementation of QuickSort encapsulated in a class of their own for each * variant of input types. **/ // Both the NonPrimitive versions of QuickSort shares the same swap() logic // and hence the base class. private static abstract class QuickSortNonPrimitives { protected static &lt;T&gt; void swap(T[] values, int i, int partitionIndex) { T tmp = values[i]; values[i] = values[partitionIndex]; values[partitionIndex] = tmp; } } private static class QuickSortNonPrimitives_ImplicitComparator extends QuickSortNonPrimitives { public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(T[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static &lt;T extends Comparable&lt;T&gt;&gt; void quickSort(T[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static &lt;T extends Comparable&lt;T&gt;&gt; int partition(T[] values, int start, int end) { T pivot = values[end]; int partitionIndex = 0; for (int i = 0; i &lt; end; ++i) { if (values[i] != null) { if (((Comparable&lt;T&gt;) values[i]).compareTo(pivot) &lt;= 0) { swap(values, i, partitionIndex); } } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } } private static class QuickSortNonPrimitives_ExternalComparator extends QuickSortNonPrimitives { public static &lt;T&gt; void sort(T[] values, Comparator&lt;? super T&gt; comparator) { validateInputArray(values); quickSort(values, 0, values.length - 1, comparator); } private static &lt;T&gt; void quickSort(T[] values, int start, int end, Comparator&lt;? super T&gt; comparator) { if (start &lt; end) { int partitionIndex = partition(values, start, end, comparator); quickSort(values, 0, partitionIndex - 1, comparator); quickSort(values, partitionIndex + 1, end, comparator); } } private static &lt;T&gt; int partition(T[] values, int start, int end, Comparator&lt;? super T&gt; comparator) { T pivot = values[end]; int partitionIndex = 0; for (int i = 0; i &lt; end; ++i) { if (comparator != null) { if (comparator.compare(values[i], pivot) &lt;= 0) { swap(values, i, partitionIndex); } } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } } private static class QuickSortPrimitives_Int { public static void sort(int[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(int[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(int[] values, int start, int end) { int partitionIndex = 0; int pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(int[] values, int index1, int index2) { int tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } private static class QuickSortPrimitives_Short { public static void sort(short[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(short[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(short[] values, int start, int end) { int partitionIndex = 0; short pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(short[] values, int index1, int index2) { short tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } private static class QuickSortPrimitives_Float { public static void sort(float[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(float[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(float[] values, int start, int end) { int partitionIndex = 0; float pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(float[] values, int index1, int index2) { float tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } private static class QuickSortPrimitives_Double { public static void sort(double[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(double[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(double[] values, int start, int end) { int partitionIndex = 0; double pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(double[] values, int index1, int index2) { double tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } private static class QuickSortPrimitives_Char { public static void sort(char[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(char[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(char[] values, int start, int end) { int partitionIndex = 0; double pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(char[] values, int index1, int index2) { char tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } private static class QuickSortPrimitives_Byte { public static void sort(byte[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(byte[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(byte[] values, int start, int end) { int partitionIndex = 0; byte pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(byte[] values, int index1, int index2) { byte tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } private static class QuickSortPrimitives_Long { public static void sort(long[] values) { validateInputArray(values); quickSort(values, 0, values.length - 1); } private static void quickSort(long[] values, int start, int end) { if (start &lt; end) { int partitionIndex = partition(values, start, end); quickSort(values, 0, partitionIndex - 1); quickSort(values, partitionIndex + 1, end); } } private static int partition(long[] values, int start, int end) { int partitionIndex = 0; double pivot = values[end]; for (int i = 0; i &lt; end; i++) { // move the small ones to the left of partitionIndex. if (values[i] &lt; pivot) { swap(values, partitionIndex, i); partitionIndex++; } } // swap the pivot. swap(values, partitionIndex, end); return partitionIndex; } private static void swap(long[] values, int index1, int index2) { long tmp = values[index1]; values[index1] = values[index2]; values[index2] = tmp; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T07:13:40.210", "Id": "197106", "Score": "2", "Tags": [ "java", "generics", "quick-sort" ], "Title": "Classical Single Pivot QuickSort implementation in Java using Generics" }
197106
<p>Whilst learning Rust I am solving different algorithm problems. Below is a solution to largest rectangle in histogram. Algorithm is well described <a href="https://stackoverflow.com/questions/4311694/maximize-the-rectangular-area-under-histogram">here</a>: </p> <p>Although code below does the job it is very verbose (much more than my C++ solution).</p> <pre><code>pub fn largest_rectangle(v: &amp;mut Vec&lt;i32&gt;) -&gt; i32 { let mut stack: Vec&lt;usize&gt; = Vec::new(); // populate stack with 0 - (index of first element in 'v') to avoid checking for empty stack stack.push(0); // insert -1 from both sides so that we don't have to test for corner cases v.insert(0, -1); v.push(-1); let mut answer = 0; for (i, h) in v.iter().enumerate() { let idx = i as i32; if h &gt; &amp;v[stack.last().unwrap().clone()] { stack.push(i); } else { while h &lt; &amp;v[stack.last().unwrap().clone()] { let last_bar = v[stack.pop().unwrap().clone()]; let area = last_bar * (idx - 1 - stack.last().unwrap().clone() as i32); answer = std::cmp::max(area, answer); } stack.push(i); } } answer } </code></pre> <p>My questions:</p> <ol> <li>Is it possible to get rid of those 'unwrap().clone()' constructs?</li> <li>Why does compiler make me use references in if statements (h > &amp;v[] and h &lt; &amp;v[])?</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T09:05:49.907", "Id": "197112", "Score": "2", "Tags": [ "algorithm", "rust" ], "Title": "Largest Rectangle in Histogram in Rust" }
197112
<p>I am currently writing mergesort in Python and have implemented it to work. I have noticed, though, that it is very slow compared to the standard sorted() method. I understand it will always be faster but I am open to suggestions in terms of optimization.</p> <pre><code>def merge(left,right): sortedArray=[] l_idx,r_idx=0,0 #set index for left and right array #compare values of left and right array while l_idx&lt;len(left) and r_idx&lt;len(right): if(left[l_idx] &lt; right[r_idx]): sortedArray.append(left[l_idx]) l_idx+=1 else: sortedArray.append(right[r_idx]) r_idx+=1 if l_idx==len(left): sortedArray.extend(right[r_idx:]) else: sortedArray.extend(left[l_idx:]) return sortedArray def mergesort(A): if len(A)&lt;=1: return A middle=len(A)//2 left,right=mergesort(A[:middle]),mergesort(A[middle:]) return merge(left,right) </code></pre> <p>Thank you for any feedback</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T08:32:14.207", "Id": "460083", "Score": "0", "body": "One thing killing performance is bound to be allocating a fresh buffer in each and every call." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T12:22:22.810", "Id": "197118", "Score": "2", "Tags": [ "python", "sorting", "mergesort" ], "Title": "Mergesort in Python optimization" }
197118
<p>I have to solve an exercise from ANSI C book:</p> <blockquote> <p>Add the commands to print the top elements of the stack without popping, to duplicate it, and to swap the top two elements. Add a command to clear the stack.</p> </blockquote> <p>Here is my implementation in RPN Calculator:</p> <pre><code>#include &lt;ctype.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define MAXOP 100 #define NUMBER '0' #define MAXVAL 100 #define BUFSIZE 100 int getop(char []); void push(double); double pop(void); double top(void); void clear(void); void swap(void); void duplicate(void); int getch(void); void ungetch(int); int sp = 0; double val[MAXVAL]; char buf[BUFSIZE]; int bufp = 0; int main(void) { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor\n"); break; case '%': op2 = pop(); if (op2 != 0) push((int) pop() % (int) op2); else printf("error: zero divisor\n"); break; case 'c': clear(); printf("stack empty!\n"); break; case 'd': duplicate(); printf("duplicate element\n"); break; case 's': swap(); printf("swap elements\n"); break; case '?': printf("top element on the stack: %f\n", top()); break; case '\n': printf("\t%.8g\n", pop()); break; default: printf("error: unknown command %s\n", s); break; } } return 0; } void push(double f) { if (sp &lt; MAXVAL) val[sp++] = f; else printf("error: stack full, can't push %g\n", f); } double pop(void) { if (sp &gt; 0) return val[--sp]; else { printf("error: stack empty\n"); return 0.0; } } double top(void) { if (sp &gt; 0) return val[sp - 1]; else { printf("error: stack empty\n"); return 0.0; } } void clear(void) { if (sp &gt; 0) { while (--sp &gt; 0); } else { printf("error: stack empty\n"); } } void duplicate(void) { if (sp &gt; 0) { int elem = val[sp - 1]; push(elem); } else { printf("error: stack empty\n"); } } void swap(void) { if (sp &gt; 0 &amp;&amp; (sp - 1) &gt; 0) { int elem1 = val[sp - 1]; int elem2 = val[sp - 2]; val[sp - 1] = elem2; val[sp - 2] = elem1; } else { printf("error: stack empty\n"); } } int getop(char s[]) { int i, c; while ((s[0] = c = getch()) == ' ' || c == '\t') ; s[1] = '\0'; if (!isdigit(c) &amp;&amp; c != '.' &amp;&amp; c != '-') return c; i = 0; if (c == '-') s[++i] = c = getch(); if (isdigit(c)) while (isdigit(s[++i] = c = getch())) ; if (c == '.') while (isdigit(s[++i] = c = getch())) ; s[i] = '\0'; if (c != EOF) ungetch(c); return NUMBER; } 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; } </code></pre> <p>What are your opinions about it? Is it proper and optimal way to implement these functions?</p>
[]
[ { "body": "<ol>\n<li><p>Your clear function uses <code>while (--sp &gt; 0);</code> when <code>sp = 0;</code> does the same thing in faster and clearer way. also consider not throwing an error when clearing an empty stack, because it still behaves as expected.</p></li>\n<li><p>The condition <code>sp &gt; 0 &amp;...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T12:39:19.047", "Id": "197120", "Score": "3", "Tags": [ "c", "homework" ], "Title": "Stack implementation in C" }
197120
<p>I'm new to coding C++ and I want to get some insight on my progress. Can you guys take a look at my program and give me some feedback on it? </p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(){ int day{}; int monthNum{}; cout &lt;&lt; "Calculate how many days are left in the month. \nPlease enter the month number and the day, seperated by a space. ex 1 22 for Jan 22nd: "; cin &gt;&gt; monthNum &gt;&gt; day; if (monthNum &lt; 1 || monthNum &gt; 12 || day &lt; 1 || day &gt; 31 || (monthNum == 2 &amp;&amp; (day &lt; 1 || day &gt; 29))){ cout &lt;&lt; "Error, not a valid input. \nPlease make sure you're month and day are valid." &lt;&lt; endl; return 0; } int daysInCurrentMonth{}; char leapYear; int doNothing{}; //Used to do nothing if certain conditions are false if (monthNum == 2){ cout &lt;&lt; "\nIs it leap year? Type y for yes and n for no. "; cin &gt;&gt; leapYear; ((leapYear == 'y') ? daysInCurrentMonth = 29 : daysInCurrentMonth = 28); if (leapYear != 'y' &amp;&amp; leapYear != 'n'){ cout &lt;&lt; "invalid input..." &lt;&lt; endl &lt;&lt; endl; return 0; }else{ doNothing = 0; } } cout &lt;&lt; "\nYou entered day " &lt;&lt; day &lt;&lt; " of month " &lt;&lt; monthNum &lt;&lt; endl; ((monthNum == 4 || monthNum == 6 || monthNum == 9 || monthNum == 11) ? daysInCurrentMonth = 30 : doNothing = 0); ((monthNum == 1 || monthNum == 3 || monthNum == 5 || monthNum == 7 || monthNum == 8 || monthNum == 10 || monthNum == 12) ? daysInCurrentMonth = 31 : doNothing = 0); int daysLeftInMonth{daysInCurrentMonth - day}; cout &lt;&lt; "\nThere are " &lt;&lt; daysLeftInMonth &lt;&lt; " days left in the month." &lt;&lt; endl; cout &lt;&lt; endl; return 0; } </code></pre> <p>This is my third iteration of this program. <a href="https://www.udemy.com/beginning-c-plus-plus-programming/learn/v4/content" rel="nofollow noreferrer">This</a> is the tutorial series that I've been watching. I'm currently on section 9 and just finished learning about conditional operators. I'm trying to refine the project as I go along. Also, I know it's pretty early to be thinking about this, but if anyone is able to, I'd like to know if the way I structure this is in the right direction for becoming a professional programmer, i.e. it's easy to follow and is readable, or it looks like garbage.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T09:16:55.930", "Id": "379884", "Score": "1", "body": "Line 12: `you're` should be `your` :P I'm sorry, I know it's a little thing but I can't stop thinking about it." } ]
[ { "body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't use <code>using namespace std</code> </a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T13:20:12.513", "Id": "197121", "Score": "8", "Tags": [ "c++", "beginner" ], "Title": "Testing out a program that calculates the days left in the month" }
197121
<p><strong>Task:</strong></p> <p>The task requires creating a class (say, <code>ConfigDict</code>) which inherits from the <code>dict</code> class.</p> <p>It is supposed to save its keys and values in a file. If a file does not exist, the instance of <code>ConfigDict</code> should be able to create it. </p> <p><strong>Examples:</strong></p> <p>For instance, the following code:</p> <pre><code>fh=open("config.txt","w") fh.write("key1 = 5\n") fh.write("key2 = 3\n") fh.close() cd=ConfigDict("config.txt") cd.items() </code></pre> <p>would generate an output <code>dict_items([('key1', '5'), ('key2', '3')])</code>.</p> <p>If a file does not exists, it should be possible for the instance to create it and save its data inside it.</p> <pre><code>dd=ConfigDict("test.txt") dd["keyA"] = 'testA' dd["keyB"] = 'testB' dd.items() </code></pre> <p>The above lines would produce <code>dict_items([('keyA', 'testA'), ('keyB', 'testB')])</code> (and a <code>print</code> message).</p> <p><strong>My attempt:</strong></p> <p>I will greatly appreciate any comments.</p> <pre><code>class ConfigDict(dict): def __init__(self,file): self.file = file try: #check if file exists with open(self.file,"r+") as fh: for line in fh: key, item = line.replace(" ", "").rstrip().split("=") dict.__setitem__(self,key,item) except: print("creating "+file) fh=open(self.file,"w") fh.close() def __setitem__(self,key,item): dict.__setitem__(self,key,item) #to avoid infinite loop lines = open(self.file).read().splitlines() for index, line in enumerate(lines): if line.replace(" ", "").rstrip().split("=")[0] == key: lines[index] = str(key)+" = "+str(item) else: lines.append(str(key)+" = "+str(item)) open(self.file,'w').write('\n'.join(lines)) </code></pre> <p><strong>Corrected version</strong></p> <pre><code>import os class ConfigDict(dict): def __init__(self,file): self.file = file if os.path.isfile(self.file): with open(self.file,"r") as fh: for line in fh: key, item = line.replace(" ", "").rstrip().split("=") dict.__setitem__(self,key,item) def __setitem__(self,key,item): dict.__setitem__(self,key,item) with open(self.file, 'w') as save_file: for key, value in self.items(): save_file.write("{} = {}\n".format(key, value)) </code></pre>
[]
[ { "body": "<h2>bugs:</h2>\n\n<ol>\n<li>Your implementation of <code>__setitem__()</code> does not to add a line\nif the key does not exist in the file yet.</li>\n</ol>\n\n<h2>other issues:</h2>\n\n<ol>\n<li><p>There is no need to create the file if it does not exist in\n<code>__init__()</code>, as <code>open(.....
{ "AcceptedAnswerId": "197134", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T19:04:16.833", "Id": "197129", "Score": "7", "Tags": [ "python", "beginner", "object-oriented", "python-3.x" ], "Title": "Create a dictionary which saves its data to file" }
197129
<p>I'm trying to validate if an integer represents a valid IPv6 mask, which boils down to checking if all the left-most bits of an u128 are 1s, and all the right-most bits are 0s. For instance:</p> <ul> <li><code>0</code> is valid</li> <li><code>0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff</code> is valid</li> <li><code>0xffff_ffff_ffff_ffff_0000_0000_0000_0000</code> is valid</li> <li><code>0xffff_ffff_fff8_0000_0000_0000_0000_0000</code> is valid</li> <li><code>0xffff_ffff_fffe_0000_0000_0000_0000_0000</code> is valid</li> </ul> <p>but:</p> <ul> <li><code>1</code> is invalid (its representation is <code>0x0000_0000_0000_0000_0000_0000_0000_0001</code>)</li> <li><code>0x0fff_ffff_ffff_ffff_ffff_ffff_ffff_ffff</code> is invalid</li> <li><code>0xffff_ffff_fff1_0000_0000_0000_0000_0000</code> is invalid</li> </ul> <p>Here is the function:</p> <pre><code>/// Check whether the given integer represents a valid IPv6 mask. /// A valid IP mask is an integer which left-most bits are 1s, and right-most bits are 0s. fn is_valid_ipv6_mask(value: u128) -&gt; bool { // flag to check if we're currently processing 1s or 0s let mut count_ones = true; // check each byte starting from the left. for byte_index in (0..=15).rev() { let x = (value &gt;&gt; (byte_index * 8)) &amp; 0xff; match x { // We're processing 1s and this byte is 0b1111_1111 0xff if count_ones =&gt; continue, // We're processing 0s and this byte is 0b0000_0000 0x00 if !count_ones =&gt; continue, // We're processing 1s and this byte is 0b0000_0000. // That means all the remaining bytes should be 0 for this integer // to be a valid mask 0x00 if count_ones =&gt; { count_ones = false; continue; } // We're processsing 1s and this byte has at least a 1, so we have // to check bit by bit that the left-most bits are 1s and the // right-most bits are 0s byte if byte &gt; 0 &amp;&amp; count_ones =&gt; { let mut bit_index = 7; while (byte &gt;&gt; bit_index) &amp; 1 == 1 { // This does not overflow, because we now this byte has at // least a 0 somewhere bit_index -= 1 } // At this point, all the bits should be 0s count_ones = false; for i in 0..bit_index { if (byte &gt;&gt; i) &amp; 1 == 1 { return false; } } } // Any other case is an error _ =&gt; return false, } } true } </code></pre> <p>And to test it:</p> <pre><code>fn main() { assert!(is_valid_ipv6_mask(0)); assert!(is_valid_ipv6_mask( 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff )); assert!(is_valid_ipv6_mask( 0xffff_0000_0000_0000_0000_0000_0000_0000 )); assert!(is_valid_ipv6_mask( 0xff80_0000_0000_0000_0000_0000_0000_0000 )); assert!(!is_valid_ipv6_mask( 0xff01_0000_0000_0000_0000_0000_0000_0000 )); assert!(!is_valid_ipv6_mask( 0xffff_0000_ffff_ffff_ffff_ffff_ffff_ffff )); } </code></pre> <p><a href="https://play.rust-lang.org/?gist=624e2e73fcb9130b5ef365686c69242f&amp;version=stable&amp;mode=debug" rel="nofollow noreferrer">Link to playground</a>.</p> <p>The problem is that have the feeling that there <em>must</em> be a much simple solution to this problem. After all, bit operations are what computers do, I can't believe there's not more concise and more efficient way to check if an integer is all 1s then all 0s.</p>
[]
[ { "body": "<blockquote>\n <p>The problem is that have the feeling that there must be a much simple solution to this problem.</p>\n</blockquote>\n\n<p>You're right! Integers in Rust have many useful bitwise operations (as well as other useful ones like wrapping and saturating arithmetic), most of which are expo...
{ "AcceptedAnswerId": "197138", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T19:16:19.877", "Id": "197131", "Score": "2", "Tags": [ "integer", "rust" ], "Title": "Check whether an integer's leftmost bits are ones in Rust" }
197131
<p>In a grid of hexagons, we often want to find the neighbors of a cell with distance <code>n</code>. In the image below we have a rhombus-shaped grid of hexagons with an axial coordinate system showing the cell <code>(row, col) = (3,3)</code> (dark gray), its 1-distance neighbors (medium gray) and its 2-distance neighbors (light gray).</p> <p><a href="https://i.stack.imgur.com/MtkBG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MtkBG.png" alt=""></a></p> <p>In the code below (which has the correct output), we create 5 arrays. Array #1 contains, for each row and column, indecies of neighbors with a distance of 1 <strong>or less</strong>. Array #2, #3, and #4 contain indecies of neighbors with distance 2, 3, 4 or less respectively. The last array contains, for each distance 1,2,3, and 4, for each cell, the number of neighbors of the cell with the given distance or less. This is necessary as cells close to the grid boundary have fewer neighbors than cells close to the center.</p> <pre><code>#[macro_use] extern crate ndarray; use ndarray::prelude::*; use std::ops::AddAssign; fn hex_distance(r1: i8, c1: i8, r2: i8, c2: i8) -&gt; i8 { // Distance from cell (r1, c1) to cell (r2, c2) in a hexagonal grid ((r1 - r2).abs() + (r1 + c1 - r2 - c2).abs() + (c1 - c2).abs()) / 2 } fn generate_neighs() -&gt; (Array&lt;usize, Ix4&gt;, Array&lt;usize, Ix4&gt;,Array&lt;usize, Ix4&gt;, Array&lt;usize, Ix4&gt;, Array&lt;usize, Ix3&gt;) { // Return 4 arrays with indecies of neighbors (including self) with distance of (1..5) or less; // and a (4 X rows x cols) array with the number of neighbors for each row and column since // the number of n-distance neighbors can vary for each cell. let rows = 7; let cols = 7; // Indecies of neighbors with distance of 1 or less let mut neighs1 = Array::zeros((rows, cols, 7, 2)); let mut neighs2 = Array::zeros((rows, cols, 19, 2)); let mut neighs3 = Array::zeros((rows, cols, 37, 2)); let mut neighs4 = Array::zeros((rows, cols, 43, 2)); // For distance 1..5 or less, for each row and col: the number of neighbors. let mut n_neighs = Array::zeros((4, rows, cols)); neighs1.slice_mut(s![0, 0, 0, ..]).assign(&amp;Array::ones(2)); for r1 in 0..rows { for c1 in 0..cols { // Want to store index of self first, so that it can be easily excluded neighs1.slice_mut(s![r1, c1, 0, ..]).assign(&amp;array![r1, c1]); n_neighs.slice_mut(s![.., r1, c1]).add_assign(1); for r2 in 0..rows { for c2 in 0..cols { let dist = hex_distance(r1 as i8, c1 as i8, r2 as i8, c2 as i8); if (r1, c1) != (r2, c2) &amp;&amp; dist &lt;= 4 { let n = n_neighs[[3, r1, c1]]; neighs4 .slice_mut(s![r1, c1, n, ..]) .assign(&amp;array![r2, c2]); n_neighs[[3, r1, c1]] += 1; if dist &lt;= 3 { let n = n_neighs[[2, r1, c1]]; neighs3 .slice_mut(s![r1, c1, n, ..]) .assign(&amp;array![r2, c2]); n_neighs[[2, r1, c1]] += 1; if dist &lt;= 2 { let n = n_neighs[[1, r1, c1]]; neighs2 .slice_mut(s![r1, c1, n, ..]) .assign(&amp;array![r2, c2]); n_neighs[[1, r1, c1]] += 1; if dist == 1 { let n = n_neighs[[0, r1, c1]]; neighs1 .slice_mut(s![r1, c1, n, ..]) .assign(&amp;array![r2, c2]); n_neighs[[0, r1, c1]] += 1; } } } } } } } } return (neighs1, neighs2, neighs3, neighs4, n_neighs) } fn main() { let neighs = generate_neighs(); println!("{}", neighs.4); } </code></pre> <p>Besides the code review I have a question, namely, how can I make these 5 arrays easily available throughout my program (without ever calling the function twice)? Is there any way of making them immutable (they won't change), making them global (for use in same file), and exporting them (for use in other files)?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T19:41:23.323", "Id": "197133", "Score": "2", "Tags": [ "rust" ], "Title": "Finding n-distance neighbors in a hexagonal grid" }
197133
<p>I wanted to reproduce the type of navigation system found in the console of Firefox and Chrome: you can explore an object's properties by unfolding boxes:</p> <p><a href="https://i.stack.imgur.com/gBTOU.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gBTOU.gif" alt="enter image description here"></a></p> <p>So I'm searching to:</p> <ol> <li><p>display all of the object's properties (even if they're nested)</p></li> <li><p>being able to fold/unfold the properties if themselves are objects</p></li> </ol> <hr> <h3>Element handling</h3> <p>I have written two functions <code>createElement</code> and <code>appendElement</code>, I will need them later:</p> <pre><code>/** * Creates an HTML element without rendering in the DOM * @params {String} htmlString is the HTML string that is created * @return {HTMLElement} is the actual object of type HTMLElement */ const createElement = htmlString =&gt; { const div = document.createElement('div'); div.innerHTML = htmlString; return div.firstChild; } /** * Appends the given element to another element already rendered in the DOM * @params {String or HTMLElement} parent is either a CSS String selector or a DOM element * {String or HTMLElement} element is either a HTML String or an HTMLElement * @return {HTMLElement} the appended child element */ const appendElement = (parent, element) =&gt; { element = element instanceof HTMLElement ? element : createElement(element); return (parent instanceof HTMLElement ? parent : document.querySelector(parent)) .appendChild(element); } </code></pre> <hr> <h3>Version 1</h3> <p>My initial attempt was to use a recursive approach. Essentially each level would call the function for each of its children which would, in turn, call the function for their own children. </p> <p>In the end, it would result in having the complete tree displayed on the page.</p> <pre><code>const showContent = (object, parent) =&gt; { Object.keys(object).forEach(e =&gt; { if(object[e] &amp;&amp; object[e].constructor == Object) { showContent(object[e], appendElement(parent, `&lt;div class="level fold"&gt;&lt;div class="parent"&gt;&lt;span&gt;-&lt;/span&gt; ${e}&lt;div&gt;&lt;/div&gt;`)); } else { appendElement(parent, `&lt;div class="level"&gt;${e}: &lt;span&gt;${object[e]}&lt;/span&gt;&lt;/div&gt;`) } }); } // display the object's property showContent(obj, 'body'); // toggle function to fold/unfold the properties const toggle = () =&gt; event.target.parentElement.classList.toggle('fold'); // listen to click event on each element document.querySelectorAll('.parent span').forEach(e =&gt; e.parentElement.addEventListener('click', toggle)); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const showContent = (object, parent) =&gt; { Object.keys(object).forEach(e =&gt; { if(object[e] &amp;&amp; object[e].constructor == Object) { showContent(object[e], appendElement(parent, `&lt;div class="level fold"&gt;&lt;div class="parent"&gt;&lt;span&gt;-&lt;/span&gt; ${e}&lt;div&gt;&lt;/div&gt;`)); } else { appendElement(parent, `&lt;div class="level"&gt;${e}: &lt;span&gt;${object[e]}&lt;/span&gt;&lt;/div&gt;`) } }); } // display the object's property showContent(obj, 'body'); // toggle function to fold/unfold the properties const toggle = () =&gt; event.target.parentElement.classList.toggle('fold'); // listen to click event on each element document.querySelectorAll('.parent span').forEach(e =&gt; e.parentElement.addEventListener('click', toggle));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body&gt;.level{position:relative;left:25%;width:50%}.level{background:lightgrey;border:2px solid brown;padding:4px;margin:4px;overflow:hidden}.level&gt;span{color:#0366d5}.level&gt;.parent{color:green;display:inline-block;width:100%}.fold{height:18px}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt;const createElement=htmlString=&gt;{const div=document.createElement('div');div.innerHTML=htmlString;return div.firstChild};const appendElement=(parent,element)=&gt;{element=element instanceof HTMLElement?element:createElement(element);return(parent instanceof HTMLElement?parent:document.querySelector(parent)).appendChild(element)};const obj = {innerObj:{other:'yes',note:12,innerObj:{other:'no',note:1}},name:'one',int:1225,bool:true};&lt;/script&gt;</code></pre> </div> </div> </p> <p>Here are a few things I didn't like about this code:</p> <ul> <li><p>there's an event <strong>on each property element</strong>, also the event listener needs to be set after the element has been added to the DOM. So calling <code>showContent</code> <em>before</em> the event handlers doesn't feel natural.</p></li> <li><p>this version doesn't support circular structures. For example:</p> <pre><code>let obj = {}; obj['obj'] = obj; showContent(obj); </code></pre> <p>will fail...</p></li> </ul> <p>So this won't work for me. I need something able to handle cycles without too much trouble and that would not require to add an event listener each time a new property is unfolded.</p> <hr> <h3>Version 2</h3> <p>I came up with a better version that solved all these problems:</p> <pre><code>/** * Shows all the object's properties with a depth of 1 * @params {Object} object, its first level properties are shown * {String or HTMLElement} parent the element in which are displayed the properties * @return {undefined} */ const showObject = (object, parent='body') =&gt; { Object.entries(object).forEach(([key, value]) =&gt; { if(value &amp;&amp; value.constructor == Object) { const element = appendElement(parent, `&lt;div class="level fold"&gt;&lt;div class="parent"&gt;&lt;span&gt;-&lt;/span&gt; ${key}&lt;div&gt;&lt;/div&gt;`); element.addEventListener('click', () =&gt; {showObject(value, element)}, {once: true}); } else { appendElement(parent, `&lt;div class="level"&gt;${key}: &lt;span&gt;${value}&lt;/span&gt;&lt;/div&gt;`); } }); }; /** * Toggles the CSS class .fold on the provided element * @params {HTMLElement} element on which to toggle the class * @return {undefined} */ const fold = element =&gt; element.classList.toggle('fold'); /** * Document click listener */ document.addEventListener('click', function() { const target = event.target; const isFoldable = target.classList.contains('parent'); if(isFoldable) { fold(target.parentElement); } }); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/** * Shows all the object's properties with a depth of 1 * @params {Object} object, its first level properties are shown * {String or HTMLElement} parent the element in which are displayed the properties * @return {undefined} */ const showObject = (object, parent='body') =&gt; { Object.entries(object).forEach(([key, value]) =&gt; { if(value &amp;&amp; value.constructor == Object) { const element = appendElement(parent, `&lt;div class="level fold"&gt;&lt;div class="parent"&gt;&lt;span&gt;-&lt;/span&gt; ${key}&lt;div&gt;&lt;/div&gt;`); element.addEventListener('click', () =&gt; {showObject(value, element)}, {once: true}); } else { appendElement(parent, `&lt;div class="level"&gt;${key}: &lt;span&gt;${value}&lt;/span&gt;&lt;/div&gt;`); } }); }; /** * Toggles the CSS class .fold on the provided element * @params {HTMLElement} element on which to toggle the class * @return {undefined} */ const fold = element =&gt; element.classList.toggle('fold'); /** * Document click listener */ document.addEventListener('click', function() { const target = event.target; const isFoldable = target.classList.contains('parent'); if(isFoldable) { fold(target.parentElement); } }); showObject(obj);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body&gt;.level{position:relative;left:25%;width:50%}.level{background:lightgrey;border:2px solid brown;padding:4px;margin:4px;overflow:hidden}.level&gt;span{color:#0366d5}.level&gt;.parent{color:green;display:inline-block;width:100%}.fold{height:18px}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt;const createElement=htmlString=&gt;{const div=document.createElement('div');div.innerHTML=htmlString;return div.firstChild};const appendElement=(parent,element)=&gt;{element=element instanceof HTMLElement?element:createElement(element);return(parent instanceof HTMLElement?parent:document.querySelector(parent)).appendChild(element)};const obj = {innerObj:{other:'yes',note:12,innerObj:{other:'no',note:1}},name:'one',int:1225,bool:true};&lt;/script&gt;</code></pre> </div> </div> </p> <p>Here it is seen working with a cycle:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {}; obj['obj'] = obj; showObject(obj);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body&gt;.level{position:relative;left:25%;width:50%}.level{background:lightgrey;border:2px solid brown;padding:4px;margin:4px;overflow:hidden}.level&gt;span{color:#0366d5}.level&gt;.parent{color:green;display:inline-block;width:100%}.fold{height:18px}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt;const createElement=htmlString=&gt;{const div=document.createElement('div');div.innerHTML=htmlString;return div.firstChild};const appendElement=(parent,element)=&gt;{element=element instanceof HTMLElement?element:createElement(element);return(parent instanceof HTMLElement?parent:document.querySelector(parent)).appendChild(element)};const showObject=(object,parent='body')=&gt;{Object.entries(object).forEach(([key,value])=&gt;{if(value&amp;&amp;value.constructor==Object){const element=appendElement(parent,`&lt;div class="level fold"&gt;&lt;div class="parent"&gt;&lt;span&gt;-&lt;/span&gt; ${key}&lt;div&gt;&lt;/div&gt;`);element.addEventListener('click',()=&gt;{showObject(value,element)},{once:!0})}else{appendElement(parent,`&lt;div class="level"&gt;${key}: &lt;span&gt;${value}&lt;/span&gt;&lt;/div&gt;`)}})};const fold=element=&gt;element.classList.toggle('fold');document.addEventListener('click',function(){const target=event.target;const isFoldable=target.classList.contains('parent');if(isFoldable){fold(target.parentElement)}})&lt;/script&gt;</code></pre> </div> </div> </p> <hr> <h3>Questions</h3> <ul> <li>What do you think?</li> <li>What could be improved (structure, naming, comments, programming style)?</li> <li>Any advice?</li> </ul>
[]
[ { "body": "<p>Very neat project! Your code already looks pretty clean to me. I especially like the optimization of only running <code>showObject</code> once for each expansion. </p>\n\n<ol>\n<li><p>Bug: If my object is <code>{ a: '&lt;b&gt;Bold&lt;/b&gt;' }</code>, the text displayed for property <code>a</code>...
{ "AcceptedAnswerId": "197183", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T20:29:18.517", "Id": "197135", "Score": "5", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Displaying JavaScript object's structure on page with HTML" }
197135
<p>I've written this plotter for Ionic in Typescript to plot data that I push to a Firebase list. I'm new to Typescript so I'm interested in all kinds of feedback, especially on the style.</p> <p>First I've created a database provider that I used to retrieve the data for the charts from Firebase:</p> <pre><code>import { Injectable } from '@angular/core'; import { AngularFireDatabase } from 'angularfire2/database'; // Provides read and write database methods @Injectable() export class MyProjectDatabase { userID; deviceID; constructor( private afDB: AngularFireDatabase, ) { } public connect(userID) { this.userID = userID; this.read(`/user/${this.userID}/linked_device`).then( (val) =&gt; { this.deviceID = val; }); } public disconnect() { this.userID = ""; this.deviceID = ""; } // In a regular function: // fun () { // db.read(path).then( (val) =&gt; { // this.val = val; // }); // } // // In an async function: // async fun() { // val = await db.read(path); // } public async read(path: string, query?) { let snapshot; if (query) { snapshot = await this.afDB.list(path, query).query.once("value"); } else { snapshot = await this.afDB.list(path).query.once("value"); } return snapshot.val(); } public write(path: string, value) { this.afDB.object(path).set(value); } public remove(path: string, query?) { if (query) { this.afDB.list(path, query).remove(); } else { this.afDB.list(path).remove(); } } // Returns the values of the list in an array: // In a regular function: // fun() { // readList(path).then( values =&gt; { // values.forEach( value =&gt; { // ... // }); // }); // } // // In an async function: // async fun() { // let values = await readList(path); // values.forEach( value =&gt; { // ... // }); // } public async readList(path: string, query?) { let snapshot; if (query) { snapshot = await this.afDB.list(path, query).query.once("value"); } else { snapshot = await this.afDB.list(path).query.once("value"); } let obj = snapshot.val(); if (obj) { return Object.keys(obj).map(key =&gt; { return obj[key] }); } else { return []; } } public addToList(path: string, value) { this.afDB.list(path).push(value); } // Returns all entries of the list that match the value in an object { key: value } // In a regular function: // fun() { // findInList(path, value).then( match =&gt; { // for (let key in match) { // console.log(match[key]); // } // }); // } // // In an async function: // async fun() { // let match = await findInList(path, value); // for (let key in match) { // console.log(match[key]); // } // } public async findInList(path: string, value) { let snapshot = await this.afDB.list(path, ref =&gt; ref.orderByValue().equalTo(value)).query.once("value"); return snapshot.val(); } // Remove all entries in the list that match the value public removeFromList(path: string, value) { let list = this.afDB.list(path); list.query.once("value").then( snapshot =&gt; { let snapshotValues = snapshot.val(); for (let key in snapshotValues) { console.log(`${snapshotValues[key]} == ${value}`); if (snapshotValues[key] == value) { list.remove(key); } } }); } } </code></pre> <p>When the <code>query</code> parameter is optional, is there a better way to check it rather than doing an <code>if(query)</code>?</p> <p>Then I use this provider in my charts. I have an abstract chart that I use as a template:</p> <pre><code>import { ElementRef } from '@angular/core'; import { MyProjectDatabase } from '../../../providers/my-project-database'; import { Chart } from 'chart.js'; export abstract class MyProjectChart { abstract chartCanvas: ElementRef; abstract numberOfMeasurements: number; abstract dataPath: string; abstract chartStyle: object; private chart: Chart; constructor( private db: MyProjectDatabase, ) { } public init() { this.chart = new Chart(&lt;HTMLCanvasElement&gt;this.chartCanvas.nativeElement, this.chartStyle); } public update() { const componentPath = `/device/${this.db.deviceID}/component`; this.db.readList(`${componentPath}/${this.dataPath}`, ref =&gt; ref.limitToLast(this.numberOfMeasurements)) .then( data =&gt; { data.forEach((item, index) =&gt; { this.chart.data.datasets[0].data[index] = item.value; this.chart.data.labels[index] = item.timestamp; }); this.chart.update(); }); } } </code></pre> <p>An example of a chart would be:</p> <pre><code>import { Component, ViewChild, ElementRef } from '@angular/core'; import { MyProjectDatabase } from '../../../providers/my-project-database'; import { MyProjectChart } from './my-project-chart' @Component({ selector: 'light-chart', template: ` &lt;div style="margin-left:auto; margin-right:auto; position: relative; height:50vh; width:80vw"&gt; &lt;canvas #chartCanvas&gt;&lt;/canvas&gt; &lt;/div&gt;` }) export class LightChart extends MyProjectChart { @ViewChild('chartCanvas') chartCanvas: ElementRef; numberOfMeasurements: number = 10; dataPath: string = 'lux/data'; chartStyle: object = { type: 'line', data: { labels: new Array(this.numberOfMeasurements).fill("00:00:00"), datasets: [ { label: "Light Intensity", fill: true, lineTension: 0.5, backgroundColor: "rgb(48,151,127)", borderColor: "rgb(48,151,127,0.8)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgb(48,151,127)", pointBackgroundColor: "rgba(48,151,127)", pointBorderWidth: 3, pointHoverRadius: 5, pointHoverBackgroundColor: "rgb(48,151,127)", pointHoverBorderColor: "rgba(48,151,127)", pointHoverBorderWidth: 2, pointRadius: 3, pointHitRadius: 10, spanGaps: false, data: new Array(this.numberOfMeasurements).fill(10), } ] }, options: { responsive: true, maintainAspectRatio: false, legend: { display: false }, scales: { yAxes: [{ ticks: { min: 0, max: 30, display: false }, gridLines: { display: false, drawBorder: false } }], xAxes: [{ gridLines: { display: false, drawBorder: false } }] } } } constructor ( db: MyProjectDatabase ) { super(db); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T21:03:16.057", "Id": "197137", "Score": "1", "Tags": [ "typescript", "firebase" ], "Title": "Firebase Plotter for Ionic" }
197137
<p>This is one of my first C++ training project where I created the console application which displays the calendar of any given month.</p> <p>I observed how offset of days (empty places on the calendar) change year by year and build the empirical formula on it. For the starting point (the fixed year) I have chosen 2008 only because I worked on this ten years ago.</p> <p>Now I changed and fixed several things in that old code. However, I am sure there are much more which could be done better or improved.</p> <pre><code>//Comment next line if you do not use MS-DOS compilers #define MSDOS #include &lt;iostream&gt; #include &lt;string.h&gt; #ifdef MSDOS #include &lt;conio.h&gt; #endif using namespace std; void Calendar(int year, int month); int GetUserInput(const char * name, int from = 0, int to = 0); int main() { int year, month; char control = 0; char menu[] = "&lt; P &gt; - Previous, &lt; N &gt; - Next\n&lt; D &gt; - New date, &lt; E &gt; - Exit\n"; year = GetUserInput("Year"); month = GetUserInput("Month", 1, 12); Calendar(year, month); cout &lt;&lt; menu; do { bool Proceed = false; #ifdef MSDOS Proceed = _kbhit(); #else Proceed = true; #endif if (Proceed) { #ifdef MSDOS control = _getch(); #else cin.get(control); cin.get(); #endif system("cls"); switch (control) { case -32: continue; break; case 'P': case 'p': case 72: // Up arrow case 75: // Left arrow month--; if (month &lt; 1) { month += 12; year -= 1; } break; case 'N': case 'n': case 13: // Enter case 77: // Right arrow month++; if (month &gt; 12) { month -= 12; year += 1; } break; case 'D': case 'd': year = GetUserInput("Year"); month = GetUserInput("Month", 1, 12); break; case 'E': case 'e': cout &lt;&lt; "\n\tBye!\n"; break; default: cout &lt;&lt; "\n\tWrong input!\n\n"; cout &lt;&lt; menu; continue; break; } Calendar(year, month); cout &lt;&lt; menu; } } while (control != 'e' &amp;&amp; control != 'E'); return 0; } int GetUserInput(const char * name, int from, int to) { bool succeed = false; int value = 0; char buffer[10]; do { cout &lt;&lt; "Enter " &lt;&lt; name &lt;&lt; ": "; cin.getline(buffer, 10); value = atoi(buffer); if (from == to || value &gt;= from &amp;&amp; value &lt;= to) succeed = true; } while (!succeed); return value; } void Calendar(int year, int month) { char monthName[][10] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int numberOfDaysInMonth, shift, empty; int daysInMonth[]{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; numberOfDaysInMonth = (month == 2 &amp;&amp; year % 4 == 0) ? 29 : daysInMonth[month - 1]; const int fixedYear = 2008; const int fixedEmpty[]{ 1, 4, 5, 1, 3, 6, 1, 4, 0, 2, 5, 0 }; int yearDiff = year - fixedYear; if (yearDiff &gt; 0) { shift = yearDiff + yearDiff / 4; if (month &lt;= 2 &amp;&amp; year % 4 != 0) shift++; } else { shift = yearDiff - yearDiff / 4; if (month &gt; 2 &amp;&amp; year % 4 != 0) shift--; } empty = fixedEmpty[month - 1] + shift; empty = empty % 7; if (empty &lt; 0) empty += 7; cout &lt;&lt; " ................... " &lt;&lt; monthName[month - 1] &lt;&lt; " " &lt;&lt; year &lt;&lt; " "; int dots = 23 - strlen(monthName[month - 1]); for (int i = 0; i &lt; dots; i++) cout &lt;&lt; "."; cout &lt;&lt; "\n Mo\tTu\tWe\tTh\tFr\tSa\tSu\t\n "; for (int e = 0; e &lt; empty; e++) cout &lt;&lt; "\t"; for (int d = 1; d &lt;= numberOfDaysInMonth; d++) cout &lt;&lt; d &lt;&lt; ((empty + d) % 7 == 0 ? "\n " : "\t"); cout &lt;&lt; "\n\n"; } </code></pre> <p>I wonder if there is any conventional way to determine the weekday for the start a month based on only month and year.</p> <p>It would be great if someone could show me what is common practice to manage different libraries for different compilers (like the <code>&lt;conio.h&gt;</code> in my case).</p>
[]
[ { "body": "<p>If you have a C++ standards-compliant compiler, then you should not need to use <code>&lt;conio.h&gt;</code> under Windows (<code>_kbhit</code> and <code>_getch</code>). <code>std::cin</code> will work. I know there are still old compilers floating around, but there are various modern C++ compiler...
{ "AcceptedAnswerId": "197151", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-23T22:06:41.723", "Id": "197141", "Score": "6", "Tags": [ "c++", "c++11", "datetime", "macros" ], "Title": "Calendar for any given month/year" }
197141
<p>This class encapsulates a 2D Array and a Scripting Dictionary. Values are add or returned from to the Array using a Key and a <code>ColumnIndex</code>, e.g. <code>IndexedArray(Key, ColumnIndex) = Value</code> . The Key is used to get the <code>RowIndex</code> of the Array. The Value is then added to the Array, e.g. <code>Array(ColumnIndex, RowIndex)</code>.</p> <p>Although, I am quite pleased with the performance, flexibility, and ease of use, I am open to any suggestions on how to improve its design. </p> <h2>IndexedArray:Class</h2> <pre><code>Attribute VB_Description = "Uses a Scripting.Dictionary (m.Dictionary) to Index and Array of Values" Option Explicit Private Const DEFAULT_ROW_BUFFER As Long = 100 Attribute DEFAULT_ROW_BUFFER.VB_VarDescription = "The number of rows added to m.Values when resized" Private Const DEFAULT_COLUMN_COUNT As Long = 10 Attribute DEFAULT_COLUMN_COUNT.VB_VarDescription = "The default number of Columns in m.Values" Private Type Members ColumnCount As Long Dictionary As Object Initiated As Boolean Values As Variant 'Values(Columns, Rows) End Type Private m As Members Attribute m.VB_VarDescription = "Encapsulates Class Member Fields For VBA Like m Reference (e.g. m.Value is simular to VBA m_Value)" Private Sub Class_Initialize() Set m.Dictionary = CreateObject("Scripting.Dictionary") m.ColumnCount = DEFAULT_COLUMN_COUNT ReDim m.Values(1 To m.ColumnCount, 1 To DEFAULT_ROW_BUFFER) End Sub Public Property Get Value(ByVal Key As Variant, ByVal ColumnIndex As Long) As Variant Attribute Value.VB_Description = "Gets or sets m.Values() element at Index returned by m.Dictionary(Key)" Attribute Value.VB_UserMemId = 0 If Not m.Dictionary.Exists(Key) Then Expand Key Value = m.Values(ColumnIndex, m.Dictionary(Key)) End Property Public Property Let Value(ByVal Key As Variant, ByVal ColumnIndex As Long, ByVal vValue As Variant) If Not m.Dictionary.Exists(Key) Then Expand Key m.Values(ColumnIndex, m.Dictionary(Key)) = vValue End Property Public Function Exists(Key As Variant) As Boolean Attribute Exists.VB_Description = "Tests if Key Exists in m.Dictionary" Exists = m.Dictionary.Exists(Key) End Function Private Sub Expand(ByVal Key As Variant) Attribute Expand.VB_Description = "Adds new Key to m.Dictionary and Increase adds an additional number of rows to m.Values equal to DEFAULT_ROW_BUFFER." m.Dictionary.Add Key, m.Dictionary.Count + 1 If m.Dictionary.Count &gt; UBound(m.Values, 2) Then ReDim Preserve m.Values(1 To m.ColumnCount, 1 To UBound(m.Values, 2) + DEFAULT_ROW_BUFFER) End Sub Public Sub setColumnCount(ColumnCount As Long) Attribute setColumnCount.VB_Description = "Changes the number of column in m.Values()" Dim Values As Variant Dim c As Long, r As Long If ColumnCount &lt; 1 Then Err.Raise Number:=vbObjectError + 513, Description:="ColumnCount can not be less than 1" If m.ColumnCount &lt;&gt; ColumnCount Then ReDim Values(1 To ColumnCount, UBound(m.Values, 2)) For r = 1 To UBound(m.Values) For c = 1 To IIf(m.ColumnCount &lt; ColumnCount, m.ColumnCount, ColumnCount) Values(c, r) = m.Values(c, r) Next Next m.ColumnCount = ColumnCount m.Values = Values End If End Sub Public Sub EnsureCapacity(Capacity As Long) If UBound(m.Values, 2) &lt; Capacity Then ReDim Preserve m.Values(1 To m.ColumnCount, 1 To Capacity) End Sub Public Function ToArray(Optional SearchString As String, Optional IncludeHeaderRows As Boolean) As Variant() Attribute ToArray.VB_Description = "Return 2D Array of Values(Rows, Columns) either filtered or unfiltered. Array filtering is delagated to ToFilteredArray" Dim Values As Variant Dim c As Long, r As Long If Len(SearchString) = 0 Then ReDim Values(1 To m.Dictionary.Count, 1 To m.ColumnCount) For r = 1 To m.Dictionary.Count For c = 1 To m.ColumnCount Values(r, c) = m.Values(c, r) Next Next ToArray = Values Else ToArray = ToFilteredArray(SearchString, IncludeHeaderRows) End If End Function Private Function ToFilteredArray(SearchString As String, IncludeHeaderRows As Boolean) As Variant() Attribute ToFilteredArray.VB_Description = "Returns a 2D Array of filtered Values(Rows, Columns) to ToArray" Dim Key As Variant, header As Variant, Values As Variant Dim c As Long, r As Long, n As Long With CreateObject("System.Collections.ArrayList") If IncludeHeaderRows Then header = m.Dictionary.Keys()(0) .Add header End If For Each Key In m.Dictionary.Keys() If Key Like SearchString And Not .Contains(Key) Then .Add Key Next If .Count = 0 Then ReDim Values(1 To 1, 1 To 1) Values(1, 1) = vbNullString Else .Sort If Not IsEmpty(header) Then .Remove header .Insert 0, header End If ReDim Values(1 To .Count + 1, 1 To m.ColumnCount) For Each Key In .ToArray n = n + 1 r = m.Dictionary(Key) For c = 1 To m.ColumnCount Values(n, c) = m.Values(c, r) Next Next End If End With ToFilteredArray = Values End Function </code></pre> <h2>Test Routine</h2> <p>Note: constants prefixed with <code>order</code> belong to <code>Public Enum OrderColumns</code>. <code>OrderColumns</code> enumerates all the columns on the <code>Worksheet("Orders")</code>.</p> <pre><code>Public Sub UpdateSummary(KeyColumn As Long, Optional SearchString As String, Optional IncludeHeaderRows As Boolean) Dim t As Long Application.ScreenUpdating = False Dim idxArray As New IndexedArray, Key As Variant, row As Range t = Timer With ThisWorkbook.Worksheets("Orders") Key = "Header Row" idxArray(Key, 1) = .Cells(KeyColumn).Value idxArray(Key, 2) = "Count" idxArray(Key, 3) = "Average" idxArray(Key, 4) = .Cells(orderSales).Value idxArray(Key, 5) = .Cells(orderQuantity).Value idxArray(Key, 6) = .Cells(orderDiscount).Value idxArray(Key, 7) = .Cells(orderProfit).Value For Each row In .Range("A2", .Range("A" &amp; .Rows.Count).End(xlUp)).EntireRow With row Key = .Cells(KeyColumn) idxArray(Key, 1) = .Cells(KeyColumn).Value idxArray(Key, 2) = idxArray(Key, 4) + 1 idxArray(Key, 3) = "=AVERAGE(RC[-2]:RC[-1])" idxArray(Key, 4) = .Cells(orderSales).Value + idxArray(Key, 4) idxArray(Key, 5) = .Cells(orderQuantity).Value + idxArray(Key, 5) idxArray(Key, 6) = .Cells(orderDiscount).Value + idxArray(Key, 6) idxArray(Key, 7) = .Cells(orderProfit).Value + idxArray(Key, 7) End With Next End With Debug.Print Round(Timer - t, 2) CreateSummaryTable idxArray.ToArray(SearchString, IncludeHeaderRows) Application.ScreenUpdating = True End Sub </code></pre> <h2>Immediate Window Test</h2> <p><a href="https://i.stack.imgur.com/F0oyf.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/F0oyf.jpg" alt="UpdateSummary orderCustomer_Name"></a></p> <blockquote> <pre><code>UpdateSummary orderCustomer_Name </code></pre> </blockquote> <p><a href="https://i.stack.imgur.com/utT3o.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/utT3o.jpg" alt="UpdateSummary orderCustomer_Name, &quot;*Alan*&quot;, False"></a></p> <blockquote> <pre><code>UpdateSummary orderCustomer_Name, "*Alan*", False </code></pre> </blockquote> <p><a href="https://i.stack.imgur.com/q4mRb.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/q4mRb.jpg" alt="enter image description here"></a></p> <blockquote> <pre><code>UpdateSummary orderCustomer_Name, "*Alan*", True </code></pre> </blockquote> <p><a href="https://i.stack.imgur.com/aXbsL.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/aXbsL.jpg" alt="enter image description here"></a></p> <blockquote> <pre><code>UpdateSummary orderOrder_ID, "*CA-2014-##3###*", True </code></pre> </blockquote> <p><a href="https://drive.google.com/open?id=18zvKreajiv0_ikAHAEpJqO3GORfO9s2U" rel="noreferrer">Download: IndexedArray.xlsm</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T03:11:19.713", "Id": "379869", "Score": "0", "body": "I'd `KeyColumn = getKeyColumn\n If KeyColumn < 1 Or KeyColumn > 18 Then Exit Sub`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T07:58:41.273"...
[]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T00:28:40.243", "Id": "197144", "Score": "6", "Tags": [ "vba", "excel", "hash-map" ], "Title": "IndexedArray Class: Uses a Dictionary Keys to Index a 2 Dimensional Array of Values" }
197144
<p><code>currentUserPosts</code> will have a post object with an <code>id</code> that either matches a <code>tempId</code>, an <code>Id</code>, or nothing.</p> <p>If there's a <code>tempId</code> match there won't be an <code>id</code> match and vice versa.</p> <p>This code works but there's something about it I don't like. How can it be refactored?</p> <pre><code>let postIndex; postIndex = currentUserPosts.findIndex(post =&gt; post.id === upsertParams.tempId); if (postIndex === -1) { postIndex = currentUserPosts.findIndex(post =&gt; post.id === upsertParams.id); } if (postIndex === -1) { currentUserPosts.push(upsertParams); } else { currentUserPosts[postIndex] = upsertParams; } </code></pre> <p>Complete function:</p> <pre><code>const upsertIntoApolloCache = (upsertParams) =&gt; { try { const data = client.readQuery({ query: USER_POSTS_QUERY, }); const currentUserPosts = data.currentUser.posts; const postIndex = currentUserPosts.findIndex( post =&gt; post.id === upsertParams.tempId || post.id === upsertParams.id ); if (postIndex === -1) { currentUserPosts.push(upsertParams); } else { currentUserPosts[postIndex] = upsertParams; } client.writeQuery({ query: USER_POSTS_QUERY, data, }); } catch (error) { console.log('!!ERROR in upsertIntoApolloCache!!', error); } }; </code></pre>
[]
[ { "body": "<p>You can group the two conditions for finding into a single <code>||</code> condition, since the <code>post.id</code> can match only one of <code>tempId</code> or <code>id</code>.</p>\n\n<pre><code>let postIndex = currentUserPosts.findIndex(post =&gt; {\n return post.id === upsertParams.id || post...
{ "AcceptedAnswerId": "197157", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T00:54:46.867", "Id": "197146", "Score": "3", "Tags": [ "javascript", "search" ], "Title": "Finding an index in an array of objects with 3 possible outcomes" }
197146
<p>I would really appreciate some feedback on this code. It 100% works (as far as I have tested it). Really just looking to improve where I can. This script is currently hosted on my local PC and is accessible to those I specify via <code>ngrok</code>. This is supposed to be a very rough and simple banking api. Wherein a user has a starting amount of funds, they can create multiple accounts, and keep track of all transactions that occur. I made this in about 5 hours this morning, I challenged myself to "Just get it done" and as I result I spent less time worrying about what is "pythonic" or even good coding practices. All criticisms welcome.</p> <p>Database Template Script:</p> <pre><code>import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine import sqlalchemy_utils #Drop DB if it exists. if sqlalchemy_utils.database_exists('postgresql:///bankapi.db'): sqlalchemy_utils.drop_database('postgresql:///bankapi.db') sqlalchemy_utils.create_database('postgresql:///bankapi.db') Base = declarative_base() #DB Models. class UserWallet(Base): __tablename__ = 'wallet' uid = Column(Integer, primary_key=True, autoincrement=True) funds = Column(Integer, nullable=True) @property def serialize(self): return { 'uid' : uid, 'funds' : funds, } class Account(Base): __tablename__ = 'accounts' aid = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(50), nullable=False) hodlings = Column(Integer, nullable=True) @property def serialize(self): return { 'aid' : self.aid, 'name' : self.name, 'hodlings' : self.hodlings, } class Transaction(Base): __tablename__ = 'transactions' txid = Column(Integer, primary_key=True, autoincrement=True) aid = Column(Integer, ForeignKey('accounts.aid')) amount = Column(Integer, nullable=False) account = relationship(Account) @property def serialize(self): return { 'txid' : self.txid, 'aid' : self.aid, 'amount' : self.amount, } #DB Engine. engine = create_engine('postgresql:///bankapi.db') Base.metadata.create_all(engine) </code></pre> <p>Main Application:</p> <pre><code>from database_template import Base, Account, Transaction, UserWallet import sqlalchemy import flask import random import string import httplib2 import json import sqlalchemy_utils #Initiate Flask Server app = flask.Flask(__name__) #Initiate DB Engine. engine = sqlalchemy.create_engine('postgresql:///bankapi.db') Base.metadata.bind = engine dbsession = sqlalchemy.orm.sessionmaker(bind=engine) session = dbsession() #API reset. @app.route('/reset') def api_reset(): meta = Base.metadata for table in reversed(meta.sorted_tables): session.execute(table.delete()) session.commit() return 'Database Reset, return to / or /accounts' + '\n' #Root / Show all accounts. @app.route('/') @app.route('/accounts') def accounts_all(): user = session.query(UserWallet).all() if user: accounts = session.query(Account).all() if accounts: u = 'Current Wallet: ' + str(user[0].funds) + '\n' x = 'Your accounts are listed below:' +'\n' y = '\n'.join(str(a.aid) for a in accounts) z = '\n''To create a new account, make a POST request to /accounts/new_ac' zz = '\n' + 'arguments for [name] are required.' + '\n' return u + x + y + z + zz else: return 'There are no accounts, curl to make some' + '\n' else: newUser = UserWallet(funds=1000000) session.add(newUser) session.commit() return 'Welcome, your initial personal wallet balance is 1000000sat.' + \ '\n' + 'Follow the curl guide included in the respository to manage' + \ '\n' + 'your accounts. Have fun and rest assured, funds are safe.' + '\n' #Create New Account. @app.route('/accounts/new_ac', methods=['GET','POST']) def account_new(): if flask.request.method == 'POST': data = flask.request.get_json() if data['name']: aname = data['name'] newAccount = Account(name=aname, hodlings=0) session.add(newAccount) session.commit() return '{} Account Successfully Created'.format(newAccount.name) + '\n' else: return 'Arguments [name, password] are required.' + '\n' else: return 'Accounts can only be created via POST requests.' + '\n' #Create New Transaction. @app.route('/accounts/&lt;int:account_id&gt;/tx/new', methods=['GET','POST']) def tx_new(account_id): try: active_ac = session.query(Account).filter_by(aid=account_id).one() except: return 'Invalid Account ID.' + '\n' if flask.request.method == 'POST': data = flask.request.get_json() if data['amount']: tx_amount = data['amount'] check_bal = active_ac.hodlings + tx_amount userwal = session.query(UserWallet).one() check_wal = userwal.funds - tx_amount if check_bal &lt; 0: return 'Not enough hodlings for specified withdrawal.' + '\n' elif check_wal &lt; 0: return 'Not enough funds for specified deposit.' + '\n' new_tx = Transaction(aid=account_id, amount=tx_amount) session.add(new_tx) active_ac.hodlings += tx_amount userwal.funds -= tx_amount session.commit() latest_tx = session.query(Transaction).order_by(Transaction.txid.desc()).first() latest_txid = latest_tx.txid return 'Tx {} succesfully created'.format(latest_txid) + '\n' else: return 'Arguments [amount,password] are required.' + '\n' else: return 'Transactions can only be created via POST requests.' + '\n' #API Serialized Data Endpoints. @app.route('/accounts/&lt;int:account_id&gt;/JSON') def account_page(account_id): try: active_ac = session.query(Account).filter_by(aid=account_id).one() except: return 'Invalid Account ID.' + '\n' return flask.jsonify(Account=active_ac.serialize) @app.route('/accounts/&lt;int:account_id&gt;/tx/JSON') def tx_all(account_id): try: active_tx = session.query(Transaction).filter_by(aid=account_id).all() except: return 'Invalid Account ID.' + '\n' if active_tx: return flask.jsonify(Transaction=[tx.serialize for tx in active_tx]) else: return 'No transactions to display' + '\n' @app.route('/accounts/&lt;int:account_id&gt;/tx/&lt;int:tx_id&gt;/JSON') def tx_page(account_id, tx_id): try: tx = session.query(Transaction).filter_by(txid=tx_id, aid=account_id).one() except: return 'One of the specified IDs is not valid.' + '\n' return flask.jsonify(Transaction=tx.serialize) if __name__ == '__Main__': app.run() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:14:01.153", "Id": "453775", "Score": "0", "body": "Three quick points: (1) use `__init__` in your classes (and `__repr__` if possible). (2) white space after # (3) use fstrings (they are more readable in my opinion. (3) conventio...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T00:58:27.373", "Id": "197147", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Simple Bank API script" }
197147
<p>I'm currently in the process of building my own Chess game engine and could really use some suggestions on how to make this segment of code for calculating diagonal moves more efficient. (This is obviously only for diagonals going Up-Right.)</p> <p>As of now I'm using "Try-Except" to iterate by 1, and then my <code>return</code> statement filters out any off-board values. However this seems like a very bulky way of doing things.</p> <pre><code>import argparse, json chessBoard = [[1, 1, 1, 1, 1, 1, 1, 1] for i in range(8)] chess_map_from_alpha_to_index = { "a" : 0, "b" : 1, "c" : 2, "d" : 3, "e" : 4, "f" : 5, "g" : 6, "h" : 7 } chess_map_from_index_to_alpha = { 0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h" } def getBishopMoves(pos, chessBoard): column, row = list(pos.strip().lower()) row = int(row) - 1 column = chess_map_from_alpha_to_index[column] i,j = row, column solutionMoves = [] #Up-Right Diagonal try: temp = chessBoard[i + 1][j + 1] solutionMoves.append([i + 1, j + 1]) except: pass try: temp = chessBoard[i + 2][j + 2] solutionMoves.append([i + 2, j + 2]) except: pass try: temp = chessBoard[i + 3][j + 3] solutionMoves.append([i + 3, j + 3]) except: pass try: temp = chessBoard[i + 4][j + 4] solutionMoves.append([i + 4, j + 4]) except: pass try: temp = chessBoard[i + 5][j + 5] solutionMoves.append([i + 5, j + 5]) except: pass try: temp = chessBoard[i + 6][j + 6] solutionMoves.append([i + 6, j + 6]) except: pass try: temp = chessBoard[i + 7][j + 7] solutionMoves.append([i + 7, j + 7]) except: pass try: temp = chessBoard[i + 7][j + 7] solutionMoves.append([i + 7, j + 7]) except: pass temp = [i for i in solutionMoves if i[0] &gt;=0 and i[1] &gt;=0] solutionMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in temp] solutionMoves.sort() return solutionMoves </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T07:43:02.993", "Id": "379876", "Score": "2", "body": "Can you give an example of a call to `getBishopMoves()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T14:36:16.277", "Id": "379893", "S...
[ { "body": "<blockquote>\n <p>Go through the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8 style guide</a>. You have inconsistent naming\n convention. A mixed case of <code>camelCase</code> and <code>snake_case</code> throws off\n the developer. Follow <code>snake_case</code> ...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T06:45:10.257", "Id": "197153", "Score": "5", "Tags": [ "python", "performance", "chess" ], "Title": "Diagonal Movement Code for Python Chess Engine" }
197153
<p><strong>Description:</strong></p> <p>Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.</p> <p>Note: A leaf is a node with no children.</p> <p><a href="https://leetcode.com/problems/path-sum-ii/description/" rel="nofollow noreferrer">Leetcode</a></p> <p><strong>Code:</strong></p> <pre><code>class Solution { private List&lt;List&lt;Integer&gt;&gt; paths = new ArrayList&lt;&gt;(); public List&lt;List&lt;Integer&gt;&gt; pathSum(TreeNode root, int sum) { traverse(root, sum, new ArrayList&lt;Integer&gt;()); return paths; } private void traverse(TreeNode root, int sum, ArrayList&lt;Integer&gt; path) { if (root != null) { path.add(root.val); if (root.left == null &amp;&amp; root.right == null &amp;&amp; sum == root.val) { paths.add((ArrayList) path.clone()); } traverse(root.left, sum - root.val, path); traverse(root.right, sum - root.val, path); path.remove(path.size() - 1); } } } </code></pre>
[]
[ { "body": "<p>It's a fine solution. I have a few minor comments.</p>\n\n<ul>\n<li><p>It's easy to overlook that <code>pathSum</code> doesn't clear the content of <code>paths</code>, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it ...
{ "AcceptedAnswerId": "197305", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T13:02:16.123", "Id": "197161", "Score": "2", "Tags": [ "java", "algorithm", "programming-challenge", "tree", "interview-questions" ], "Title": "Find all k-sum paths in a binary tree" }
197161
<blockquote> <p>Problem Statement:</p> <p>You are given a read-only array of n integers from 1 to n. Each integer appears exactly once except A which appears twice and B which is missing.</p> <p>Return A and B.</p> <p>Example</p> <pre><code>Input:[3 1 2 5 3] Output:[3, 4] A = 3, B = 4 </code></pre> </blockquote> <p>I wrote the following code:</p> <pre><code>def repeated_number(number_array): pair_A_B = [] n = len(number_array) for i in number_array: if(number_array.count(i)==2): pair_A_B.append(i) break sample = range(1,n+1) diff = list(set(sample)-set(number_array)) pair_A_B.append(diff[0]) return pair_A_B sample_input = [3,1,2,3,5] print(repeated_number(sample_input)) </code></pre> <p>The code works fine for this problem on my laptop but when I try to submit it on a coding forum it says my code is not efficient. How can I make it efficient in terms of time?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T15:51:16.920", "Id": "379899", "Score": "0", "body": "I don't have time to write a full answer, but it comes down to this: you have a turned an O(n) problem into an O(n^2) problem. Here is the algorithm I would use: create a list of...
[ { "body": "<p>The problem lies in these 2 lines of code:</p>\n\n<pre><code> for i in number_array:\n if(number_array.count(i)==2):\n</code></pre>\n\n<p>Here for each number you are counting the number of occurrences in the array. Now, by doing that, You are reiterating over the numbers which are already counte...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T14:48:23.027", "Id": "197163", "Score": "0", "Tags": [ "python", "algorithm", "array", "set" ], "Title": "Finding Repeat and missing numbers in an array" }
197163
<p>I've made some code that reads in text files (which hold quite large vectors of word frequencies), which in turn stores each index of a vector within an <code>ArrayList</code> for their specified team (i.e. <code>Arsenal</code> vector to the <code>Arsenal</code> <code>ArrayList</code>, <code>Chelsea</code> vector the <code>Chelsea</code> <code>ArrayList</code>, etc.). It then uses a cosine similarity function to determine similarity between the two documents and writes it to a file. </p> <p>What I would like is to make the code that reads in the text files (and storing them in their corresponding <code>ArrayList</code> more efficient), rather than me change the parameters of the while loop each time i need to use it.</p> <pre><code>public static Double cosineSimilarity(ArrayList&lt;Integer&gt; vectorOne, ArrayList&lt;Integer&gt; vectorTwo) { Double dotProduct = 0.0; Double normVecA = 0.0; Double normVecB = 0.0; for(int i = 0; i &lt; vectorOne.size(); i++) { dotProduct += vectorOne.get(i) * vectorTwo.get(i); normVecA += Math.pow(vectorOne.get(i), 2); normVecB += Math.pow(vectorTwo.get(i), 2); } return dotProduct / (Math.sqrt(normVecA) * Math.sqrt(normVecB)); } public static void main(String[] args) throws IOException { ArrayList&lt;Integer&gt; arsenal = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; chelsea = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; liverpool = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; manchesterCity = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; manchesterUnited = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; tottenham = new ArrayList&lt;Integer&gt;(); Scanner textFile = new Scanner(new File("Enter textfile here")); while (textFile.hasNext()) { arsenal.add(textFile.nextInt()); } Double output = cosineSimilarity(arsenal, chelsea); File fileName; FileWriter fw; // Create a new textfile for listOfWords fileName = new File("arsenalCosineSimilarities.txt"); fw = new FileWriter(fileName, true); fw.write(String.valueOf("Chelsea: " + output + "\n")); fw.close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T15:56:41.847", "Id": "379901", "Score": "1", "body": "In the current example code, `chelsea` never gets any values. Do you have an example text file and can made this code runnable and testable so that it's possible to try it out by...
[ { "body": "<p>For flexibility, your <code>cosineSimilarity()</code> method should taken in <code>List&lt;Integer&gt;</code> arguments, instead of <code>ArrayList&lt;Integer&gt;</code> arguments. This method doesn't care how the list is stored, only that it is a list which implements <code>.size()</code> and <c...
{ "AcceptedAnswerId": "197170", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T15:39:02.320", "Id": "197164", "Score": "0", "Tags": [ "java", "clustering" ], "Title": "Determining the similarity between two documents" }
197164
<p>I recently published an iOS control/component called <code>BJDraggable</code> which basically, with a call of a method, enables us to drag a view within its superview boundary. The whole setup works using the <code>UIKitDynamics</code> API. <em>(Scroll to last to see the output achieved.)</em></p> <p>These are the methods I expose to consumers. You could follow up from these method calls in the detailed code (<strong>BJDraggable.swift</strong>).</p> <pre><code>@objc protocol BJDraggable: class { @objc func addDraggability(withinView referenceView: UIView) @objc func addDraggability(withinView referenceView: UIView, withMargin insets:UIEdgeInsets) @objc func removeDraggability() } </code></pre> <hr> <p>Here is my full code. Please bear with the length of the code; it is pretty long. <a href="https://github.com/BadhanGanesh/BJDraggable.git" rel="nofollow noreferrer">Demo project is available here at GitHub.</a> Thanks in advance for your time.</p> <p><strong>BJDraggable.swift</strong></p> <pre><code>import UIKit var kReferenceViewKey: String = "ReferenceViewKey" var kDynamicAnimatorKey: String = "DynamicAnimatorKey" var kAttachmentBehaviourKey: String = "AttachmentBehaviourKey" var kPanGestureKey: String = "PanGestureKey" var kResetPositionKey: String = "ResetPositionKey" fileprivate enum BehaviourNames { case main case border case collision case attachment } /**A simple protocol *(No need to implement methods and properties yourself. Just drop-in the BJDraggable file to your project and all done)* utilizing the powerful `UIKitDynamics` API, which makes **ANY** `UIView` draggable within a boundary view that acts as collision body, with a single method call. */ @objc protocol BJDraggable: class { /** Gives you the power to drag your `UIView` anywhere within a specified view, and collide within its bounds. - parameter referenceView: The boundary view which acts as a wall, and your view will collide with it and would never fall out of bounds hopefully. **Note that the reference view should contain the view that you're trying to add draggability to in its view hierarchy. The app would crash otherwise.** */ @objc func addDraggability(withinView referenceView: UIView) /** This single method call will give you the power to drag your `UIView` anywhere within a specified view, and collide within its bounds. - parameter referenceView: This is the boundary view which acts as a wall, and your view will collide with it and would never fall out of bounds hopefully. **Note that the reference view should contain the view that you're trying to add draggability to in its view hierarchy. The app would crash otherwise.** - parameter insets: If you want to make the boundary to be offset positively or negatively, you can specify that here. This is nothing but a margin for the boundary. */ @objc func addDraggability(withinView referenceView: UIView, withMargin insets:UIEdgeInsets) /** Removes the power from you, to drag the view in question */ @objc func removeDraggability() } ///Implementation of `BJDraggable` protocol extension UIView: BJDraggable { // ////////////////////////////////////////////////////////////////////////////////////////// //MARK:- //MARK: Properties //MARK:- ////////////////////////////////////////////////////////////////////////////////////////// // public var shouldResetViewPositionAfterRemovingDraggability: Bool { get { let getValue = (objc_getAssociatedObject(self, &amp;kResetPositionKey) as? Bool) return getValue == nil ? false : getValue! } set { objc_setAssociatedObject(self, &amp;kResetPositionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.translatesAutoresizingMaskIntoConstraints = !newValue } } fileprivate var referenceView: UIView? { get { return objc_getAssociatedObject(self, &amp;kReferenceViewKey) as? UIView } set { objc_setAssociatedObject(self, &amp;kReferenceViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var animator: UIDynamicAnimator? { get { return objc_getAssociatedObject(self, &amp;kDynamicAnimatorKey) as? UIDynamicAnimator } set { objc_setAssociatedObject(self, &amp;kDynamicAnimatorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var attachmentBehaviour: UIAttachmentBehavior? { get { return objc_getAssociatedObject(self, &amp;kAttachmentBehaviourKey) as? UIAttachmentBehavior } set { objc_setAssociatedObject(self, &amp;kAttachmentBehaviourKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var panGestureRecognizer: UIPanGestureRecognizer? { get { return objc_getAssociatedObject(self, &amp;kPanGestureKey) as? UIPanGestureRecognizer } set { objc_setAssociatedObject(self, &amp;kPanGestureKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // ////////////////////////////////////////////////////////////////////////////////////////// //MARK:- //MARK: Method Implementations //MARK:- ////////////////////////////////////////////////////////////////////////////////////////// // final func addDraggability(withinView referenceView: UIView) { self.addDraggability(withinView: referenceView, withMargin: UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)) } final func addDraggability(withinView referenceView: UIView, withMargin insets:UIEdgeInsets) { guard self.animator == nil else { return } /////////////////////// /////Configuration///// /////////////////////// performInitialConfiguration() addPanGestureRecognizer() //////////////////////////////////////////////// /////Getting Collision Items For Behaviours///// //////////////////////////////////////////////// let collisionItems = self.drawAndGetCollisionViewsAround(referenceView, withInsets: insets) //////////////////// /////Behaviours///// //////////////////// let mainItemBehaviour = get(behaviour: .main, for: referenceView, withInsets: insets, configuredWith: collisionItems)! let borderItemsBehaviour = get(behaviour: .border, for: referenceView, withInsets: insets, configuredWith: collisionItems)! let collisionBehaviour = get(behaviour: .collision, for: referenceView, withInsets: insets, configuredWith: collisionItems)! let attachmentBehaviour = get(behaviour: .attachment, for: referenceView, withInsets: insets, configuredWith: collisionItems)! ////////////////// /////Animator///// ////////////////// let animator = UIDynamicAnimator.init(referenceView: referenceView) animator.addBehavior(mainItemBehaviour) animator.addBehavior(borderItemsBehaviour) animator.addBehavior(collisionBehaviour) animator.addBehavior(attachmentBehaviour) ///////////////////// /////Persistence///// ///////////////////// self.animator = animator self.referenceView = referenceView self.attachmentBehaviour = attachmentBehaviour as? UIAttachmentBehavior } final func removeDraggability() { if let recognizer = self.panGestureRecognizer { self.removeGestureRecognizer(recognizer) } self.translatesAutoresizingMaskIntoConstraints = !self.shouldResetViewPositionAfterRemovingDraggability self.animator?.removeAllBehaviors() if let subviews = self.referenceView?.subviews { for view in subviews { if view.tag == 122 || view.tag == 222 || view.tag == 322 || view.tag == 422 { view.removeFromSuperview() } } } self.referenceView = nil self.attachmentBehaviour = nil self.animator = nil self.panGestureRecognizer = nil } // ////////////////////////////////////////////////////////////////////////////////////////// //MARK:- //MARK: Helpers 1 //MARK:- ////////////////////////////////////////////////////////////////////////////////////////// // fileprivate func performInitialConfiguration() { self.isUserInteractionEnabled = true } fileprivate func addPanGestureRecognizer() { let panGestureRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(self.panGestureHandler(_:))) self.addGestureRecognizer(panGestureRecognizer) self.panGestureRecognizer = panGestureRecognizer } @objc final func panGestureHandler(_ gesture: UIPanGestureRecognizer) { guard let referenceView = self.referenceView else { return } let touchPoint = gesture.location(in: referenceView) self.attachmentBehaviour?.anchorPoint = touchPoint } fileprivate func get(behaviour:BehaviourNames, for referenceView:UIView, withInsets:UIEdgeInsets, configuredWith boundaryCollisionItems:[UIDynamicItem]) -&gt; UIDynamicBehavior? { let allItems = [self] + boundaryCollisionItems switch behaviour { case .border: let borderItemsBehaviour = UIDynamicItemBehavior.init(items: boundaryCollisionItems) borderItemsBehaviour.allowsRotation = false borderItemsBehaviour.isAnchored = true borderItemsBehaviour.friction = 2.0 return borderItemsBehaviour case .main: let mainItemBehaviour = UIDynamicItemBehavior.init(items: [self]) mainItemBehaviour.allowsRotation = false mainItemBehaviour.isAnchored = false mainItemBehaviour.friction = 2.0 return mainItemBehaviour case .collision: let collisionBehaviour = UICollisionBehavior.init(items: allItems) collisionBehaviour.collisionMode = .items collisionBehaviour.addBoundary(withIdentifier: "Boundary" as NSCopying, for: self.boundaryPathFor(referenceView)) return collisionBehaviour case .attachment: let attachmentBehaviour = UIAttachmentBehavior.init(item: self, attachedToAnchor: self.center) return attachmentBehaviour } } // ////////////////////////////////////////////////////////////////////////////////////////// //MARK:- //MARK: Helpers 2 //MARK:- ////////////////////////////////////////////////////////////////////////////////////////// // func alteredFrameByPoints(_ point:CGFloat) -&gt; CGRect { var newFrame = self.frame newFrame.origin.x -= point newFrame.origin.y -= point newFrame.size.width += point * 2 newFrame.size.height += point * 2 return newFrame } fileprivate func boundaryPathFor(_ view:UIView) -&gt; UIBezierPath { let cgPath = CGPath.init(rect: view.alteredFrameByPoints(2.0), transform:nil) return UIBezierPath.init(cgPath: cgPath) } fileprivate func getNewRectFrom(rect:CGRect, byApplying insets:UIEdgeInsets) -&gt; CGRect { var newRect:CGRect = .zero let x = rect.origin.x + insets.left let y = rect.origin.y + insets.top let width = rect.width - insets.right let height = rect.height - insets.bottom newRect.origin.x = x newRect.origin.y = y newRect.size.width = width newRect.size.height = height return newRect } @discardableResult fileprivate func drawAndGetCollisionViewsAround(_ referenceView:UIView, withInsets insets:UIEdgeInsets) -&gt; ([UIView]) { let boundaryViewWidth = CGFloat(1) let boundaryViewHeight = CGFloat(1) //////////////////// ////Get New Rect//// //////////////////// let newReferenceViewRect = self.getNewRectFrom(rect:referenceView.alteredFrameByPoints(1), byApplying:insets) //////////// ////Left//// //////////// let leftView = UIView(frame: CGRect.init(x: newReferenceViewRect.origin.x - (boundaryViewWidth - 1), y: newReferenceViewRect.origin.y, width: boundaryViewWidth, height: newReferenceViewRect.size.height - insets.bottom)) leftView.isUserInteractionEnabled = false leftView.tag = 122 ///////////// ////Right//// ///////////// let rightView = UIView(frame: CGRect.init(x: newReferenceViewRect.size.width - 2.0, y: newReferenceViewRect.origin.y, width: boundaryViewWidth, height: newReferenceViewRect.size.height - insets.bottom)) rightView.isUserInteractionEnabled = false rightView.tag = 222 /////////// ////Top//// /////////// let topView = UIView(frame: CGRect.init(x: newReferenceViewRect.origin.x, y: newReferenceViewRect.origin.y - (boundaryViewHeight - 1), width: newReferenceViewRect.size.width - insets.right, height: boundaryViewHeight)) topView.isUserInteractionEnabled = false topView.tag = 322 ////////////// ////Bottom//// ////////////// let bottomView = UIView(frame: CGRect.init(x: newReferenceViewRect.origin.x, y: newReferenceViewRect.size.height - 2.0, width: newReferenceViewRect.size.width - insets.right, height: boundaryViewHeight)) bottomView.isUserInteractionEnabled = false bottomView.tag = 422 /////////////////// ////Add Subview//// /////////////////// referenceView.addSubview(leftView) referenceView.addSubview(rightView) referenceView.addSubview(topView) referenceView.addSubview(bottomView) return [leftView, rightView, topView, bottomView] } } </code></pre> <hr> <p><strong>This is how it works:</strong></p> <p><a href="https://github.com/BadhanGanesh/BJDraggable/blob/master/Resources/BJDraggable.gif?raw=true" rel="nofollow noreferrer"><img src="https://github.com/BadhanGanesh/BJDraggable/blob/master/Resources/BJDraggable.gif?raw=true" alt="Output"></a></p>
[]
[ { "body": "<p>Comparing an optional value with <code>nil</code> as in</p>\n\n<pre><code>return getValue == nil ? false : getValue!\n</code></pre>\n\n<p>is better done with the nil-coalescing operator <code>??</code>:</p>\n\n<pre><code>return getValue ?? false\n</code></pre>\n\n<p>It is shorter, avoids the force...
{ "AcceptedAnswerId": "197175", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T16:30:06.813", "Id": "197166", "Score": "3", "Tags": [ "swift", "ios", "protocols", "uikit" ], "Title": "Adding dragging ability to a UIView using UIKitDynamics" }
197166
<p>I am very new programming and am trying to develop a small tycoon game as a hobby project in Unity. This algorithm executes beautifully but if 100+ agents are getting new paths simultaneously there is a significant drop in frame rate. Where should I start with optimizing?</p> <p>I use 4 classes for my pathfinding. The <code>PathFinder</code> creates a <code>PathGrid</code> when Initialized, and has the actual algorithm. The <code>PathGrid</code> contains a multidimensional array of <code>PathNode</code>, and all methods needed to modify the grid. The PathNode is just a location, corresponding to a tile, and a <code>List</code> of <code>PathEdge</code>. <code>PathEdge</code> is a simple struct containing a ref to a <code>PathNode</code> (the edge's end) and a move cost.</p> <p><code>PathController</code>:</p> <pre><code>public class PathController : MonoBehaviour { //main control class for game GameController gameController; PathGrid pathGrid; public void Initialize() { pathGrid = new PathGrid (); } public Queue&lt;Location&gt; GetPath (Location start, Location end) { //GameController keeps record of map size if (gameController.IsInBounds (start) &amp;&amp; gameController.IsInBounds (end)) { int xSize = gameController.xSize; int zSize = gameController.zSize; Queue&lt;Location&gt; path = new Queue&lt;Location&gt; (); List&lt;PathNode&gt; frontier = new List&lt;PathNode&gt; (); bool[,] visited = new bool[xSize,zSize]; Dictionary&lt;PathNode, PathNode&gt; leadingMap = new Dictionary&lt;PathNode, PathNode&gt; (); float[,] scores = new float[xSize,zSize]; Location currentPosition = start; int attempts = 0; while (true) { if (gameController.AreLocationsIdentical (currentPosition, end)) { break; } else { attempts++; if (attempts &gt;= 10000) { Debug.LogError ("Frontier while loop timed out."); return null; } PathNode currentNode = pathGrid.GetPathNode (currentPosition); foreach (PathEdge edge in currentNode.edges) { int x = edge.end.location.x; int z = edge.end.location.z; if (!visited [x,z] &amp;&amp; !frontier.Contains (edge.end)) { float f = Mathf.Abs (end.x - currentPosition.x) + Mathf.Abs (end.z - currentPosition.z); float g = attempts + edge.moveCost; scores [x, z] = f + g; frontier.Add (edge.end); leadingMap.Add (edge.end, currentNode); } } frontier.Remove (currentNode); visited [currentPosition.x, currentPosition.z] = true; PathNode best = frontier [0]; foreach (PathNode node in frontier) { if (scores [node.location.x, node.location.z] &lt; scores [best.location.x, best.location.z]) { best = node; } } currentPosition = new Location (best.location.x, best.location.z); } } attempts = 0; Stack&lt;Location&gt; rev = new Stack&lt;Location&gt; (); currentPosition = end; while (true) { attempts++; if (attempts &gt;= 10000) { Debug.LogError ("While loop for stack population timed out!"); return null; } if (gameController.AreLocationsIdentical (currentPosition, start)) { break; } rev.Push (currentPosition); PathNode nextNode = leadingMap [pathGrid.GetPathNode(currentPosition)]; currentPosition = nextNode.location; } int pathCount = rev.Count; for (int i = 0; i &lt; pathCount; i++) { path.Enqueue (rev.Pop ()); } return path; } else { Debug.LogError ("Tried to get a path with start or end out of bounds: S " + start.x + "," + start.z + " E " + end.x + "," + end.z); return null; } } public void UpdateNodeEdges (Location location) { pathGrid.UpdateNodeEdges (location); } } </code></pre> <p><code>PathGrid</code>:</p> <pre><code>public class PathGrid { public PathNode[,] pathNodes { get; protected set; } public PathGrid () { int x = GameController.Instance.xSize; int z = GameController.Instance.zSize; pathNodes = new PathNode[x,z]; //Create all nodes for (int i = 0; i &lt; x; i++) { for (int j = 0; j &lt; z; j++) { PathNode node = new PathNode (new Location (i, j)); pathNodes [i, j] = node; } } //Create all edges for (int i = 0; i &lt; x; i++) { for (int j = 0; j &lt; z; j++) { UpdateNodeEdges (new Location (i, j)); } } } public PathNode GetPathNode (Location location) { if (GameController.Instance.IsInBounds (location)) { return pathNodes [location.x, location.z]; } else { Debug.LogError ("Tried to get PathNode out of range: " + location.x + "," + location.z); return null; } } public void UpdateNodeEdges(Location location) { List&lt;PathEdge&gt; edges = new List&lt;PathEdge&gt; (); foreach (PathNode neighbor in GetNodeNeighbors(location)) { edges.Add (CreatePathEdge (location, neighbor.location)); } GetPathNode (location).edges = edges; } List&lt;PathNode&gt; GetNodeNeighbors (Location location) { List&lt;PathNode&gt; neighbors = new List&lt;PathNode&gt; (); foreach (Location neighborLoc in GameController.Instance.DirectionalLocations(location)) { neighbors.Add (GetPathNode (neighborLoc)); } return neighbors; } PathEdge CreatePathEdge (Location start, Location end) { int moveCost = (GetMovementCostForTile (start) + GetMovementCostForTile (end)) / 2; PathEdge edge = new PathEdge (moveCost, GetPathNode (end)); return edge; } int GetMovementCostForTile (Location location) { TileData data = GameController.Instance.dataController.GetTileData (location); if (data.installedObject == null) { return 20; } else { switch (data.installedObject.installedObjectType) { case InstalledObjectType.None: return 20; case InstalledObjectType.Structure: if (data.installedObject.subType == 1) { return 2; } else { return 1000; } case InstalledObjectType.Nature: return 1000; case InstalledObjectType.Resource: return 400; default: Debug.LogError ("Tried to get move cost for unsupported tile at " + location.x + "," + location.z); return 100; } } } } </code></pre> <p><code>PathNode</code>:</p> <pre><code>public class PathNode { public Location location; public List&lt;PathEdge&gt; edges; public PathNode (Location location) { this.location = location; } } </code></pre> <p><code>PathEdge</code>:</p> <pre><code>public struct PathEdge { public int moveCost; public PathNode end; public PathEdge (int moveCost, PathNode end) { this.moveCost = moveCost; this.end = end; } } </code></pre> <p>In case it's needed, here is the script for Location, as it's a custom struct I made and is used extensively throughout my classes.</p> <p><code>Location</code>:</p> <pre><code>public struct Location { public int x { get; set; } public int z { get; set; } public Location(int x, int z) : this() { this.x = x; this.z = z; } } </code></pre> <p>This is my first time asking for help on a project. ANY critique is greatly appreciated as I feel as though self teaching is sometimes like reaching in to the dark and hoping to come up with a working solution. I have not run in to a problem with optimization yet, and could not find a good example to fit my needs with my underdeveloped google-fu skills.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T17:56:02.690", "Id": "379911", "Score": "1", "body": "I havn't the energy to write a proper answer now - hopefully you'll get one - but to get you started, you need to use a smarter data-structure for the frontier (i.e. a priority q...
[ { "body": "\n\n<p>There is a lot of code here, so there is a lot to say; no way I'll covered everything! I'll do the easy things first, and then assume lots of them before we look at the algorithm.</p>\n\n<h2>Style</h2>\n\n<ul>\n<li><p>Usually C#ers put starting braces for everything on a new line.</p></li>\n<l...
{ "AcceptedAnswerId": "197204", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T17:18:57.110", "Id": "197167", "Score": "5", "Tags": [ "c#", "beginner", "algorithm", "pathfinding", "unity3d" ], "Title": "A* Algorithm in C# for pathfinding 2D tile grid" }
197167
<p>My neural network is buggy somewhere. However, the reason I am posting here and not Stack Overflow is because a buggy neural network can still be trained to some degree and will compile/perform better than no neural network, unlike other programs. These "bugs" can be solved by optimizations/better initialization of the weight values/better implementation of back-propagation (it is not completely wrong).</p> <p>No neural network can be correct 100% (there is always something I can change to make it have a lower cost). The network does not have a binary output or certain number it must hit, rather, it must simply reduce the cost after each epoch, which it currently does. Asking for reviews regarding how how I can make it reduce the cost further does not imply that my program is not currently working. Rather, it implies that it is not most optimal, which is present among other questions as well (as other questions ask how programs can be more performant, for instance).</p> <p>Since my neural network is from scratch (and thus pretty long for the casual reviewer), I would like two specific functions to be reviewed that are causing me problems:</p> <ol> <li><p><code>offsetLayerIndex</code></p> <p>Since there are no weights for a neural network in the first layer, I offset all the layer indices of my stored weights by -1 when writing to the weight storage. However, changing the offset to 0 (none) changed the program, even though every where I write to weight storage I offset the index.</p></li> <li><p><code>updateParameterGradients</code></p> <p>This is the backpropagation implementation which I based off these 4 formulas from <a href="http://neuralnetworksanddeeplearning.com/chap2.html" rel="nofollow noreferrer">here</a>:</p> <p><a href="https://i.stack.imgur.com/kl8DJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kl8DJ.png" alt="enter image description here"></a></p></li> </ol> <p>Finally, the printing in the <code>#if</code> -> <code>#endif</code> printing macros is the least important (just for convenience), and thus doesn't need to be reviewed.</p> <p><strong>functions.h</strong></p> <pre><code>#ifndef NEURALNETWORK_FUNCTIONS_H #define NEURALNETWORK_FUNCTIONS_H /** * Activates the value given by the weighted sum function. This activated value will be put * into the neuron. * * @param weightedSum The result of the weighted sum function. * @return The activated neuron value. */ double getDefaultActivation(double weightedSum); /** * Calculates the derivative of the sigmoid function at the weighted sum, which, when inputted into sigmoid, * gives activationValue. * * @param activationValue Since the derivative of a sigmoid does not depend on the input of a sigmoid, * but rather the output of the sigmoid, the value of the neuron is passed for efficiency. * @return activationValue * (1 - activationValue) */ double getDefaultActivationDerivative(double activationValue); /** * Calculates the derivative of the function that produces the weighted sum given a weight, neuron value and bias, * with respect to the neuron value. * * @param weight The weight that the function multiplies with the neuron value, which is w[endLayerIndex, endNeuronIndex, * startNeuronIndex] * @return Δ Z[endLayerIndex, endNeuronIndex] / Δ a[startLayerIndex, startNeuronIndex] */ double getWeightedSumNeuronValueDerivative(double weight); /** * Calculates the derivative of the function that produces the weighted sum given a weight, neuron value and bias, * with respect to the weight. * * @param neuronValue The neuron value that the function multiplies with the weight, which is a[startLayerIndex, * startNeuronIndex] * @return Δ Z[endLayerIndex, endNeuronIndex] / Δ w[endLayerIndex, endNeuronIndex] */ double getWeightedSumWeightDerivative(double neuronValue); /** * Calculates the derivative of the function that produces the weighted sum given a weight, neuron value and bias, * with respect to the bias. * * @return Δ Z[endLayerIndex, endNeuronIndex] / Δ b[endLayerIndex, endNeuronIndex] */ double getWeightedSumBiasDerivative(); /** * Calculates the cost of {@code neuronValue} relative to the target output. * * @param neuronValue The output produced by the neural network. * @param intendedValue The correct output that the neural network aims to produce. * @return The "cost"/effect of the network outputting {@code neuronValue} instead of {@code intendedValue}. */ double getDefaultCost(double neuronValue, double intendedValue); /** * Calculates the derivative of the cost of {@code neuronValue} relative to the target output. * * @param neuronValue The output produced by the neural network. * @param intendedValue The correct output that the neural network aims to produce. * @return Δ "cost"/effect of the network outputting {@code neuronValue} instead of {@code intendedValue} / * Δ neuronValue */ double getDefaultCostDerivative(double neuronValue, double intendedValue); /** * Calculates the initial value that a weight[endLayerIndex][endNeuronIndex][startNeuronIndex] * should have before the first epoch of the network. * * @param previousLayerSize Number of neurons in startLayerIndex. * @param layerSize Number on neurons in endLayerIndex. * @return */ double getDefaultInitialWeightValue(double previousLayerSize, double layerSize); /** * Calculates the initial value that a bias[endLayerIndex][endNeuronIndex] * should have before the first epoch of the network. * * @param previousLayerSize Number of neurons in startLayerIndex. * @param layerSize Number on neurons in endLayerIndex. * @return */ double getDefaultInitialBiasValue(double previousLayerSize, double layerSize); #endif </code></pre> <p><strong>functions.c</strong></p> <pre><code>#include "functions.h" #include "math.h" double getDefaultActivation(double weightedSum) { double eToWSum = pow(M_E, weightedSum); return eToWSum / (eToWSum + 1); } double getDefaultActivationDerivative(double activationValue) { return activationValue * (1 - activationValue); } /** * start_index can be any value * * @param neuronValue value of w[column][end_index][start_index] * @return delta z[column, end_index] / delta w[column, end_index, start_index]. This is always * equivalent to the neuron value itself since weight is multiplied with the neuron value when calculating * weighted sum. */ double getWeightedSumWeightDerivative(double neuronValue) { return neuronValue; } double getWeightedSumNeuronValueDerivative(double weight) { return weight; } double getDefaultInitialWeightValue(double previousLayerSize, double layerSize) { return sqrt(2 / (previousLayerSize)); } double getDefaultInitialBiasValue(double previousLayerSize, double layerSize) { return 0; } /** * @return delta z[column, end_index] / delta b[column, end_index]. This is always * constant (1) since the bias is not multiplied by the neuron value when calculating weighted sum. */ double getWeightedSumBiasDerivative() { return 1; } double getDefaultCost(double neuronValue, double intendedValue) { double difference = neuronValue - intendedValue; return pow(difference, 2); } double getDefaultCostDerivative(double neuronValue, double intendedValue) { return neuronValue - intendedValue; } </code></pre> <p><strong>model.h</strong></p> <pre><code>#ifndef NEURALNETWORK_MODEL_H #define NEURALNETWORK_MODEL_H #include &lt;stdbool.h&gt; #include "data.h" #define NUMBER_OF_LAYERS 3 #define INPUT_LAYER 0 #define OUTPUT_LAYER (NUMBER_OF_LAYERS - 1) #define NUMBER_OF_TRAINING_FEATURE_VECTORS 2 typedef double (*CostFunction)(double, double); typedef double (*ActivationFunction)(double); typedef double (*WeightInitializationFunction)(double, double); typedef double (*BiasInitializingFunction)(double, double); /** * Represents a model to be used in regards to training the vehicle to move efficiently. * Implemented as a neural network. */ struct Model { /* Weight of link between two neurons is received with indices * [layer index of end neuron][index of end neuron within its layer][index of start neuron within its layer] */ double** weights[NUMBER_OF_LAYERS - 1]; double* biases[NUMBER_OF_LAYERS - 1]; double* values[NUMBER_OF_LAYERS]; int neuronsPerLayer[NUMBER_OF_LAYERS]; double learningRate; /** * the function used to activate the neuron. The value returned by this function is put into the neuron. */ ActivationFunction getActivation; /** * the derivative of the function used to activate the neuron. */ ActivationFunction getActivationChange; /** * the function uses to calculate the cost, given an output neuron's value and its target value */ CostFunction getCost; /** * the function used to calculate the derivative of the cost with respect to the output neuron's value, given the * output neuron's value and its target value */ CostFunction getCostDerivative; WeightInitializationFunction getInitialWeightValue; BiasInitializingFunction getInitialBiasValue; /** * specifies whether the given activation function derivative can take the output of the activation function * rather than the input. This is the case for sigmoid */ bool activationFunctionDerivativeUsesOutput; }; void train(struct Model* model, struct Data* data, int inputColumnIndices[], int outputColumnIndices[]); void test(struct Model* model, struct Data* data, int inputColumnIndices[], int outputColumnIndices[], double* predictedOutputs[], double costs[]); void compute(struct Model* model, struct Data* data, int inputColumnIndices[], double cost[]); void initParameters(struct Model* model); void initValues(struct Model* model); int offsetLayer(int layerIndex); void initInput(double input[], const double entry[], const int inputColumnIndices[], int inputColumnIndicesCount); void initTargetOutput(double targetOutput[], const double entry[], const int targetOutputIndices[], int targetOutputIndicesCount); #endif </code></pre> <p><strong>model.c</strong></p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;memory.h&gt; #include "model.h" #include "functions.h" #define GRADIENT_CHECKING true #define PRINT_NEURON_VALUE false #define PRINT_WEIGHT_UPDATE false #define PRINT_BIAS_UPDATE false #define PRINT_EPOCH_UPDATE true /** * No weights are in the INPUT_LAYER. Thus, layer N is indexed as N - 1 in the weights * array of matrices. * @param layerIndex The layer index within the neural network. * @return The index within the weights storage of the matrix of weights that belong to layers[layerIndes]. */ int offsetLayer(int layerIndex) { return layerIndex - 1; } /** * @param model * @param input The head to ann input array of size &lt;code&gt;model.neuronsPerLayer[INPUT_LAYER]&lt;/code&gt; that has the inputs * of the model. */ void setInput(struct Model* model, double* inputHead) { model-&gt;values[INPUT_LAYER] = inputHead; } void propagateInputForward(struct Model* model, double* inputHead) { setInput(model, inputHead); for (int endLayerIndex = 1; endLayerIndex &lt; NUMBER_OF_LAYERS; endLayerIndex++) { int offsetEndLayerIndex = offsetLayer(endLayerIndex); int startLayerIndex = endLayerIndex - 1; int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[startLayerIndex]; for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { double weightedSum = 0.0; double bias = model-&gt;biases[offsetEndLayerIndex][endNeuronIndex]; for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { double weightOfLink = model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex]; double previousNeuronValue = model-&gt;values[startLayerIndex][startNeuronIndex]; double weightedInfluence = weightOfLink * previousNeuronValue + bias; weightedSum += weightedInfluence; } double activatedNeuronValue = model-&gt;getActivation(weightedSum); #if PRINT_NEURON_VALUE printf("Neuron[%i][%i] - Pre-Acivation: %lf, Post-Activation: %lf\n", layerIndex, neuronIndex, weightedSum, activatedNeuronValue); #endif model-&gt;values[endLayerIndex][endNeuronIndex] = activatedNeuronValue; } } } #if GRADIENT_CHECKING double getTotalCost(struct Model* model, const double targetOutputs[]) { int outputNeuronCount = model-&gt;neuronsPerLayer[OUTPUT_LAYER]; double totalCost = 0.0; for (int outputNeuronIndex = 0; outputNeuronIndex &lt; outputNeuronCount; outputNeuronIndex++) { double outputNeuronValue = model-&gt;values[OUTPUT_LAYER][outputNeuronIndex]; double expectedOutputNeuronValue = targetOutputs[outputNeuronIndex]; double cost = model-&gt;getCost(outputNeuronValue, expectedOutputNeuronValue); totalCost += cost; } return totalCost; } void initCheckParameterGradients(struct Model* model, double** checkWeightGradients[], double* checkBiasGradients[]) { for (int endLayerIndex = 1; endLayerIndex &lt; NUMBER_OF_LAYERS; endLayerIndex++) { int offsetEndLayerIndex = offsetLayer(endLayerIndex); int startLayerIndex = endLayerIndex - 1; int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[startLayerIndex]; checkWeightGradients[offsetEndLayerIndex] = malloc(sizeof(double*) * endNeuronCount); checkBiasGradients[offsetEndLayerIndex] = malloc(sizeof(double) * endNeuronCount); for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { checkWeightGradients[offsetEndLayerIndex][endNeuronIndex] = malloc(sizeof(double) * startNeuronCount); checkBiasGradients[offsetEndLayerIndex][endNeuronIndex] = 0.0; for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { checkWeightGradients[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex] = 0; } } } } /** * Updates the check weight and bias gradients (computed numerically as opposed to through back propagation). * * @param model * @param input * @param targetOutput * @param checkWeightGradients * @param checkBiasGradients */ void updateCheckParameterGradients(struct Model* model, double input[], const double targetOutput[], double** checkWeightGradient[], double* checkBiasGradients[]) { static float epsilon = 1e-6; double preChangeTotalCost; double postChangeTotalCost; double costDifference; for (int endLayerIndex = 1; endLayerIndex &lt; NUMBER_OF_LAYERS; endLayerIndex++) { int offsetEndLayerIndex = offsetLayer(endLayerIndex); int startLayerIndex = endLayerIndex - 1; int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[startLayerIndex]; for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { propagateInputForward(model, input); preChangeTotalCost = getTotalCost(model, targetOutput); model-&gt;biases[offsetEndLayerIndex][endNeuronIndex] += epsilon; propagateInputForward(model, input); postChangeTotalCost = getTotalCost(model, targetOutput); costDifference = postChangeTotalCost - preChangeTotalCost; double checkBiasDeltaInfluence = costDifference / epsilon; checkBiasDeltaInfluence *= model-&gt;learningRate; checkBiasGradients[offsetEndLayerIndex][endNeuronIndex] += checkBiasDeltaInfluence; model-&gt;biases[offsetEndLayerIndex][endNeuronIndex] -= epsilon; for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { propagateInputForward(model, input); preChangeTotalCost = getTotalCost(model, targetOutput); model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex] += epsilon; propagateInputForward(model, input); postChangeTotalCost = getTotalCost(model, targetOutput); // Undo change model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex] -= epsilon; costDifference = postChangeTotalCost - preChangeTotalCost; double checkWeightDeltaInfluence = costDifference / epsilon; checkWeightDeltaInfluence *= model-&gt;learningRate; checkWeightGradient[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex] += checkWeightDeltaInfluence; } } } } void printCheckParamterGradients(struct Model *model, double** checkWeightGradients[], double* checkBiasGradients[]) { for (int endLayerIndex = 1; endLayerIndex &lt; NUMBER_OF_LAYERS; endLayerIndex++) { int offsetEndLayerIndex = offsetLayer(endLayerIndex); int startLayerIndex = endLayerIndex - 1; int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[startLayerIndex]; for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { double checkBiasDelta = checkBiasGradients[offsetEndLayerIndex][endNeuronIndex]; printf("Check Δ Bias[%i][%i] = %lf\n", endLayerIndex, endNeuronIndex, checkBiasDelta); for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { double checkWeightDelta = checkWeightGradients[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex]; printf("Check Δ Weight[%i][%i][%i] = %lf\n", endLayerIndex, endNeuronIndex, startNeuronIndex, checkWeightDelta); } } } } #endif /** * @param model The model which the parameter gradients will be based on. * @param layerIndex The layer index whose weight deltas are being calculated. * @param baseDelta The base delta, equal to change in the cost function over change in * the weighted sum of the neuron value. * @param weightGradients The weight gradient to fill. * @param biasGradients The bias gradient to fill. */ void updateParameterGradients(struct Model *model, const double* targetOutput, double** weightGradients[], double* biasGradients[]) { int outputNeuronCount = model-&gt;neuronsPerLayer[OUTPUT_LAYER]; // Entry indexed by [layerIndex][neuronIndex] gives // Δ C / Δ Z[layerIndex, neuronIndex] double* errors[NUMBER_OF_LAYERS]; errors[OUTPUT_LAYER] = malloc(sizeof(double) * outputNeuronCount); // Fill errors of output layers for (int outputNeuronIndex = 0; outputNeuronIndex &lt; outputNeuronCount; outputNeuronIndex++) { double outputNeuronValue = model-&gt;values[OUTPUT_LAYER][outputNeuronIndex]; double targetOutputNeuronValue = targetOutput[outputNeuronIndex]; // Δ C_outputNeuronIndex / Δ A[OUTPUT_LAYER][outputNeuronIndex] double firstErrorComponent = model-&gt;getCostDerivative(outputNeuronValue, targetOutputNeuronValue); // Δ A[OUTPUT_LAYER][outputNeuronIndex] / Δ Z[OUTPUT_LAYER][outputNeuronIndex] double secondErrorComponent = model-&gt;getActivation(outputNeuronValue); // Δ C_outputNeuronIndex / Δ Z[OUTPUT_LAYER][outputNeuronIndex] double error = firstErrorComponent * secondErrorComponent; errors[OUTPUT_LAYER][outputNeuronIndex] = error; } // Fill errors of non-output layers for (int endLayerIndex = OUTPUT_LAYER; endLayerIndex &gt; INPUT_LAYER; endLayerIndex--) { int startLayerIndex = endLayerIndex - 1; int offsetEndLayerIndex = offsetLayer(endLayerIndex); int startNeuronsCount = model-&gt;neuronsPerLayer[startLayerIndex]; int endNeuronsCount = model-&gt;neuronsPerLayer[endLayerIndex]; errors[startLayerIndex] = malloc(sizeof(double) * startNeuronsCount); for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronsCount; startNeuronIndex++) { double error = 0.0; for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronsCount; endNeuronIndex++) { double nextError = errors[endLayerIndex][endNeuronIndex]; double nextWeight = model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex]; double activationValue = model-&gt;values[startLayerIndex][startNeuronIndex]; double activationValueDelta = model-&gt;getActivationChange(activationValue); double errorInfluence = nextWeight * nextError * activationValueDelta; error += errorInfluence; } // Take average of errors, not sum error /= endNeuronsCount; errors[startLayerIndex][startNeuronIndex] = error; } } // Update weights and biases of all layers based on errors for (int endLayerIndex = OUTPUT_LAYER; endLayerIndex &gt; INPUT_LAYER; endLayerIndex--) { int offsetEndLaterIndex = offsetLayer(endLayerIndex); int startLayerIndex = endLayerIndex - 1; int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[startLayerIndex]; for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { double errorOfEndNeuronOfWeight = errors[endLayerIndex][endNeuronIndex]; double valueOfStartNeuron = model-&gt;values[startLayerIndex][startNeuronIndex]; double biasGradientInfluence = errorOfEndNeuronOfWeight; double weightGradientInfluence = errorOfEndNeuronOfWeight * valueOfStartNeuron; biasGradientInfluence *= model-&gt;learningRate; weightGradientInfluence *= model-&gt;learningRate; weightGradients[offsetEndLaterIndex][endNeuronIndex][startNeuronIndex] += weightGradientInfluence; biasGradients[offsetEndLaterIndex][endNeuronIndex] += biasGradientInfluence; } } } } /** * Updates the weight and bias values within {@code model}, given the gradients of the cost function * with respect to the weights and biases. * * @param model * @param weightGradients * @param biasGradients */ void updateParameterValues(struct Model *model, double** weightGradients[], double* biasGradients[]) { for (int endLayerIndex = 1; endLayerIndex &lt; NUMBER_OF_LAYERS; endLayerIndex++) { int offsetEndLayerIndex = offsetLayer(endLayerIndex); int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex - 1]; for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { double biasDelta = biasGradients[offsetEndLayerIndex][endNeuronIndex]; // update bias model-&gt;biases[offsetEndLayerIndex][endNeuronIndex] -= biasDelta; #if PRINT_BIAS_UPDATE printf("Δ Bias[%i][%i] = %lf\n", endLayerIndex, endNeuronIndex, -biasDelta); printf("Bias[%i][%i] = %lf\n", endLayerIndex, endNeuronIndex, model-&gt;biases[offsetEndLayerIndex][endNeuronIndex]); #endif for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { double weightDelta = weightGradients[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex]; // update weight model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex] -= weightDelta; #if PRINT_WEIGHT_UPDATE printf("Δ Weight[%i][%i][%i] = %lf\n", endLayerIndex, endNeuronIndex, startNeuronIndex, weightDelta); printf("Weight[%i][%i][%i] = %lf\n", endLayerIndex, endNeuronIndex, startNeuronIndex, model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex]); #endif } } } } static int epochIndex = 0; /** * Allocates memory for the weight and bias gradients. * * @param model * @param weightGradients * @param biasGradients */ void initParameterGradients(struct Model* model, double** weightGradients[], double** biasGradients) { for (int layerIndex = 1; layerIndex &lt; NUMBER_OF_LAYERS; layerIndex++) { int offsetLayerIndex = offsetLayer(layerIndex); int endNeuronCount = model-&gt;neuronsPerLayer[layerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[layerIndex - 1]; biasGradients[offsetLayerIndex] = malloc(sizeof(double) * endNeuronCount); weightGradients[offsetLayerIndex] = malloc(sizeof(double*) * endNeuronCount); for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { biasGradients[offsetLayerIndex][endNeuronIndex] = 0.0; // 1 1 weightGradients[offsetLayerIndex][endNeuronIndex] = malloc(sizeof(double) * startNeuronCount); for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) weightGradients[offsetLayerIndex][endNeuronIndex][startNeuronIndex] = 0.0; } } } /** * Feeds the input values of the entry into the input array given. * * @param input * @param entry * @param inputColumnIndices * @param inputColumnIndicesCount */ void initInput(double input[], const double entry[], const int inputColumnIndices[], int inputColumnIndicesCount) { for (int inputColumnIndex = 0; inputColumnIndex &lt; inputColumnIndicesCount; inputColumnIndex++) { int inputColumn = inputColumnIndices[inputColumnIndex]; input[inputColumnIndex] = entry[inputColumn]; } } /** * Feeds the target output values of entry given into the target output array given. * * @param targetOutput * @param entry * @param outputColumnIndices * @param outputColumnIndicesCount */ void initTargetOutput(double targetOutput[], const double entry[], const int outputColumnIndices[], int outputColumnIndicesCount) { printf("Entry Input %lf Entry Output %lf\n", entry[0], entry[1]); for (int outputColumnIndex = 0; outputColumnIndex &lt; outputColumnIndicesCount; outputColumnIndex++) { int outputColumn = outputColumnIndices[outputColumnIndex]; targetOutput[outputColumnIndex] = entry[outputColumn]; } } /** * Tests how well {@code model} fits {@code data}, placing the results into {@code predictedOutputs} and {@costs}. * * @param model * @param data * @param inputColumnIndices * @param outputColumnIndices * @param predictedOutputs * @param costs */ void test(struct Model* model, struct Data* data, int inputColumnIndices[], int outputColumnIndices[], double* predictedOutputs[], double costs[]) { int inputNeuronCount = model-&gt;neuronsPerLayer[INPUT_LAYER]; int outputNeuronCount = model-&gt;neuronsPerLayer[OUTPUT_LAYER]; for (int entryIndex = 0; entryIndex &lt; data-&gt;numberOfEntries; entryIndex++) { double *entry = data-&gt;elements[entryIndex]; double input[inputNeuronCount]; double targetOutput[outputNeuronCount]; initInput(input, entry, inputColumnIndices, inputNeuronCount); initTargetOutput(targetOutput, entry, outputColumnIndices, outputNeuronCount); // forward propagation propagateInputForward(model, input); double cost = 0.0; for (int outputIndex = 0; outputIndex &lt; outputNeuronCount; outputIndex++) { double value = model-&gt;values[OUTPUT_LAYER][outputIndex]; predictedOutputs[entryIndex][outputIndex] = value; double targetValue = targetOutput[outputIndex]; cost += model-&gt;getCost(value, targetValue); } // Take average cost cost /= outputNeuronCount; costs[entryIndex] = cost; } } /** * Trains the model on the given data. * * @param model * @param data Container for the data the model will be trained on. * @param inputColumnIndices The indices of the columns within {@code data} that are the input columns. * @param outputColumnIndices The indices of the columns within {@code data} that are the output columns. */ void train(struct Model* model, struct Data* data, int inputColumnIndices[], int outputColumnIndices[]) { // [offsetLayerIndex][endNeuronIndex in layerIndex][startNeuronIndex in layerIndex - 1] double** weightGradients[NUMBER_OF_LAYERS - 1]; // [offsetLayerIndex][endNeuronIndex] double* biasGradients[NUMBER_OF_LAYERS - 1]; // Allocate the storage for the weight and bias deltas, in addition // to initializing them all weight and bias deltas with values of 0 initParameterGradients(model, weightGradients, biasGradients); #if GRADIENT_CHECKING // indexed same way as weightGradients and biasGradients double** checkWeightGradients[NUMBER_OF_LAYERS - 1]; double* checkBiasGradients[NUMBER_OF_LAYERS - 1]; initCheckParameterGradients(model, checkWeightGradients, checkBiasGradients); #endif int inputNeuronCount = model-&gt;neuronsPerLayer[INPUT_LAYER]; int outputNeuronCount = model-&gt;neuronsPerLayer[OUTPUT_LAYER]; epochIndex++; // Feed each input into model for (int entryIndex = 0; entryIndex &lt; data-&gt;numberOfEntries; entryIndex++) { double* entry = data-&gt;elements[entryIndex]; double input[inputNeuronCount]; double targetOutput[outputNeuronCount]; // Feed values of entry into input and targetOutput given indices of input and output columns initInput(input, entry, inputColumnIndices, inputNeuronCount); initTargetOutput(targetOutput, entry, outputColumnIndices, outputNeuronCount); // forward propagation propagateInputForward(model, input); #if PRINT_EPOCH_UPDATE double cost = 0.0; for (int outputIndex = 0; outputIndex &lt; outputNeuronCount; outputIndex++) { double value = model-&gt;values[OUTPUT_LAYER][outputIndex]; double targetValue = targetOutput[outputIndex]; cost += model-&gt;getCost(value, targetValue); } printf("Epoch %i, Entry %i, Total Cost %lf, \t\tCost %lf\n", epochIndex, entryIndex, cost, cost / outputNeuronCount); #endif // update weight and bias gradients based on this entry, part of the batch updateParameterGradients(model, targetOutput, weightGradients, biasGradients); #if GRADIENT_CHECKING updateCheckParameterGradients(model, input, targetOutput, checkWeightGradients, checkBiasGradients); #endif } // now that updateParameterValues(model, checkWeightGradients, checkBiasGradients); #if GRADIENT_CHECKING printCheckParamterGradients(model, checkWeightGradients, checkBiasGradients); #endif // free the memory taken by weight and bias gradients for (int layerIndex = 1; layerIndex &lt; NUMBER_OF_LAYERS; layerIndex++) { int offsetLayerIndex = offsetLayer(layerIndex); int neuronCount = model-&gt;neuronsPerLayer[layerIndex]; free(biasGradients[offsetLayerIndex]); for (int neuronIndex = 0; neuronIndex &lt; neuronCount; neuronIndex++) free(weightGradients[offsetLayerIndex][neuronIndex]); } } /** * Allocates the memory for the parameters (weights and biases) of the model, in addition to initializing * them to their default values. * * @param model */ void initParameters(struct Model* model) { // initialize weights with arbitrary for (int endLayerIndex = 1; endLayerIndex &lt; NUMBER_OF_LAYERS; endLayerIndex++) { int offsetEndLayerIndex = offsetLayer(endLayerIndex); int endNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex]; int startNeuronCount = model-&gt;neuronsPerLayer[endLayerIndex - 1]; model-&gt;weights[offsetEndLayerIndex] = malloc(sizeof(double*) * endNeuronCount); for (int endNeuronIndex = 0; endNeuronIndex &lt; endNeuronCount; endNeuronIndex++) { model-&gt;weights[offsetEndLayerIndex][endNeuronIndex] = malloc(sizeof(double) * startNeuronCount); model-&gt;biases[offsetEndLayerIndex] = malloc(sizeof(double) * endNeuronCount); for (int startNeuronIndex = 0; startNeuronIndex &lt; startNeuronCount; startNeuronIndex++) { model-&gt;weights[offsetEndLayerIndex][endNeuronIndex][startNeuronIndex] = model-&gt;getInitialWeightValue(startNeuronCount, endNeuronCount); model-&gt;biases[offsetEndLayerIndex][endNeuronIndex] = model-&gt;getInitialBiasValue(startNeuronCount, endNeuronCount); } } } } /** * Allocayes the memory for the values of the model. * * @param model */ void initValues(struct Model* model) { for (int layerIndex = 0; layerIndex &lt; NUMBER_OF_LAYERS; layerIndex++) { int neuronsInLayer = model-&gt;neuronsPerLayer[layerIndex]; model-&gt;values[layerIndex] = malloc(sizeof(double) * neuronsInLayer); } } </code></pre> <p>I won't show <strong>data.c/h</strong> since it is irrelevant to the network itself (just loads data from CSV). Trust that <code>initInput</code> and <code>initOutput</code>, given an entry from this data, population a conventional input and output array as one would expect.</p> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;zconf.h&gt; #include "model.h" #include "functions.h" #include "data.h" #define EPOCH_COUNT 100 #define NUMBER_OF_COLUMNS 3 #define TRAIN_ENTRIES_SIZE 4 #define TEST_ENTRIES_SIZE 4 #define PRINT_TEST_RESULTS true int main() { struct Model model = { .neuronsPerLayer = {2, 5, 1}, .learningRate = 0.2, // Default values .getActivation = getDefaultActivation, .getActivationChange = getDefaultActivationDerivative, .getCost = getDefaultCost, .getCostDerivative = getDefaultCostDerivative, .activationFunctionDerivativeUsesOutput = true, .getInitialWeightValue = getDefaultInitialWeightValue, .getInitialBiasValue = getDefaultInitialBiasValue, }; int numberOfInputs = model.neuronsPerLayer[INPUT_LAYER]; int numberOfOutputs = model.neuronsPerLayer[OUTPUT_LAYER]; // Change working directory so data can be referenced relative to parent data folder chdir(".."); chdir("data"); struct Data trainData; fill(&amp;trainData, "xor/train.csv", NUMBER_OF_COLUMNS, TRAIN_ENTRIES_SIZE); struct Data testData; fill(&amp;testData, "xor/test.csv", NUMBER_OF_COLUMNS, TEST_ENTRIES_SIZE); int inputColumnIndices[numberOfInputs]; int outputColumnIndices[numberOfOutputs]; inputColumnIndices[0] = 0; inputColumnIndices[1] = 1; outputColumnIndices[0] = 2; initValues(&amp;model); initParameters(&amp;model); for (int epochIndex = 0; epochIndex &lt; EPOCH_COUNT; epochIndex++) train(&amp;model, &amp;trainData, inputColumnIndices, outputColumnIndices); // Testing double* predictedOutputs[TEST_ENTRIES_SIZE]; for (int predictedOutputIndex = 0; predictedOutputIndex &lt; TEST_ENTRIES_SIZE; predictedOutputIndex++) predictedOutputs[predictedOutputIndex] = malloc(sizeof(double) * numberOfOutputs); double costs[TEST_ENTRIES_SIZE]; test(&amp;model, &amp;testData, inputColumnIndices, outputColumnIndices, predictedOutputs, costs); for (int entryIndex = 0; entryIndex &lt; TEST_ENTRIES_SIZE; entryIndex++) { double* entry = testData.elements[entryIndex]; double inputs[numberOfInputs]; double targetOutputs[numberOfOutputs]; initInput(inputs, entry, inputColumnIndices, numberOfInputs); initTargetOutput(targetOutputs, entry, outputColumnIndices, numberOfOutputs); #if PRINT_TEST_RESULTS printf("Inputs ="); for (int inputIndex = 0; inputIndex &lt; numberOfInputs; inputIndex++) { double input = inputs[inputIndex]; printf(" %lf", input); } printf(", Target Outputs ="); for (int outputIndex = 0; outputIndex &lt; numberOfOutputs; outputIndex++) { double targetOutput = targetOutputs[outputIndex]; printf(" %lf", targetOutput); } printf(", Predicted Outputs ="); for (int outputIndex = 0; outputIndex &lt; numberOfOutputs; outputIndex++) { double predictedOutput = predictedOutputs[entryIndex][outputIndex]; printf(" %lf", predictedOutput); } printf(".\n"); #endif } exit(0); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T17:40:30.510", "Id": "197168", "Score": "2", "Tags": [ "algorithm", "c", "machine-learning", "neural-network" ], "Title": "Neural Network Backpropagation" }
197168
<p>I have written a double linked list in Scala. The list should be fixed in size and items are always added to the head. if the list reaches max size then the tail is dropped.</p> <p>This is my code. I want to review this for brevity and functional approach.</p> <pre><code>sealed trait List { var prev : List var next : List } case object Empty extends List { var prev : List = Empty var next : List = Empty } case class Node(v: Int, p: List, n: List) extends List { var prev = p var next = n } class DoubleLinkedList(maxSize: Int) { private var head : List = Empty private var tail : List = Empty private var currentSize = 0 def print() : Unit = { var temp = head while(temp != Empty) { temp match { case Empty =&gt; println("Empty") case Node(v, _, _) =&gt; println(v) } temp = temp.next } } def add(i: Int) : List = { if (head == Empty || tail == Empty) { val n = new Node(i: Int, Empty, Empty) head = n tail = n currentSize += 1 Empty } else { val n = new Node(i, null, head) head.prev = n head = n currentSize += 1 if (currentSize &gt; maxSize) { val retVal = tail tail = tail.prev tail.next = Empty currentSize -= 1 retVal } else Empty } } } </code></pre>
[]
[ { "body": "<p>A few things I've noticed.</p>\n\n<pre><code>while(temp != Empty) {\n temp match {\n case Empty =&gt; println(\"Empty\")\n . . .\n</code></pre>\n\n<p>That will never print <code>\"Empty\"</code>.</p>\n\n<pre><code>case object Empty extends List {\n var prev : List = Empty\n var next : Lis...
{ "AcceptedAnswerId": "197839", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T18:12:46.287", "Id": "197172", "Score": "1", "Tags": [ "linked-list", "scala" ], "Title": "Fixed size double linked list in Scala" }
197172
<p>I am a mathematician attempting to become proficient with C++. At the moment I am learning about data structures. I am now writing a stack data structure using linked list from scratch.</p> <p>I have tested my class that I wrote and everything seems to be working fine but I want to see if there are any bugs or some areas of the code I could improve on.</p> <p>Here is the class:</p> <pre><code> #ifndef Stack_h #define Stack_h template &lt;class T&gt; class Stack { private: struct Node { T data; Node* next; }; Node* top; public: // Constructors Stack() : top(nullptr){} // empty constructor Stack(Stack const&amp; value); // copy constructor Stack&lt;T&gt;(Stack&lt;T&gt;&amp;&amp; move) noexcept; // move constuctor Stack&lt;T&gt;&amp; operator=(Stack&amp;&amp; move) noexcept; // move assignment operator ~Stack(); // destructor // Overload operators Stack&amp; operator=(Stack const&amp; rhs); friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, Stack&lt;T&gt; const&amp; data) { data.show(str); return str; } // Member functions void swap(Stack&amp; other) noexcept; bool isEmpty(); int getSize(); void push(const T&amp; theData); void push(T&amp;&amp; theData); void pop(); void show(std::ostream &amp;str) const; }; template &lt;class T&gt; Stack&lt;T&gt;::Stack(Stack const&amp; value) : top(nullptr) { for(Node* loop = value-&gt;data; loop != nullptr; loop = loop-&gt;next) { push(loop-&gt;data); } } template &lt;class T&gt; Stack&lt;T&gt;::Stack(Stack&lt;T&gt;&amp;&amp; move) noexcept : top(nullptr) { move.swap(*this); } template &lt;class T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::operator=(Stack&lt;T&gt; &amp;&amp;move) noexcept { move.swap(*this); return *this; } template &lt;class T&gt; Stack&lt;T&gt;::~Stack() { while(top != nullptr) { pop(); } } template &lt;class T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::operator=(Stack const&amp; rhs) { Stack copy(rhs); swap(copy); return *this; } template &lt;class T&gt; void Stack&lt;T&gt;::swap(Stack&lt;T&gt; &amp;other) noexcept { using std::swap; swap(top,other.top); } template &lt;class T&gt; bool Stack&lt;T&gt;::isEmpty() { if(top == nullptr) { return true; } else { return false; } } template &lt;class T&gt; int Stack&lt;T&gt;::getSize() { int size = 0; Node* current = top; while(current != nullptr) { size++; current = current-&gt;next; } return size; } template &lt;class T&gt; void Stack&lt;T&gt;::push(const T &amp;theData) { Node* newNode = new Node; newNode-&gt;data = theData; newNode-&gt;next = nullptr; if(top != nullptr) { newNode-&gt;next = top; } top = newNode; } template &lt;class T&gt; void Stack&lt;T&gt;::push(T&amp;&amp; theData) { Node* newNode = new Node; newNode-&gt;data = std::move(theData); newNode-&gt;next = nullptr; if(top != nullptr) { newNode-&gt;next = top; } top = newNode; } template &lt;class T&gt; void Stack&lt;T&gt;::pop() { Node* temp; if(top == nullptr) { throw std::invalid_argument("The list is already empty, nothing to pop."); } temp = top; top = top-&gt;next; delete temp; } template &lt;class T&gt; void Stack&lt;T&gt;::show(std::ostream &amp;str) const { for(Node* loop = top; loop != nullptr; loop = loop-&gt;next) { str &lt;&lt; loop-&gt;data &lt;&lt; "\t"; } str &lt;&lt; "\n"; } #endif /* Stack_h */ </code></pre> <p>Here is the main.cpp file that tests the class:</p> <pre><code>#include &lt;iostream&gt; #include "Stack.h" int main(int argc, const char * argv[]) { /////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// Stack Using Linked List ////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// Stack&lt;int&gt; obj; obj.push(2); obj.push(4); obj.push(6); obj.push(8); obj.push(10); std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Displaying Stack Contents---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Pop Stack Element -------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop(); std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Get the size of stack -------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.getSize() &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Re-Add Poped Element---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.push(10); std::cout &lt;&lt; obj &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T19:09:06.750", "Id": "379924", "Score": "0", "body": "Currently the implementations of `Stack operator=(const Stack&)` and `Stack<T>::swap` are missing. Also there is no way to access any data in the stack from outside (not even the...
[ { "body": "<h1>General stuff</h1>\n\n<ul>\n<li>In the copy constructor, the implementation starts to iterate over all the nodes, starting from <code>value-&gt;data</code>. I guess this is meant to be <code>value.top</code>.</li>\n<li>Still in the copy constructor, it pushes the values in reverse order (traversa...
{ "AcceptedAnswerId": "197180", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-24T18:55:44.443", "Id": "197174", "Score": "4", "Tags": [ "c++", "stack" ], "Title": "Generic Stack Data Structure Using Linked Lists" }
197174
<p>The scenario is the following: There is a list of persons and places where those persons visit. Each person is connected to a single or multiple places. See the picture below, where <strong>O[i]</strong> represents objects (persons) and <strong>P[i]</strong> places, respectively.</p> <p>I need to get the list of places connected by those persons.</p> <p><a href="https://i.stack.imgur.com/Xom5v.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xom5v.jpg" alt="Here **O** represents objects (persons) and **P** places, respectively"></a></p> <p><strong>Codes:</strong></p> <pre><code>class Program { static void Main(string[] args) { var Connections = new List&lt;Tuple&lt;string, List&lt;string&gt;&gt;&gt;() { new Tuple&lt;string, List&lt;string&gt;&gt;("O1", new List&lt;string&gt;(){ "P1", "P2" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O2", new List&lt;string&gt;(){ "P2", "P3", "P4" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O3", new List&lt;string&gt;(){ "P8" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O4", new List&lt;string&gt;(){ "P5", "P11" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O5", new List&lt;string&gt;(){ "P2", "P3" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O6", new List&lt;string&gt;(){ "P4"}), new Tuple&lt;string, List&lt;string&gt;&gt;("O7", new List&lt;string&gt;(){ "P7", "P10" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O8", new List&lt;string&gt;(){ "P5", "P6", "P7", "P12" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O9", new List&lt;string&gt;(){ "P7", "P11" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O10", new List&lt;string&gt;(){ "P13" }), new Tuple&lt;string, List&lt;string&gt;&gt;("O11", new List&lt;string&gt;(){ "P8", "P9" }), }; var Clusters = Connections.Select(x =&gt; x.Item2).ToList(); bool proceed = true; do { var pairs = Clusters.SelectMany(x =&gt; Clusters, (x, y) =&gt; Tuple.Create(x, y)).Where(x =&gt; x.Item1 != x.Item2); proceed = false; foreach (var pair in pairs) { var cluster1 = pair.Item1; var cluster2 = pair.Item2; if (cluster1.Intersect(cluster2).Any()) { cluster1.AddRange(cluster2.Where(x =&gt; !cluster1.Contains(x))); Clusters.Remove(cluster2); proceed = true; break; } } } while (proceed); foreach (var cluster in Clusters.OrderByDescending(x =&gt; x.Count())) { Console.WriteLine(cluster.OrderBy(x =&gt; x).Aggregate((i, j) =&gt; i + ", " + j)); } Console.Read(); } } </code></pre> <p><strong>Output:</strong></p> <pre><code>P10, P11, P12, P5, P6, P7 P1, P2, P3, P4 P8, P9 P13 </code></pre> <p><strong>Questions:</strong></p> <ul> <li><p>Is this optimal way to solve the given problem for larger data?</p></li> <li><p>How can I estimate the computational complexity of those operations?</p></li> <li><p>Am I doing here something potentially dangerous or excessive with the collections?</p></li> <li><p>Any other concerns or remarks?</p></li> </ul> <p>Any feedback would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T10:54:03.060", "Id": "380697", "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>Look good to me.</p>\n\n<p>Not sure it matters but you are creating all pairs. (A,B) and (B,A). If you only created unique combinations you would cut the count in 1/2.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "Creatio...
{ "AcceptedAnswerId": "197223", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T00:03:26.287", "Id": "197189", "Score": "8", "Tags": [ "c#", "performance", "linq", "collections" ], "Title": "Build clusters from connections (virus propagation)" }
197189
<p>I've implemented countdown timer control with arc animation that looks like this</p> <p><a href="https://i.stack.imgur.com/ck2qC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ck2qC.png" alt="countdown control"></a></p> <hr> <p>Implementation notes:</p> <ul> <li><p>For arc visualization I've created class <code>Arc</code> derived from <code>Shape</code> (code is based on this <a href="https://stackoverflow.com/a/16669648/1548895">post</a>).</p></li> <li><p>I've created <code>Countdown</code> control (derived from <code>UserControl</code>). For setting timeout I've added <code>Seconds</code> dependency property. I'm using binding <code>Content="{Binding Seconds}"</code> to display seconds. Animation duration is set in code behind</p> <pre><code>Animation.Duration = new Duration(TimeSpan.FromSeconds(Seconds)); </code></pre> <p>because I'm not sure if it's possible to do it in XAML without writing custom converter. I think that creating custom converter is not justified here.</p></li> <li><p>For control's scaling content is wrapped in <code>Viewbox</code> сontrol.</p></li> <li><p>For seconds animation I'm using <code>DispatcherTimer</code>, nothing special. Is it the best to go here?</p></li> </ul> <hr> <h2>Code</h2> <p><code>Arc.cs</code></p> <pre><code>public class Arc : Shape { public Point Center { get =&gt; (Point)GetValue(CenterProperty); set =&gt; SetValue(CenterProperty, value); } // Using a DependencyProperty as the backing store for Center. This enables animation, styling, binding, etc... public static readonly DependencyProperty CenterProperty = DependencyProperty.Register("Center", typeof(Point), typeof(Arc), new FrameworkPropertyMetadata(new Point(), FrameworkPropertyMetadataOptions.AffectsRender)); // Start angle in degrees public double StartAngle { get =&gt; (double)GetValue(StartAngleProperty); set =&gt; SetValue(StartAngleProperty, value); } // Using a DependencyProperty as the backing store for StartAngle. This enables animation, styling, binding, etc... public static readonly DependencyProperty StartAngleProperty = DependencyProperty.Register("StartAngle", typeof(double), typeof(Arc), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsRender)); // End angle in degrees public double EndAngle { get =&gt; (double)GetValue(EndAngleProperty); set =&gt; SetValue(EndAngleProperty, value); } // Using a DependencyProperty as the backing store for EndAngle. This enables animation, styling, binding, etc... public static readonly DependencyProperty EndAngleProperty = DependencyProperty.Register("EndAngle", typeof(double), typeof(Arc), new FrameworkPropertyMetadata(90.0, FrameworkPropertyMetadataOptions.AffectsRender)); public double Radius { get =&gt; (double)GetValue(RadiusProperty); set =&gt; SetValue(RadiusProperty, value); } // Using a DependencyProperty as the backing store for Radius. This enables animation, styling, binding, etc... public static readonly DependencyProperty RadiusProperty = DependencyProperty.Register("Radius", typeof(double), typeof(Arc), new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender)); public bool SmallAngle { get =&gt; (bool)GetValue(SmallAngleProperty); set =&gt; SetValue(SmallAngleProperty, value); } // Using a DependencyProperty as the backing store for SmallAngle. This enables animation, styling, binding, etc... public static readonly DependencyProperty SmallAngleProperty = DependencyProperty.Register("SmallAngle", typeof(bool), typeof(Arc), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)); static Arc() =&gt; DefaultStyleKeyProperty.OverrideMetadata(typeof(Arc), new FrameworkPropertyMetadata(typeof(Arc))); protected override Geometry DefiningGeometry { get { double startAngleRadians = StartAngle * Math.PI / 180; double endAngleRadians = EndAngle * Math.PI / 180; double a0 = StartAngle &lt; 0 ? startAngleRadians + 2 * Math.PI : startAngleRadians; double a1 = EndAngle &lt; 0 ? endAngleRadians + 2 * Math.PI : endAngleRadians; if (a1 &lt; a0) a1 += Math.PI * 2; SweepDirection d = SweepDirection.Counterclockwise; bool large; if (SmallAngle) { large = false; double t = a1; d = (a1 - a0) &gt; Math.PI ? SweepDirection.Counterclockwise : SweepDirection.Clockwise; } else large = (Math.Abs(a1 - a0) &lt; Math.PI); Point p0 = Center + new Vector(Math.Cos(a0), Math.Sin(a0)) * Radius; Point p1 = Center + new Vector(Math.Cos(a1), Math.Sin(a1)) * Radius; List&lt;PathSegment&gt; segments = new List&lt;PathSegment&gt; { new ArcSegment(p1, new Size(Radius, Radius), 0.0, large, d, true) }; List&lt;PathFigure&gt; figures = new List&lt;PathFigure&gt; { new PathFigure(p0, segments, true) { IsClosed = false } }; return new PathGeometry(figures, FillRule.EvenOdd, null); } } } </code></pre> <p><code>Countdown.xaml</code></p> <pre><code>&lt;UserControl x:Class="WpfApp3.Countdown" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApp" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="450" Loaded="UserControl_Loaded"&gt; &lt;UserControl.Triggers&gt; &lt;EventTrigger RoutedEvent="UserControl.Loaded"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Name="Animation" Storyboard.TargetName="Arc" Storyboard.TargetProperty="EndAngle" From="-90" To="270" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/UserControl.Triggers&gt; &lt;Viewbox&gt; &lt;Grid Width="100" Height="100"&gt; &lt;Border Background="#222" Margin="5" CornerRadius="50"&gt; &lt;StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"&gt; &lt;Label Foreground="#fff" Content="{Binding Seconds}" FontSize="50" Margin="0, -10, 0, 0" /&gt; &lt;Label Foreground="#fff" Content="sec" HorizontalAlignment="Center" Margin="0, -20, 0, 0" /&gt; &lt;/StackPanel&gt; &lt;/Border&gt; &lt;local:Arc x:Name="Arc" Center="50, 50" StartAngle="-90" EndAngle="-90" Stroke="#45d3be" StrokeThickness="5" Radius="45" /&gt; &lt;/Grid&gt; &lt;/Viewbox&gt; &lt;/UserControl&gt; </code></pre> <p><code>Countdown.xaml.cs</code></p> <pre><code>public partial class Countdown : UserControl { public int Seconds { get =&gt; (int)GetValue(SecondsProperty); set =&gt; SetValue(SecondsProperty, value); } public static readonly DependencyProperty SecondsProperty = DependencyProperty.Register(nameof(Seconds), typeof(int), typeof(Countdown), new PropertyMetadata(0)); private readonly DispatcherTimer _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; public Countdown() { InitializeComponent(); DataContext = this; } private void UserControl_Loaded(object sender, EventArgs e) { Animation.Duration = new Duration(TimeSpan.FromSeconds(Seconds)); if (Seconds &gt; 0) { _timer.Start(); _timer.Tick += Timer_Tick; } } private void Timer_Tick(object sender, EventArgs e) { Seconds--; if (Seconds == 0) _timer.Stop(); } } </code></pre> <p>Control is placed on <code>Window</code> like this</p> <pre><code>&lt;local:Countdown Width="300" Height="300" Seconds="25" /&gt; </code></pre>
[]
[ { "body": "<p>There are a couple of things which could be more consistent.</p>\n\n<blockquote>\n<pre><code> public static readonly DependencyProperty StartAngleProperty =\n DependencyProperty.Register(\"StartAngle\", typeof(double), typeof(Arc),\n new FrameworkPropertyMetadata(0.0, Framewor...
{ "AcceptedAnswerId": "197212", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T08:48:43.527", "Id": "197197", "Score": "11", "Tags": [ "c#", "animation", "wpf", "timer" ], "Title": "Countdown control with arc animation" }
197197
<p>I wrote a code for a quant finance job and they told me that, besides it worked, it was poorly written. I asked for a more detailed feedback but they did not send it to me. I paste it here with minimal info about it, so it will be difficult to connect it to the company.</p> <p>The scope of the code is to calculate <a href="https://www.khanacademy.org/economics-finance-domain/core-finance/derivative-securities/black-scholes/v/introduction-to-the-black-scholes-formula" rel="nofollow noreferrer">implied volatility</a> for options on two different underlyings (stocks, futures) with two different models (Black and Scholes and another one, for which they gave me some publications).</p> <p>They asked to write all the math functions <strong>from scratch and do not use third party libraries</strong>.</p> <p>What do you suggest in order to improve?</p> <pre><code>import csv from math import * def cdf_of_normal(x): #reference Paul Wilmott on Quantitative Finance a1 = 0.31938153 a2 = -0.356563782 a3 = 1.781477937 a4 = -1.821255978 a5 = 1.330274429 if x &gt;= 0.0: d = 1.0/(1.0+0.2316419*x) N_x = 1.0 - 1.0/sqrt(2.0*pi)*exp(-x**2/2.0)*(a1*d + a2*d**2 + a3*d**3 + a4*d**4 + a5*d**5) else: N_x = 1.0 - cdf_of_normal(-x) return(N_x) def pdf_of_normal(x): #No sigma, just for Bachelier. Thomson 2016 return( 1.0/sqrt(2*pi)*exp(-0.5*x**2) ) def brent_dekker(a,b,f,epsilon,N_step,N_corr): #reference https://en.wikipedia.org/wiki/Brent%27s_method if f(a)*f(b)&lt;0: if abs(f(a))&lt;abs(f(b)): return(brent_dekker(b,a,f,epsilon,N_step,N_corr)) else: i=0 c=a s=b mflag=True while(f(b)!=0.0 and f(s)!=0.0 and abs(b-a)&gt;=epsilon and i&lt;N_step): i=i+1 if (f(a)!=f(c) and f(b)!=f(c)): #inverse quadratic interpolation s=a*f(b)*f(c)/((f(a)-f(b))*(f(a)-f(c)))+b*f(a)*f(c)/((f(b)-f(a))*(f(b)-f(c)))+c*f(a)*f(b)/((f(c)-f(a))*(f(c)-f(b))) else: #secant method s=b-f(b)*(b-a)/(f(b)-f(a)) if((s&lt;(3.0*a+b)/4.0 or s&gt;b) or (mflag==True and abs(s-b)&gt;=abs(b-c)/2.0) or (mflag==False and abs(s-b)&gt;=abs(c-d)/2.0) or (mflag==True and abs(b-c)&lt;epsilon) or (mflag==False and abs(c-d)&lt;epsilon)): #bisection method s=(a+b)/2.0 mflag=True else: mflag=False d=c c=b if f(a)*f(s)&lt;0.0: b=s else: a=s if abs(f(a))&lt;abs(f(b)): aux=a a=b b=aux if i&gt;=N_step: #it did not converge, it never happened return(float('nan')) else: if(f(s)==0.0): return s else: return b else: #I try to automate it knowing that volatility will be between 0 and infinity # return 'error' if N_corr&gt;0: if a&gt;b: a=a*10.0 b=b/10.0 else: a=a/10.0 b=b*10.0 #print a,b,N_corr,f(a),f(b) #for debug N_corr = N_corr-1 return(brent_dekker(a,b,f,epsilon,N_step,N_corr)) else: return(float('nan')) #it happens. The problem is f(a) and f(b) remain constant. #ABSTRACT CLASS FOR A PRICING MODEL #I think these classes are useful if a person wants to play with implied volatility (iv) for a specific model with a diverse set of assets (call/put options on futures/stocks). In this way he can define a model, then update it and run the different methods. #I don't know exactly how a normal day working in finance is so it might not be the smartest way to do it. class pricing_model_iv(object): def __init__(self, z): self.z = z def update(self): raise NameError("Abstract Pricing Model") def iv_call_stock(self): raise NameError("Abstract Pricing Model") def iv_put_stock(self): raise NameError("Abstract Pricing Model") def iv_call_future(self): raise NameError("Abstract Pricing Model") def iv_put_future(self): raise NameError("Abstract Pricing Model") #BLACK &amp; SCHOLES PRICING MODEL class bl_sch_iv(pricing_model_iv): def __init__(self, V, S, E, time_to_exp, r, epsilon, nstep_conv): self.V = V #option price self.S = S #underlying price, either stock or future. self.E = E #strike price self.time_to_exp = time_to_exp #time to expiration self.r = r #risk-free interest rate self.epsilon = epsilon #precision self.nstep_conv = nstep_conv #maximum number of steps to convergence def update(self, V, S, E, time_to_exp, r, epsilon, nstep_conv): self.V = V #option price self.S = S #underlying price, either stock or future. self.E = E #strike price self.time_to_exp = time_to_exp #time to expiration self.r = r #risk-free interest rate self.epsilon = epsilon #precision self.nstep_conv = nstep_conv #maximum number of steps to convergence def iv_call_stock(self): #Black &amp; Scholes def price_tozero(sigma): d1=( log(self.S/self.E)+(self.r+sigma**2/2.0)*self.time_to_exp )/( sigma*sqrt(self.time_to_exp) ) d2=d1-sigma*sqrt(self.time_to_exp) return(self.S*cdf_of_normal(d1)-self.E*exp(-self.r*self.time_to_exp)*cdf_of_normal(d2)-self.V) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,10)) def iv_put_stock(self): #Black &amp; Scholes def price_tozero(sigma): d1=( log(self.S/self.E)+(self.r+sigma**2/2.0)*self.time_to_exp )/( sigma*sqrt(self.time_to_exp) ) d2=d1-sigma*sqrt(self.time_to_exp) return(-self.S*cdf_of_normal(-d1)+self.E*exp(-self.r*self.time_to_exp)*cdf_of_normal(-d2)-self.V) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) def iv_call_future(self): #Black &amp; Scholes + http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/node9.html def price_tozero(sigma): d1=( log(self.S/self.E)+(self.r+sigma**2/2.0)*self.time_to_exp )/( sigma*sqrt(self.time_to_exp) ) d2=d1-sigma*sqrt(self.time_to_exp) return((self.S*cdf_of_normal(d1)-self.E*cdf_of_normal(d2))*exp(-self.r*self.time_to_exp)-self.V) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) def iv_put_future(self): #Obtained using Put-Call Parity using the call future formula #In the put-call parity relation I should discount also S because we are considering a future contract def price_tozero(sigma): d1=( log(self.S/self.E)+(self.r+sigma**2/2.0)*self.time_to_exp )/( sigma*sqrt(self.time_to_exp) ) d2=d1-sigma*sqrt(self.time_to_exp) return((self.S*cdf_of_normal(d1)-self.E*cdf_of_normal(d2))*exp(-self.r*self.time_to_exp) + self.E*exp(-self.r*self.time_to_exp) - self.S*exp(-self.r*self.time_to_exp) -self.V) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) #BACHELIER PRICING MODEL class bachl_iv(pricing_model_iv): def __init__(self, V, S, E, time_to_exp, r, epsilon, nstep_conv): self.V = V #option price self.S = S #underlying price, either stock or future. self.E = E #strike price self.time_to_exp = time_to_exp #time to expiration self.r = r #risk-free interest rate self.epsilon = epsilon #precision self.nstep_conv = nstep_conv #maximum number of steps to convergence def update(self, V, S, E, time_to_exp, r, epsilon, nstep_conv): self.V = V #option price self.S = S #underlying price, either stock or future. self.E = E #strike price self.time_to_exp = time_to_exp #time to expiration self.r = r #risk-free interest rate self.epsilon = epsilon #precision self.nstep_conv = nstep_conv #maximum number of steps to convergence #Following 4.5.1 and 4.5.2 of Thomson 2016 #I converted the arithmetic compounding to continuous compounding, but not the normal to log-normal distribution of returns #I thought the distribution of the returns was an important part of the Bachelier model, while continuous compounding is related to the interest rate that is given in the data def iv_call_stock(self): #From Thomson 2016, Eq. 31c, paragraph 4.2.3 def price_tozero(sigma): d=(self.S - self.E*exp(-self.r*self.time_to_exp))/(self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)) return( (self.S - self.E*exp(-self.r*self.time_to_exp))*cdf_of_normal(d) + self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)*pdf_of_normal(d) - self.V ) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) def iv_put_stock(self): #From IV_CALL_STOCK method plus put-call parity (Paul Wilmott on Quantitative Finance, it is model independent.) =&gt; P = C + E*e^(-r*time_to_exp) - S def price_tozero(sigma): d=(self.S - self.E*exp(-self.r*self.time_to_exp))/(self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)) return( (self.S - self.E*exp(-self.r*self.time_to_exp))*cdf_of_normal(d) + self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)*pdf_of_normal(d) + self.E*exp(-self.r*self.time_to_exp) - self.S - self.V ) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) #For the options on futures, I tried to replicate the scheme I used in Black and Scholes of discounting S together with E. #This means that the first term of the price pass from: # (self.S - self.E*exp(-self.r*self.time_to_exp))*cdf_of_normal(d) #to: # (self.S - self.E)*exp(-self.r*self.time_to_exp)*cdf_of_normal(d) def iv_call_future(self): def price_tozero(sigma): d=(self.S - self.E*exp(-self.r*self.time_to_exp))/(self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)) return( (self.S - self.E)*exp(-self.r*self.time_to_exp)*cdf_of_normal(d) + self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)*pdf_of_normal(d) - self.V ) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) #In the put-call parity relation I should discount also S because we are considering a future contract def iv_put_future(self): def price_tozero(sigma): d=(self.S - self.E*exp(-self.r*self.time_to_exp))/(self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)) return( (self.S - self.E)*exp(-self.r*self.time_to_exp)*cdf_of_normal(d) + self.E*exp(-self.r*self.time_to_exp)*sigma*sqrt(self.time_to_exp)*pdf_of_normal(d) + self.E*exp(-self.r*self.time_to_exp) - self.S*exp(-self.r*self.time_to_exp) - self.V ) return(brent_dekker(1.0,99.0,price_tozero,self.epsilon,self.nstep_conv,3)) #NOW I START THE CODE blsc = bl_sch_iv(1,1,1,1,1,1,1) bach = bachl_iv(1,1,1,1,1,1,1) precision = 1.e-8 max_n = 10**6 #max number of steps to convergence for the Brent Dekker zero finding algorithm bad_ids=[] bad_ids_u_F=set() bad_ids_u_S=set() bad_ids_o_C=set() bad_ids_o_P=set() bad_ids_m_Ba=set() bad_ids_m_BS=set() ids_u_F=set() ids_u_S=set() ids_o_C=set() ids_o_P=set() ids_m_Ba=set() ids_m_BS=set() sick=set() with open('input.csv','rb') as csvfile, open('output.csv','wb') as csvout: has_header = csv.Sniffer().has_header(csvfile.read(10)) #I check the header existence with a little sample csvfile.seek(0) #rewind reading = csv.reader(csvfile, delimiter=',') writing = csv.writer(csvout, delimiter=',') writing.writerow(['ID','Spot','Strike','Risk-Free Rate','Years to Expiry','Option Type','Model Type','Implied Volatility','Market Price']) if has_header: next(reading) #skip header # I did this just in case the next time you give me a CSV without the header for row in reading: #print ', '.join(row) ID=row[0] underlying_type=row[1] underlying=float(row[2]) risk_free_rate=float(row[3])*(-1.) #all the interest rates are negative values (in the CSV file). I think the - sign is given for granted. It's usually a yearly interest rate days_to_expiry=float(row[4])/365.0 #Converting from days to expiry into years to expiry strike=float(row[5]) option_type=row[6] model_type=row[7] market_price=float(row[8]) if model_type=='BlackScholes': ids_m_BS.add(ID) else: ids_m_Ba.add(ID) if underlying_type=='Stock': ids_u_S.add(ID) else: ids_u_F.add(ID) if option_type=='Call': ids_o_C.add(ID) else: ids_o_P.add(ID) if model_type=='BlackScholes': blsc.update(market_price, underlying, strike, days_to_expiry, risk_free_rate, precision, max_n) if underlying_type=='Stock': if option_type=='Call': iv=blsc.iv_call_stock() else: iv=blsc.iv_put_stock() else: if option_type=='Call': iv=blsc.iv_call_future() else: iv=blsc.iv_put_future() else: bach.update(market_price, underlying, strike, days_to_expiry, risk_free_rate, precision, max_n) if underlying_type=='Stock': if option_type=='Call': iv=bach.iv_call_stock() else: iv=bach.iv_put_stock() else: if option_type=='Call': iv=bach.iv_call_future() else: iv=bach.iv_put_future() #Writing the csv file if underlying_type=='Stock': writing.writerow([row[0],row[2],row[5],row[3],str(days_to_expiry),row[6],row[7],str(iv),row[8]]) else:#Spot price for futures writing.writerow([row[0],str(underlying*exp(-risk_free_rate*days_to_expiry)),row[5],row[3],str(days_to_expiry),row[6],row[7],str(iv),row[8]]) #Count of nans if isnan(iv): bad_ids.append(ID) if model_type=='BlackScholes': bad_ids_m_BS.add(ID) else: bad_ids_m_Ba.add(ID) if underlying_type=='Stock': bad_ids_u_S.add(ID) else: bad_ids_u_F.add(ID) if option_type=='Call': bad_ids_o_C.add(ID) else: bad_ids_o_P.add(ID) #It returns how many options have NaN volatility. It also allows to study them print len(bad_ids), ' out of 65535 that is the ', len(bad_ids)/65535.0*100.0, '% \n' print 'BS-CALL-STOCK: ', len(bad_ids_m_BS &amp; bad_ids_u_S &amp; bad_ids_o_C)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_BS &amp; bad_ids_u_S &amp; bad_ids_o_C) print 'BS-PUT-STOCK: ', len(bad_ids_m_BS &amp; bad_ids_u_S &amp; bad_ids_o_P)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_BS &amp; bad_ids_u_S &amp; bad_ids_o_P) print 'BS-CALL-FUTURE: ', len(bad_ids_m_BS &amp; bad_ids_u_F &amp; bad_ids_o_C)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_BS &amp; bad_ids_u_F &amp; bad_ids_o_C) print 'BS-PUT-FUTURE: ', len(bad_ids_m_BS &amp; bad_ids_u_F &amp; bad_ids_o_P)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_BS &amp; bad_ids_u_F &amp; bad_ids_o_P) print 'Ba-CALL-STOCK: ', len(bad_ids_m_Ba &amp; bad_ids_u_S &amp; bad_ids_o_C)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_Ba &amp; bad_ids_u_S &amp; bad_ids_o_C) print 'Ba-PUT-STOCK: ', len(bad_ids_m_Ba &amp; bad_ids_u_S &amp; bad_ids_o_P)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_Ba &amp; bad_ids_u_S &amp; bad_ids_o_P) print 'Ba-CALL-FUTURE: ', len(bad_ids_m_Ba &amp; bad_ids_u_F &amp; bad_ids_o_C)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_Ba &amp; bad_ids_u_F &amp; bad_ids_o_C) print 'Ba-PUT-FUTURE: ', len(bad_ids_m_Ba &amp; bad_ids_u_F &amp; bad_ids_o_P)*100.0/len(bad_ids), '% real: ', len(bad_ids_m_Ba &amp; bad_ids_u_F &amp; bad_ids_o_P) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T08:46:41.453", "Id": "380010", "Score": "0", "body": "not a full answer but my immediate thought was that the mass of \"magic numbers\" makes the code impenetrable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate":...
[ { "body": "<ul>\n<li><p>Give the operators some breathing space. For example, the</p>\n\n<pre><code> s=a*f(b)*f(c)/((f(a)-f(b))*(f(a)-f(c)))+b*f(a)*f(c)/((f(b)-f(a))*(f(b)-f(c)))+c*f(a)*f(b)/((f(c)-f(a))*(f(c)-f(b)))\n</code></pre>\n\n<p>line is a textbook example of unreadable. Consider at least</p>\n\n<pre...
{ "AcceptedAnswerId": "197240", "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T08:27:22.003", "Id": "197198", "Score": "6", "Tags": [ "python", "python-2.x", "interview-questions", "finance" ], "Title": "Calculate implied volatility for options on stocks and futures with two models" }
197198
<p>I've written a script in python in combination with selenium to parse different information from a webpage and store the collected data in a csv file. The data are rightly coming through. The email portion looks weird cause I wrapped two conditions in a single line to grab all the leads (in case one missing, another will come into play) However, the way I've used csv writer doesn't look that good. I hope there is any better way of implementation of the logic I pursued below.</p> <p>This is the script:</p> <pre><code>import csv from selenium import webdriver from bs4 import BeautifulSoup urls = "https://www.krak.dk/byggefirmaer/p:{}/s%C3%B8g.cs?xcoord=90.3636094&amp;ycoord=23.8150673" def get_info(driver,urls): with open("output.csv","w",newline="") as infile: writer = csv.writer(infile) writer.writerow(["Name","Link","Email"]) for url in [urls.format(page) for page in range(1,3)]: driver.get(url) soup = BeautifulSoup(driver.page_source,'html.parser') for links in soup.select("article.vcard"): name = links.select_one(".hit-company-name-ellipsis a").get_text(strip=True) link = links.select_one(".hit-homepage-link").get("href") if links.select_one(".hit-homepage-link") else "" email = links.select_one(".hit-footer-wrapper span[data-mail]").get("data-mail") or links.select_one(".hit-footer-wrapper span[data-mail-e-contact-mail]").get("data-mail-e-contact-mail") print(f'{name}\n{link}\n{email}\n') writer.writerow([name,link,email]) if __name__ == '__main__': driver = webdriver.Chrome() try: get_info(driver,urls) finally: driver.quit() </code></pre> <p>Currently the above script traverses three pages and scrapes three fields <code>name</code>,<code>link</code>,<code>email</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T20:42:46.990", "Id": "380104", "Score": "0", "body": "There are small changes I would make (not related to messy usage of `links`), but in my experience has been web scraping can get very messy." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T10:33:12.940", "Id": "197201", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "selenium" ], "Title": "Grabbing information traversing multiple pages" }
197201
<p>I want to create page when user can use form to display filtered data in table. Form has to remember its own state, because after every refresh it shouldnt change.</p> <p>So after submitting form I should get:</p> <ul> <li>form values</li> <li>results from database based on what was checked in form</li> </ul> <p>Seems pretty easy. </p> <ul> <li><p><code>HistoryViewModel</code> thats all data I want to display to user</p></li> <li><p><code>HistorySearchResult</code> thats view model for table content</p></li> <li><p><code>HistorySearchCriteria</code> contains filtering options in form</p></li> <li><p><code>HistorySearchBusinessLogic.GetHistories(HistorySearchCriteria searchModel)</code> I am using this to get data from database but with filtering applied.</p></li> </ul> <p>At first I created my <code>ViewModel</code> which will holds data to display:</p> <pre><code>public class HistoryViewModel { // form's filtering options here public HistorySearchCriteria HistorySearchCriteria { get; set; } // results after filtering public List&lt;HistorySearchResult&gt; HistorySearchResults { get; set; } // entries amount (needed for pagination) public int AmountOfEntries { get; set; } // avaible actions to modify row's data. For example on particular page only `delete` and `edit` will be possible public List&lt;SiteEnums.GroupActionOptions&gt; GroupActions { get; set; } } </code></pre> <p>Now, let me give you a quick peek of <code>HistorySearchCriteria</code>. I am using this to get values from filtering form.</p> <pre><code>public class HistorySearchCriteria { [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] public DateTime? DateFrom { get; set; } [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] public DateTime? DateTo { get; set; } public int? AmountFrom { get; set; } public int? AmountTo { get; set; } public string Title { get; set; } public List&lt;SelectListItem&gt; Banks { get; set; } public string SelectedBankId { get; set; } public List&lt;SelectListItem&gt; Statuses { get; set; } public int? SelectedStatusId { get; set; } public SiteEnums.ShowOptions Display { get; set; } public int? SelectedDisplayId { get; set; } } </code></pre> <p>After making <code>POST</code> I am retreiving data from filtering form and using that data to fill another <code>ViewModel</code>:</p> <pre><code>[HttpPost] public ActionResult Index(HistoryViewModel searchViewModel, int page = 0, int resultsAmount = 100) { var logic = new HistorySearchBusinessLogic(); // get data based on filtering options var query = logic.GetHistories(searchViewModel.HistorySearchCriteria); // do some validation if (page &lt; 0) page = 0; if (resultsAmount &lt; 0) resultsAmount = 100; // get data amount var amount = query.Count(); // get ONLY important data var results = query. OrderBy(x =&gt; x.Id) .Skip(page * resultsAmount) .Take(resultsAmount) .Select(x =&gt; new HistorySearchResult { Amount = ((double)x.Amount / 100).ToString(), Bank = x.Bankaccount.BankShort.BankShortName, CustomerData = x.CustomerData, OperationDate = x.DateIncoming, SaveDate = x.DateExecutive, Title = x.Title }) .ToList(); // fill view model var viewModel = new HistoryViewModel() { HistorySearchCriteria = searchViewModel.HistorySearchCriteria, HistorySearchResults = results, GroupActions = new List&lt;SiteEnums.GroupActionOptions&gt;() }; // pass data with RPG design pattern TempData["viewModelFromPost"] = viewModel; return RedirectToAction("Index"); } </code></pre> <p>Now in <code>TempData["viewModelFromPost"]</code> I should have data which holds my filtering criteria, results etc.</p> <p>In <code>GET</code> I have 2 scenarions:</p> <ul> <li><code>TempData["viewModelFromPost"]</code> can be null, because thats my first request <code>TempData["viewModelFromPost"]</code> can contains data results, filtering criteria etc.</li> </ul> <p>Lets see whats inside <code>GET</code></p> <pre><code>[HttpGet] public ActionResult Index() { HistoryViewModel vm = new HistoryViewModel(); if (TempData["viewModelFromPost"] != null) { vm = TempData["viewModelFromPost"] as HistoryViewModel; } else { vm.HistorySearchCriteria = new HistorySearchCriteria() { DateFrom = DateTime.Now, DateTo = DateTime.Now, }; vm.HistorySearchResults = new List&lt;HistorySearchResult&gt;(); } vm.GroupActions = new List&lt;SiteEnums.GroupActionOptions&gt;(); vm.HistorySearchCriteria.Banks = _context.BankShortTypes.Select(x =&gt; new SelectListItem { Text = x.BankShortName, Value = x.Id.ToString() }).ToList(); vm.HistorySearchCriteria.Statuses = _context.StatusTypes.Select(x =&gt; new SelectListItem { Text = x.StatusName, Value = x.Id.ToString() }).ToList(); return View(vm); } </code></pre> <p>Well, its complicated a bit. I think controllers should be lighter. What do you think about that? I think that could be archived much, much easier. It starting to be very complicated in <code>GET</code>, because I have to remeber which <code>List</code> I have to initialie, which data I have to get from database etc.</p>
[]
[ { "body": "<p>I think that pipeline pattern for filtering in connection with GET request will be a good way to go.<br>\nSee details over here: <a href=\"https://www.codeproject.com/Articles/1094513/Pipeline-and-Filters-Pattern-using-Csharp\" rel=\"nofollow noreferrer\">Pipeline pattern for .Net</a></p>\n\n<p>Ju...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T13:13:59.397", "Id": "197207", "Score": "5", "Tags": [ "c#", "asp.net" ], "Title": "Proper way to display form with filtering in ASP.NET MVC 5" }
197207
<p>I have this code that I'm putting into a library script.</p> <p>The aim of the code is the following:</p> <ul> <li>The method is to connect to a remote server and run <code>uptime</code> on the remote server. The uptime will be displayed on the host machine, to see for how long the server has been running.</li> </ul> <p>The aim in a near future, is to uptime-check several servers and have the results of my program, on the running machine.</p> <p>I put the the method under a <code>main</code> to not run it when the library is imported.</p> <pre><code>from pexpect import pxssh import pexpect # conn_up is a function for connecting to a remote server and doing an uptime. def conn_up(): try: s = pxssh.pxssh() hostname = '192.168.1.32' username = 'pi' s.login(hostname, username,ssh_key='/home/miaou/priv_keys') s.sendline('uptime') # run a command s.prompt() # match the prompt print(s.before.decode()) # print everything before the prompt. except pxssh.ExceptionPxssh as e: print("pxssh failed on login.") print(e) if __name__ == '__main__': conn_up() </code></pre> <p>Currently I have only one method, <code>conn_up()</code>.</p> <p>But if I want to create additional methods to broaden the tools available for my administration, should I list them all of them under <code>__name__ == '__main__'</code> or is there a simpler way to call all the future methods all at once?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T16:18:23.957", "Id": "380065", "Score": "1", "body": "This is an awkward library. Why do these two pieces of functionality belong together in the same program or library? Also, the `conn_wr()` function looks like a hypothetical exam...
[ { "body": "<p>It sounds like the problem is not the code but how to package it up in a such a way that only functions that you want to call get called when you want to call them.</p>\n\n<p>A part of the solution is as you have defined it ...</p>\n\n<pre><code>if __name__ == '__main__':\n conn_up()\n</code></...
{ "AcceptedAnswerId": "197293", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T13:53:14.953", "Id": "197211", "Score": "0", "Tags": [ "python", "python-3.x", "ssh" ], "Title": "Sending an uptime to a remote server through SSH with the method pxssh" }
197211
<p>While trying to get better at C++ I tried my hand at making a stack implementation. This is the result:</p> <pre><code>#include&lt;iostream&gt; template&lt;typename T&gt; struct Node { T data; Node *next; Node(T data, Node *next) : data(data), next(next) {} }; template&lt;typename T&gt; class Stack { public: Stack() : top(nullptr), level(0), max_size(10) {} Stack(int max_size) : top(nullptr), level(0), max_size(max_size) {}; void push(T data); T pop(); void display(); bool isEmpty() { return level == 0; } bool isFull() { return level == max_size; } int geLevel() { return level; } int getMaxSize() { return max_size; } private: Node&lt;T&gt; *top; int level, max_size; }; template&lt;typename T&gt; void Stack&lt;T&gt;::push(T data) { if(!isFull()) { Node&lt;T&gt; *newNode = new Node&lt;T&gt;(data, top); top = newNode; level++; } else { std::cerr &lt;&lt; "stack overflow"; } } template&lt;typename T&gt; T Stack&lt;T&gt;::pop() { if(!isEmpty()) { Node&lt;T&gt; *temp = top; T data = temp-&gt;data; top = top-&gt;next; level--; delete temp; return data; } std::cerr &lt;&lt; "stack underflow"; } template&lt;typename T&gt; void Stack&lt;T&gt;::display() { Node&lt;T&gt; *curr = top; while(curr != nullptr) { std::cout &lt;&lt; curr-&gt;data &lt;&lt; std::endl; curr = curr-&gt;next; } } </code></pre> <p>Any help would be appreciated to make this code mor C++'ish.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T15:41:14.817", "Id": "380063", "Score": "4", "body": "There is a standard stack. [std::stack](https://en.cppreference.com/w/cpp/container/stack) if you want to implement it you may want to model your interface after it. The reason t...
[ { "body": "<p>It seems a stack is the HelloWorld of C++ classes and memory management :).</p>\n\n<p>First, your class has no destructors. It means that when your instance will be destroyed, it will only deallocate the stack attributes : <code>top</code>, <code>level</code> and <code>max_size</code>. Notice that...
{ "AcceptedAnswerId": "197217", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T15:19:54.227", "Id": "197213", "Score": "5", "Tags": [ "c++", "stack" ], "Title": "Abstract Data Type: Stack implementation in C++" }
197213
<p>I have a hierarchy of parts in my database. For example, one part (call it <code>0010102-0112-315</code>) is a resistor. It's used in a billion different top-level assemblies. My final goal is to get all the top level product IDs related to the low level IDs (e.g. <code>0010102-0112-315</code>).</p> <p>My current approach is to <code>left join</code> the table onto itself 8 times (one past the max product depth), and when the <code>recordId</code> after is <code>NULL</code> then it must be a top level <code>recordId</code>. </p> <p>However, the query takes almost 7 minutes to run, and I have a feeling I'm doing something wrong.</p> <p>I can't use CTEs (to my knowledge) because we're using SQL Server 2003 (before CTEs). Is there a better way of doing this? </p> <p>Here's my current code:</p> <pre><code>SELECT I1.IMA_ItemID as ItemID1, I1.IMA_ProdFam as ProdFam1 ,I1.IMA_RecordID as RecordId1 -- same as PSH.PSH_IMA_RecordID ,I2.IMA_RecordID as RecordId2 ,I3.IMA_RecordID as RecordId3 ,I4.IMA_RecordID as RecordId4 ,I5.IMA_RecordID as RecordId5 ,I6.IMA_RecordID as RecordId6 ,I7.IMA_RecordID as RecordId7 ,I8.IMA_RecordID as RecordId8 ,I9.IMA_RecordID as RecordId9 FROM Item AS I1 left join ProductStructureHeader AS PSH1 ON PSH1.PSH_IMA_RecordID = I1.IMA_RecordID left join ProductStructure AS PS1 on PS1.PST_PSH_RecordID = PSH1.PSH_RecordID left join Item AS I2 ON I2.IMA_RecordID = PS1.PST_IMA_RecordID left join ProductStructureHeader AS PSH2 ON PSH2.PSH_IMA_RecordID = I2.IMA_RecordID left join ProductStructure AS PS2 on PS2.PST_PSH_RecordID = PSH2.PSH_RecordID left join Item AS I3 ON I3.IMA_RecordID = PS2.PST_IMA_RecordID left join ProductStructureHeader AS PSH3 ON PSH3.PSH_IMA_RecordID = I3.IMA_RecordID left join ProductStructure AS PS3 on PS3.PST_PSH_RecordID = PSH3.PSH_RecordID left join Item AS I4 ON I4.IMA_RecordID = PS3.PST_IMA_RecordID left join ProductStructureHeader AS PSH4 ON PSH4.PSH_IMA_RecordID = I4.IMA_RecordID left join ProductStructure AS PS4 on PS4.PST_PSH_RecordID = PSH4.PSH_RecordID left join Item AS I5 ON I5.IMA_RecordID = PS4.PST_IMA_RecordID left join ProductStructureHeader AS PSH5 ON PSH5.PSH_IMA_RecordID = I5.IMA_RecordID left join ProductStructure AS PS5 on PS5.PST_PSH_RecordID = PSH5.PSH_RecordID left join Item AS I6 ON I6.IMA_RecordID = PS5.PST_IMA_RecordID left join ProductStructureHeader AS PSH6 ON PSH6.PSH_IMA_RecordID = I6.IMA_RecordID left join ProductStructure AS PS6 on PS6.PST_PSH_RecordID = PSH6.PSH_RecordID left join Item AS I7 ON I7.IMA_RecordID = PS6.PST_IMA_RecordID left join ProductStructureHeader AS PSH7 ON PSH7.PSH_IMA_RecordID = I7.IMA_RecordID left join ProductStructure AS PS7 on PS7.PST_PSH_RecordID = PSH7.PSH_RecordID left join Item AS I8 ON I8.IMA_RecordID = PS7.PST_IMA_RecordID left join ProductStructureHeader AS PSH8 ON PSH8.PSH_IMA_RecordID = I8.IMA_RecordID left join ProductStructure AS PS8 on PS8.PST_PSH_RecordID = PSH8.PSH_RecordID left join Item AS I9 ON I9.IMA_RecordID = PS8.PST_IMA_RecordID </code></pre> <p>Some other obscure facts that might be useful:</p> <ul> <li><code>RecordId1</code> above is the <em>highest</em> level RecordId</li> <li>Selecting * where <code>IMA_ItemStatusCode = 'Active' and IMA_ItemTypeCode = 'Purchased Item'</code> from the <code>Item</code> table gives the lowest level items</li> <li>Can't think of anything else, but feel free to ask as there might be something.</li> </ul>
[]
[ { "body": "<p>Here are a couple of Questions:</p>\n\n<ol>\n<li>Have you tried reverse order in your joins? I.e. start with <code>PS=&gt;PSH=&gt;Item</code>.</li>\n<li>Have you tried inner joins versus left join? Could see speed improvement (less data for sure)</li>\n<li>Is there any way to recurse only on ite...
{ "AcceptedAnswerId": "197221", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T15:30:20.467", "Id": "197214", "Score": "4", "Tags": [ "sql", "sql-server" ], "Title": "Select recordIDs for Bill of Materials" }
197214
<p>I did the following exercise:</p> <blockquote> <p>Write a C program that does the equivalent of C++ <code>string s; cin&gt;&gt;s;</code>; that is, define an input operation that reads an arbitrarily long sequence of whitespace-terminated characters into a zero terminated array of chars.</p> </blockquote> <p>I wonder if it's good code. What could be improved? </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; struct String { char* signs; size_t size; size_t capacity; }; void String_allocate_space(char **c, size_t *capacity) { if (*capacity == 0) { // allocate the first time *capacity = 1; *c = malloc(sizeof(**c) * ((*capacity))); } else { *capacity *= 2; // double the new capacity *c = realloc(*c, sizeof(**c) * (*capacity)); } if (*c == NULL) exit(-1); } void add_character(struct String* string, int ch) { if (string-&gt;size == string-&gt;capacity) { // if current letter sz = capacity String_allocate_space(&amp;string-&gt;signs, &amp;string-&gt;capacity); } string-&gt;signs[string-&gt;size++] = ch; // append the sign in the array } void String_read(struct String* string) { int ch = ' '; while (ch = getc(stdin)) { if (!isalpha(ch)) break; add_character(string, ch); } add_character(string, '\0'); } void String_print(struct String* string) { printf("%s", string-&gt;signs); } void String_free(struct String* string) { int i = 0; for (i = 0; i &lt; string-&gt;capacity; ++i) { free(string[i].signs); string[i].signs = NULL; } } int main() { struct String string = { 0 }; String_read(&amp;string); String_print(&amp;string); String_free(&amp;string); getchar(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:33:24.283", "Id": "380194", "Score": "0", "body": "This approach consumes the trailing delimiter. Its value is lost. Is that truly intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:36:...
[ { "body": "<p>Don't do this:</p>\n<pre><code>*c = realloc(*c, sizeof(**c) * (*capacity));\n</code></pre>\n<p>Once you have error handling that's more sophisticated than <code>exit(1)</code>, this will become a liability. You need a temporary:</p>\n<pre><code>char *tmp = realloc(*c, new_capacity);\nif (!tmp) {\...
{ "AcceptedAnswerId": "197219", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T16:21:32.653", "Id": "197218", "Score": "10", "Tags": [ "c", "strings", "io" ], "Title": "Emulating C++ string input in C" }
197218
<p>This is used on an Excel order form to calculate quantities in a userform for variables based on various criteria on the worksheet. It's too much code for a single Sub, but I'm not sure how I can make it any smaller or break it up.</p> <pre><code>Private Sub UserForm_Activate() Dim LastRow As Integer LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row Dim B_academy As Long, B_alice As Long, B_american As Long, B_apricot As Long, B_aqua As Long, B_beige As Long, B_black As Long, B_brightgold As Long, B_bronze As Long, B_brown As Long, B_burntorange As Long, B_cardinal As Long, B_citron As Long, B_coolgray As Long, B_copper As Long, B_cream As Long, B_drab As Long, B_forest As Long, B_gold As Long, B_gray As Long, B_kelly As Long, B_lemon As Long, B_ltblue As Long, B_lilac As Long, B_maize As Long, B_maroon As Long, B_navy As Long, B_nile As Long, B_oldgold As Long, B_olive As Long, B_orange As Long, B_peach As Long, B_peacock As Long, B_pink As Long, B_purple As Long, B_red As Long, B_sage As Long, B_salmon As Long, B_silver As Long, B_texasorange As Long, B_white As Long, B_wine As Long, B_yale As Long, _ M_academy As Long, M_alice As Long, M_american As Long, M_apricot As Long, M_aqua As Long, M_beige As Long, M_black As Long, M_brightgold As Long, M_bronze As Long, M_brown As Long, M_burntorange As Long, M_cardinal As Long, M_citron As Long, M_coolgray As Long, M_copper As Long, M_cream As Long, M_drab As Long, M_forest As Long, M_gold As Long, M_gray As Long, M_kelly As Long, M_lemon As Long, M_ltblue As Long, M_lilac As Long, M_maize As Long, M_maroon As Long, M_navy As Long, M_nile As Long, M_oldgold As Long, M_olive As Long, M_orange As Long, M_peach As Long, M_peacock As Long, M_pink As Long, M_purple As Long, M_red As Long, M_sage As Long, M_salmon As Long, M_silver As Long, M_texasorange As Long, M_white As Long, M_wine As Long, M_yale As Long, _ D_academy As Long, D_alice As Long, D_american As Long, D_apricot As Long, D_aqua As Long, D_beige As Long, D_black As Long, D_brightgold As Long, D_bronze As Long, D_brown As Long, D_burntorange As Long, D_cardinal As Long, D_citron As Long, D_coolgray As Long, D_copper As Long, D_cream As Long, D_drab As Long, D_forest As Long, D_gold As Long, D_gray As Long, D_kelly As Long, D_lemon As Long, D_ltblue As Long, D_lilac As Long, D_maize As Long, D_maroon As Long, D_navy As Long, D_nile As Long, D_oldgold As Long, D_olive As Long, D_orange As Long, D_peach As Long, D_peacock As Long, D_pink As Long, D_purple As Long, D_red As Long, D_sage As Long, D_salmon As Long, D_silver As Long, D_texasorange As Long, D_white As Long, D_wine As Long, D_yale As Long, _ A_academy As Long, A_alice As Long, A_american As Long, A_apricot As Long, A_aqua As Long, A_beige As Long, A_black As Long, A_brightgold As Long, A_bronze As Long, A_brown As Long, A_burntorange As Long, A_cardinal As Long, A_citron As Long, A_coolgray As Long, A_copper As Long, A_cream As Long, A_drab As Long, A_forest As Long, A_gold As Long, A_gray As Long, A_kelly As Long, A_lemon As Long, A_ltblue As Long, A_lilac As Long, A_maize As Long, A_maroon As Long, A_navy As Long, A_nile As Long, A_oldgold As Long, A_olive As Long, A_orange As Long, A_peach As Long, A_peacock As Long, A_pink As Long, A_purple As Long, A_red As Long, A_sage As Long, A_salmon As Long, A_silver As Long, A_texasorange As Long, A_white As Long, A_wine As Long, A_yale As Long, _ Mem_academy As Long, Mem_alice As Long, Mem_american As Long, Mem_apricot As Long, Mem_aqua As Long, Mem_beige As Long, Mem_black As Long, Mem_brightgold As Long, Mem_bronze As Long, Mem_brown As Long, Mem_burntorange As Long, Mem_cardinal As Long, Mem_citron As Long, Mem_coolgray As Long, Mem_copper As Long, Mem_cream As Long, Mem_drab As Long, Mem_forest As Long, Mem_gold As Long, Mem_gray As Long, Mem_kelly As Long, Mem_lemon As Long, Mem_ltblue As Long, Mem_lilac As Long, Mem_maize As Long, Mem_maroon As Long, Mem_navy As Long, Mem_nile As Long, Mem_oldgold As Long, Mem_olive As Long, Mem_orange As Long, Mem_peach As Long, Mem_peacock As Long, Mem_pink As Long, Mem_purple As Long, Mem_red As Long, Mem_sage As Long, Mem_salmon As Long, Mem_silver As Long, Mem_texasorange As Long, Mem_white As Long, Mem_wine As Long, Mem_yale As Long, _ B_tasselCount As String, M_tasselCount As String, D_tasselCount As String, A_tasselCount As String, Mem_tasselCount As String B_alice = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("5 (macro)", "5"))) M_alice = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("5 (macro)", "5"))) D_alice = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("5 (macro)", "5"))) A_alice = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("5 (macro)", "5"))) B_apricot = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("58 (macro)", "58"))) M_apricot = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("58 (macro)", "58"))) D_apricot = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("58 (macro)", "58"))) A_apricot = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("58 (macro)", "58"))) B_aqua = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("60 (macro)", "60"))) M_aqua = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("60 (macro)", "60"))) D_aqua = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("60 (macro)", "60"))) A_aqua = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("60 (macro)", "60"))) B_black = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("98 (macro)", "98"))) M_black = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("98 (macro)", "98"))) D_black = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("98 (macro)", "98"))) A_black = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("98 (macro)", "98", "0 (macro)", "0"))) B_brown = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("30 (macro)", "30"))) M_brown = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("30 (macro)", "30"))) D_brown = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("30 (macro)", "30"))) A_brown = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("30 (macro)", "30"))) B_burntorange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("32 (macro)", "32"))) M_burntorange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("32 (macro)", "32"))) D_burntorange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("32 (macro)", "32"))) A_burntorange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("32 (macro)", "32"))) B_cardinal = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("48 (macro)", "48"))) M_cardinal = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("48 (macro)", "48"))) D_cardinal = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("48 (macro)", "48"))) A_cardinal = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("48 (macro)", "48"))) B_copper = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("20 (macro)", "20"))) M_copper = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("20 (macro)", "20"))) D_copper = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("20 (macro)", "20"))) A_copper = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("20 (macro)", "20"))) Mem_copper = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("20 (macro)", "20"))) B_citron = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("84 (macro)", "84"))) M_citron = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("84 (macro)", "84"))) D_citron = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("84 (macro)", "84"))) A_citron = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("84 (macro)", "84"))) Mem_citron = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("84 (macro)", "84"))) B_cream = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("99 (macro)", "99"))) M_cream = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("99 (macro)", "99"))) D_cream = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("99 (macro)", "99"))) A_cream = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("99 (macro)", "99"))) Mem_cream = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("99 (macro)", "99"))) B_drab = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("8 (macro)", "8"))) M_drab = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("8 (macro)", "8"))) D_drab = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("8 (macro)", "8"))) A_drab = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("8 (macro)", "8"))) Mem_drab = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("8 (macro)", "8"))) B_forest = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("81 (macro)", "81"))) M_forest = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("81 (macro)", "81"))) D_forest = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("81 (macro)", "81"))) A_forest = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("81 (macro)", "81"))) Mem_forest = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("81 (macro)", "81"))) B_gold = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("80 (macro)", "80"))) M_gold = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("80 (macro)", "80"))) D_gold = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("80 (macro)", "80"))) A_gold = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("80 (macro)", "80"))) Mem_gold = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("80 (macro)", "80"))) B_gray = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("88 (macro)", "88"))) M_gray = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("88 (macro)", "88"))) D_gray = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("88 (macro)", "88"))) A_gray = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("88 (macro)", "88"))) Mem_gray = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("88 (macro)", "88"))) B_kelly = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("54 (macro)", "54"))) M_kelly = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("54 (macro)", "54"))) D_kelly = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("54 (macro)", "54"))) A_kelly = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("54 (macro)", "54"))) Mem_kelly = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("54 (macro)", "54"))) B_lemon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("52 (macro)", "52"))) M_lemon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("52 (macro)", "52"))) D_lemon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("52 (macro)", "52"))) A_lemon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("52 (macro)", "52"))) Mem_lemon = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("52 (macro)", "52"))) B_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("18 (macro)", "18"))) + Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("6 (macro)", "6"))) M_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("18 (macro)", "18"))) + M_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("6 (macro)", "6"))) D_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("18 (macro)", "18"))) + D_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("6 (macro)", "6"))) A_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("18 (macro)", "18"))) + A_lilac = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("6 (macro)", "6"))) Mem_lilac = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("18 (macro)", "18"))) B_ltblue = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("22 (macro)", "22"))) M_ltblue = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("22 (macro)", "22"))) D_ltblue = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("22 (macro)", "22"))) A_ltblue = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("22 (macro)", "22"))) Mem_ltblue = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("22 (macro)", "22"))) B_maize = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("4 (macro)", "4"))) M_maize = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("4 (macro)", "4"))) D_maize = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("4 (macro)", "4"))) A_maize = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("4 (macro)", "4"))) Mem_maize = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("4 (macro)", "4"))) B_maroon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("40 (macro)", "40"))) M_maroon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("40 (macro)", "40"))) D_maroon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("40 (macro)", "40"))) A_maroon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("40 (macro)", "40"))) Mem_maroon = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("40 (macro)", "40"))) B_navy = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("41 (macro)", "41"))) M_navy = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("41 (macro)", "41"))) D_navy = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("41 (macro)", "41"))) A_navy = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("41 (macro)", "41"))) Mem_navy = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("41 (macro)", "41"))) B_nile = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("74 (macro)", "74"))) M_nile = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("74 (macro)", "74"))) D_nile = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("74 (macro)", "74"))) A_nile = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("74 (macro)", "74"))) Mem_nile = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("74 (macro)", "74"))) B_olive = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("72 (macro)", "72"))) M_olive = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("72 (macro)", "72"))) D_olive = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("72 (macro)", "72"))) A_olive = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("72 (macro)", "72"))) Mem_olive = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("72 (macro)", "72"))) B_orange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("28 (macro)", "28"))) M_orange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("28 (macro)", "28"))) D_orange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("28 (macro)", "28"))) A_orange = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("28 (macro)", "28"))) Mem_orange = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("28 (macro)", "28"))) B_peacock = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("66 (macro)", "66"))) M_peacock = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("66 (macro)", "66"))) D_peacock = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("66 (macro)", "66"))) A_peacock = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("66 (macro)", "66"))) Mem_peacock = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("66 (macro)", "66"))) B_pink = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("56 (macro)", "56"))) M_pink = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("56 (macro)", "56"))) D_pink = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("56 (macro)", "56"))) A_pink = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("56 (macro)", "56"))) Mem_pink = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("56 (macro)", "56"))) B_purple = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("50 (macro)", "50"))) M_purple = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("50 (macro)", "50"))) D_purple = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("50 (macro)", "50"))) A_purple = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("50 (macro)", "50"))) Mem_purple = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("50 (macro)", "50"))) B_red = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("16 (macro)", "16"))) M_red = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("16 (macro)", "16"))) D_red = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("16 (macro)", "16"))) A_red = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("16 (macro)", "16"))) Mem_reb = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("16 (macro)", "16"))) B_sage = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("68 (macro)", "68"))) M_sage = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("68 (macro)", "68"))) D_sage = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("68 (macro)", "68"))) A_sage = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("68 (macro)", "68"))) Mem_sage = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("68 (macro)", "68"))) B_salmon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("70 (macro)", "70"))) M_salmon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("70 (macro)", "70"))) D_salmon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("70 (macro)", "70"))) A_salmon = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("70 (macro)", "70"))) Mem_salmon = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("70 (macro)", "70"))) B_silver = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("62 (macro)", "62"))) M_silver = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("62 (macro)", "62"))) D_silver = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("62 (macro)", "62"))) A_silver = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("62 (macro)", "62"))) Mem_silver = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("62 (macro)", "62"))) B_yale = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("71 (macro)", "71"))) M_yale = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("71 (macro)", "71"))) D_yale = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("71 (macro)", "71"))) A_yale = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("71 (macro)", "71"))) Mem_yale = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("71 (macro)", "71"))) B_white = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "B*", Range("L84:L" &amp; LastRow), Array("2 (macro)", "2"))) M_white = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "M*", Range("L84:L" &amp; LastRow), Array("2 (macro)", "2"))) D_white = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "D*", Range("L84:L" &amp; LastRow), Array("2 (macro)", "2"))) A_white = Application.Sum(Application.SumIfs(Range("G84:G" &amp; LastRow), Range("G84:G" &amp; LastRow), "1", Range("K84:K" &amp; LastRow), "A*", Range("L84:L" &amp; LastRow), Array("2 (macro)", "2"))) Mem_white = Application.Sum(Application.SumIfs(Range("R84:R" &amp; LastRow), Range("L84:L" &amp; LastRow), Array("2 (macro)", "2"))) If B_alice &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Alice:" &amp; vbTab &amp; vbTab &amp; B_alice &amp; vbLf If B_apricot &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Apricot" &amp; vbTab &amp; vbTab &amp; B_apricot &amp; vbLf If B_aqua &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Aqua" &amp; vbTab &amp; vbTab &amp; B_aqua &amp; vbLf If B_black &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Black" &amp; vbTab &amp; vbTab &amp; B_black &amp; vbLf If B_brown &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Brown" &amp; vbTab &amp; vbTab &amp; B_brown &amp; vbLf If B_burntorange &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Burnt Orange" &amp; vbTab &amp; B_burntorange &amp; vbLf If B_cardinal &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Cardinal/Wine" &amp; vbTab &amp; B_cardinal &amp; vbLf If B_copper &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Copper" &amp; vbTab &amp; vbTab &amp; B_copper &amp; vbLf If B_citron &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Citron" &amp; vbTab &amp; vbTab &amp; B_citron &amp; vbLf If B_cream &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Cream" &amp; vbTab &amp; vbTab &amp; B_cream &amp; vbLf If B_drab &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Drab" &amp; vbTab &amp; vbTab &amp; B_drab &amp; vbLf If B_forest &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Forest Green" &amp; vbTab &amp; B_forest &amp; vbLf If B_gold &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Gold" &amp; vbTab &amp; vbTab &amp; B_gold &amp; vbLf If B_gray &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Gray" &amp; vbTab &amp; vbTab &amp; B_gray &amp; vbLf If B_kelly &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Kelly Green" &amp; vbTab &amp; B_kelly &amp; vbLf If B_lemon &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Lemon" &amp; vbTab &amp; vbTab &amp; B_lemon &amp; vbLf If B_lilac &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Lilac" &amp; vbTab &amp; vbTab &amp; B_lilac &amp; vbLf If B_ltblue &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Light Blue" &amp; vbTab &amp; B_ltblue &amp; vbLf If B_maize &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Maize" &amp; vbTab &amp; vbTab &amp; B_maize &amp; vbLf If B_maroon &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Maroon" &amp; vbTab &amp; vbTab &amp; B_maroon &amp; vbLf If B_navy &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Navy" &amp; vbTab &amp; vbTab &amp; B_navy &amp; vbLf If B_nile &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Nile Green" &amp; vbTab &amp; B_nile &amp; vbLf If B_olive &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Olive Green" &amp; vbTab &amp; B_olive &amp; vbLf If B_orange &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Orange" &amp; vbTab &amp; vbTab &amp; B_orange &amp; vbLf If B_peacock &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Peacock Blue" &amp; vbTab &amp; B_peacock &amp; vbLf If B_pink &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Pink" &amp; vbTab &amp; vbTab &amp; B_pink &amp; vbLf If B_purple &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Purple" &amp; vbTab &amp; vbTab &amp; B_purple &amp; vbLf If B_red &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Red" &amp; vbTab &amp; vbTab &amp; B_red &amp; vbLf If B_sage &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Sage Green" &amp; vbTab &amp; B_sage &amp; vbLf If B_salmon &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Salmon" &amp; vbTab &amp; vbTab &amp; B_salmon &amp; vbLf If B_silver &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Silver" &amp; vbTab &amp; vbTab &amp; B_silver &amp; vbLf If B_white &gt; 0 Then B_tasselCount = B_tasselCount &amp; "White" &amp; vbTab &amp; vbTab &amp; B_white &amp; vbLf If B_yale &gt; 0 Then B_tasselCount = B_tasselCount &amp; "Yale" &amp; vbTab &amp; vbTab &amp; B_yale &amp; vbLf If B_tasselCount = "" Then B_tasselCount = "N/A" If M_alice &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Alice:" &amp; vbTab &amp; vbTab &amp; M_alice &amp; vbLf If M_apricot &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Apricot" &amp; vbTab &amp; vbTab &amp; M_apricot &amp; vbLf If M_aqua &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Aqua" &amp; vbTab &amp; vbTab &amp; M_aqua &amp; vbLf If M_black &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Black" &amp; vbTab &amp; vbTab &amp; M_black &amp; vbLf If M_brown &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Brown" &amp; vbTab &amp; vbTab &amp; M_brown &amp; vbLf If M_burntorange &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Burnt Orange" &amp; vbTab &amp; M_burntorange &amp; vbLf If M_cardinal &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Cardinal/Wine" &amp; vbTab &amp; M_cardinal &amp; vbLf If M_copper &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Copper" &amp; vbTab &amp; vbTab &amp; M_copper &amp; vbLf If M_citron &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Citron" &amp; vbTab &amp; vbTab &amp; M_citron &amp; vbLf If M_cream &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Cream" &amp; vbTab &amp; vbTab &amp; M_cream &amp; vbLf If M_drab &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Drab" &amp; vbTab &amp; vbTab &amp; M_drab &amp; vbLf If M_forest &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Forest Green" &amp; vbTab &amp; M_forest &amp; vbLf If M_gold &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Gold" &amp; vbTab &amp; vbTab &amp; M_gold &amp; vbLf If M_gray &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Gray" &amp; vbTab &amp; vbTab &amp; M_gray &amp; vbLf If M_kelly &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Kelly Green" &amp; vbTab &amp; M_kelly &amp; vbLf If M_lemon &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Lemon" &amp; vbTab &amp; vbTab &amp; M_lemon &amp; vbLf If M_lilac &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Lilac" &amp; vbTab &amp; vbTab &amp; M_lilac &amp; vbLf If M_ltblue &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Light Blue" &amp; vbTab &amp; M_ltblue &amp; vbLf If M_maize &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Maize" &amp; vbTab &amp; vbTab &amp; M_maize &amp; vbLf If M_maroon &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Maroon" &amp; vbTab &amp; vbTab &amp; M_maroon &amp; vbLf If M_navy &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Navy" &amp; vbTab &amp; vbTab &amp; M_navy &amp; vbLf If M_nile &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Nile Green" &amp; vbTab &amp; M_nile &amp; vbLf If M_olive &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Olive Green" &amp; vbTab &amp; M_olive &amp; vbLf If M_orange &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Orange" &amp; vbTab &amp; vbTab &amp; M_orange &amp; vbLf If M_peacock &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Peacock Blue" &amp; vbTab &amp; M_peacock &amp; vbLf If M_pink &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Pink" &amp; vbTab &amp; vbTab &amp; M_pink &amp; vbLf If M_purple &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Purple" &amp; vbTab &amp; vbTab &amp; M_purple &amp; vbLf If M_red &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Red" &amp; vbTab &amp; vbTab &amp; M_red &amp; vbLf If M_sage &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Sage Green" &amp; vbTab &amp; M_sage &amp; vbLf If M_salmon &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Salmon" &amp; vbTab &amp; vbTab &amp; M_salmon &amp; vbLf If M_silver &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Silver" &amp; vbTab &amp; vbTab &amp; M_silver &amp; vbLf If M_white &gt; 0 Then M_tasselCount = M_tasselCount &amp; "White" &amp; vbTab &amp; vbTab &amp; M_white &amp; vbLf If M_yale &gt; 0 Then M_tasselCount = M_tasselCount &amp; "Yale" &amp; vbTab &amp; vbTab &amp; M_yale &amp; vbLf If M_tasselCount = "" Then M_tasselCount = "N/A" If D_alice &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Alice:" &amp; vbTab &amp; vbTab &amp; D_alice &amp; vbLf If D_apricot &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Apricot" &amp; vbTab &amp; vbTab &amp; D_apricot &amp; vbLf If D_aqua &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Aqua" &amp; vbTab &amp; vbTab &amp; D_aqua &amp; vbLf If D_black &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Black" &amp; vbTab &amp; vbTab &amp; D_black &amp; vbLf If D_brown &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Brown" &amp; vbTab &amp; vbTab &amp; D_brown &amp; vbLf If D_burntorange &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Burnt Orange" &amp; vbTab &amp; D_burntorange &amp; vbLf If D_cardinal &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Cardinal/Wine" &amp; vbTab &amp; D_cardinal &amp; vbLf If D_copper &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Copper" &amp; vbTab &amp; vbTab &amp; D_copper &amp; vbLf If D_citron &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Citron" &amp; vbTab &amp; vbTab &amp; D_citron &amp; vbLf If D_cream &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Cream" &amp; vbTab &amp; vbTab &amp; D_cream &amp; vbLf If D_drab &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Drab" &amp; vbTab &amp; vbTab &amp; D_drab &amp; vbLf If D_forest &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Forest Green" &amp; vbTab &amp; D_forest &amp; vbLf If D_gold &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Gold" &amp; vbTab &amp; vbTab &amp; D_gold &amp; vbLf If D_gray &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Gray" &amp; vbTab &amp; vbTab &amp; D_gray &amp; vbLf If D_kelly &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Kelly Green" &amp; vbTab &amp; D_kelly &amp; vbLf If D_lemon &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Lemon" &amp; vbTab &amp; vbTab &amp; D_lemon &amp; vbLf If D_lilac &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Lilac" &amp; vbTab &amp; vbTab &amp; D_lilac &amp; vbLf If D_ltblue &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Light Blue" &amp; vbTab &amp; D_ltblue &amp; vbLf If D_maize &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Maize" &amp; vbTab &amp; vbTab &amp; D_maize &amp; vbLf If D_maroon &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Maroon" &amp; vbTab &amp; vbTab &amp; D_maroon &amp; vbLf If D_navy &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Navy" &amp; vbTab &amp; vbTab &amp; D_navy &amp; vbLf If D_nile &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Nile Green" &amp; vbTab &amp; D_nile &amp; vbLf If D_olive &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Olive Green" &amp; vbTab &amp; D_olive &amp; vbLf If D_orange &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Orange" &amp; vbTab &amp; vbTab &amp; D_orange &amp; vbLf If D_peacock &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Peacock Blue" &amp; vbTab &amp; D_peacock &amp; vbLf If D_pink &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Pink" &amp; vbTab &amp; vbTab &amp; D_pink &amp; vbLf If D_purple &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Purple" &amp; vbTab &amp; vbTab &amp; D_purple &amp; vbLf If D_red &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Red" &amp; vbTab &amp; vbTab &amp; D_red &amp; vbLf If D_sage &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Sage Green" &amp; vbTab &amp; D_sage &amp; vbLf If D_salmon &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Salmon" &amp; vbTab &amp; vbTab &amp; D_salmon &amp; vbLf If D_silver &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Silver" &amp; vbTab &amp; vbTab &amp; D_silver &amp; vbLf If D_white &gt; 0 Then D_tasselCount = D_tasselCount &amp; "White" &amp; vbTab &amp; vbTab &amp; D_white &amp; vbLf If D_yale &gt; 0 Then D_tasselCount = D_tasselCount &amp; "Yale" &amp; vbTab &amp; vbTab &amp; D_yale &amp; vbLf If D_tasselCount = "" Then D_tasselCount = "N/A" If A_alice &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Alice:" &amp; vbTab &amp; vbTab &amp; A_alice &amp; vbLf If A_apricot &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Apricot" &amp; vbTab &amp; vbTab &amp; A_apricot &amp; vbLf If A_aqua &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Aqua" &amp; vbTab &amp; vbTab &amp; A_aqua &amp; vbLf If A_black &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Black" &amp; vbTab &amp; vbTab &amp; A_black &amp; vbLf If A_brown &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Brown" &amp; vbTab &amp; vbTab &amp; A_brown &amp; vbLf If A_burntorange &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Burnt Orange" &amp; vbTab &amp; A_burntorange &amp; vbLf If A_cardinal &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Cardinal/Wine" &amp; vbTab &amp; A_cardinal &amp; vbLf If A_copper &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Copper" &amp; vbTab &amp; vbTab &amp; A_copper &amp; vbLf If A_citron &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Citron" &amp; vbTab &amp; vbTab &amp; A_citron &amp; vbLf If A_cream &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Cream" &amp; vbTab &amp; vbTab &amp; A_cream &amp; vbLf If A_drab &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Drab" &amp; vbTab &amp; vbTab &amp; A_drab &amp; vbLf If A_forest &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Forest Green" &amp; vbTab &amp; A_forest &amp; vbLf If A_gold &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Gold" &amp; vbTab &amp; vbTab &amp; A_gold &amp; vbLf If A_gray &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Gray" &amp; vbTab &amp; vbTab &amp; A_gray &amp; vbLf If A_kelly &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Kelly Green" &amp; vbTab &amp; A_kelly &amp; vbLf If A_lemon &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Lemon" &amp; vbTab &amp; vbTab &amp; A_lemon &amp; vbLf If A_lilac &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Lilac" &amp; vbTab &amp; vbTab &amp; A_lilac &amp; vbLf If A_ltblue &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Light Blue" &amp; vbTab &amp; A_ltblue &amp; vbLf If A_maize &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Maize" &amp; vbTab &amp; vbTab &amp; A_maize &amp; vbLf If A_maroon &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Maroon" &amp; vbTab &amp; vbTab &amp; A_maroon &amp; vbLf If A_navy &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Navy" &amp; vbTab &amp; vbTab &amp; A_navy &amp; vbLf If A_nile &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Nile Green" &amp; vbTab &amp; A_nile &amp; vbLf If A_olive &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Olive Green" &amp; vbTab &amp; A_olive &amp; vbLf If A_orange &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Orange" &amp; vbTab &amp; vbTab &amp; A_orange &amp; vbLf If A_peacock &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Peacock Blue" &amp; vbTab &amp; A_peacock &amp; vbLf If A_pink &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Pink" &amp; vbTab &amp; vbTab &amp; A_pink &amp; vbLf If A_purple &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Purple" &amp; vbTab &amp; vbTab &amp; A_purple &amp; vbLf If A_red &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Red" &amp; vbTab &amp; vbTab &amp; A_red &amp; vbLf If A_sage &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Sage Green" &amp; vbTab &amp; A_sage &amp; vbLf If A_salmon &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Salmon" &amp; vbTab &amp; vbTab &amp; A_salmon &amp; vbLf If A_silver &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Silver" &amp; vbTab &amp; vbTab &amp; A_silver &amp; vbLf If A_white &gt; 0 Then A_tasselCount = A_tasselCount &amp; "White" &amp; vbTab &amp; vbTab &amp; A_white &amp; vbLf If A_yale &gt; 0 Then A_tasselCount = A_tasselCount &amp; "Yale" &amp; vbTab &amp; vbTab &amp; A_yale &amp; vbLf If A_tasselCount = "" Then B_tasselCount = "N/A" If Mem_alice &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Alice:" &amp; vbTab &amp; vbTab &amp; Mem_alice &amp; vbLf If Mem_apricot &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Apricot" &amp; vbTab &amp; vbTab &amp; Mem_apricot &amp; vbLf If Mem_aqua &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Aqua" &amp; vbTab &amp; vbTab &amp; Mem_aqua &amp; vbLf If Mem_black &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Black" &amp; vbTab &amp; vbTab &amp; Mem_black &amp; vbLf If Mem_brown &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Brown" &amp; vbTab &amp; vbTab &amp; Mem_brown &amp; vbLf If Mem_burntorange &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Burnt Orange" &amp; vbTab &amp; Mem_burntorange &amp; vbLf If Mem_cardinal &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Cardinal/Wine" &amp; vbTab &amp; Mem_cardinal &amp; vbLf If Mem_copper &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Copper" &amp; vbTab &amp; vbTab &amp; Mem_copper &amp; vbLf If Mem_citron &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Citron" &amp; vbTab &amp; vbTab &amp; Mem_citron &amp; vbLf If Mem_cream &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Cream" &amp; vbTab &amp; vbTab &amp; Mem_cream &amp; vbLf If Mem_drab &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Drab" &amp; vbTab &amp; vbTab &amp; Mem_drab &amp; vbLf If Mem_forest &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Forest Green" &amp; vbTab &amp; Mem_forest &amp; vbLf If Mem_gold &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Gold" &amp; vbTab &amp; vbTab &amp; Mem_gold &amp; vbLf If Mem_gray &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Gray" &amp; vbTab &amp; vbTab &amp; Mem_gray &amp; vbLf If Mem_kelly &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Kelly Green" &amp; vbTab &amp; Mem_kelly &amp; vbLf If Mem_lemon &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Lemon" &amp; vbTab &amp; vbTab &amp; Mem_lemon &amp; vbLf If Mem_lilac &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Lilac" &amp; vbTab &amp; vbTab &amp; Mem_lilac &amp; vbLf If Mem_ltblue &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Light Blue" &amp; vbTab &amp; Mem_ltblue &amp; vbLf If Mem_maize &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Maize" &amp; vbTab &amp; vbTab &amp; Mem_maize &amp; vbLf If Mem_maroon &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Maroon" &amp; vbTab &amp; vbTab &amp; Mem_maroon &amp; vbLf If Mem_navy &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Navy" &amp; vbTab &amp; vbTab &amp; Mem_navy &amp; vbLf If Mem_nile &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Nile Green" &amp; vbTab &amp; Mem_nile &amp; vbLf If Mem_olive &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Olive Green" &amp; vbTab &amp; Mem_olive &amp; vbLf If Mem_orange &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Orange" &amp; vbTab &amp; vbTab &amp; Mem_orange &amp; vbLf If Mem_peacock &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Peacock Blue" &amp; vbTab &amp; Mem_peacock &amp; vbLf If Mem_pink &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Pink" &amp; vbTab &amp; vbTab &amp; Mem_pink &amp; vbLf If Mem_purple &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Purple" &amp; vbTab &amp; vbTab &amp; Mem_purple &amp; vbLf If Mem_red &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Red" &amp; vbTab &amp; vbTab &amp; Mem_red &amp; vbLf If Mem_sage &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Sage Green" &amp; vbTab &amp; Mem_sage &amp; vbLf If Mem_salmon &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Salmon" &amp; vbTab &amp; vbTab &amp; Mem_salmon &amp; vbLf If Mem_silver &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Silver" &amp; vbTab &amp; vbTab &amp; Mem_silver &amp; vbLf If Mem_white &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "White" &amp; vbTab &amp; vbTab &amp; Mem_white &amp; vbLf If Mem_yale &gt; 0 Then Mem_tasselCount = Mem_tasselCount &amp; "Yale" &amp; vbTab &amp; vbTab &amp; Mem_yale &amp; vbLf If Mem_tasselCount = "" Then Mem_tasselCount = "N/A" Label1.Caption = B_tasselCount Label2.Caption = M_tasselCount Label3.Caption = D_tasselCount Label4.Caption = A_tasselCount Label5.Caption = Mem_tasselCount End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T18:15:27.303", "Id": "380077", "Score": "2", "body": "Unfortunately you didn't give more context, but this code seems to cry for a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T18:34:56.447", ...
[ { "body": "<h2>The Actual Question</h2>\n\n<p>There are probably better ways to do this, but let me sstart with your immediate question:</p>\n\n<p>If you look closely at the first part of the sub, you will see that all the summations only differ in two places, the letter in the second criterion and the number i...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T18:10:27.773", "Id": "197224", "Score": "-3", "Tags": [ "vba", "excel" ], "Title": "Calculate quantities in a userform" }
197224
<p>Another C exercise:</p> <blockquote> <p>Write a function that takes an array of 'ints' as its input and finds the smallest and largest elements. It should also compute the median and mean. Use a <code>struct</code> holding the result as the return value</p> </blockquote> <p>I found it quite awkward that there is no function to copy an array into another array, so I wrote one <code>intdup</code> to use it in the median calculation.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include &lt;limits.h&gt; struct Result { int smallest; int largest; double median; double mean; }; int cmp(void const *lhs, void const *rhs) { const int *left = (const int *)lhs; const int *right = (const int *)rhs; return *left - *right; } int * intdup(const int * source, const size_t len) { assert(source); int * p = malloc(len * sizeof(int)); if (p == NULL) exit(1); memcpy(p, source, len * sizeof(int)); return p; } int find_smallest(const int* array, const size_t len) { assert(array); size_t i = 0; int smallest = INT_MAX; for (i = 0; i &lt; len; ++i) { if (array[i] &lt; smallest) smallest = array[i]; } return smallest; } int find_largest(const int* array, const size_t len) { assert(array); size_t i = 0; int largest = INT_MIN; for (i = 0; i &lt; len; ++i) { if (array[i] &gt; largest) largest = array[i]; } return largest; } double calculate_median(const int* array, const size_t len) { assert(array); int* calc_array = intdup(array, len); int tmp = 0; qsort(array, len, sizeof(int), cmp); if (len % 2 == 0) { // is even // return the arithmetic middle of the two middle values return (array[(len - 1) / 2] + array[len / 2] ) /2.0; } else { // is odd // return the middle return array[len / 2]; } } double calculate_mean(const int* array, const size_t len) { assert(array); double mean = 0; size_t i = 0; for (i = 0; i &lt; len; ++i) mean += array[i]; return mean / len; } struct Result calculate_values(const int* array, const size_t len) { assert(array); struct Result result = { 0 }; result.smallest = find_smallest(array, len); result.largest = find_largest(array, len); result.median = calculate_median(array, len); result.mean = calculate_mean(array, len); return result; } void print_result(const struct Result* result) { assert(result); printf("smallest: %i\n", result-&gt;smallest); printf("largest: %i\n", result-&gt;largest); printf("median: %f\n", result-&gt;median); printf("mean: %f\n\n", result-&gt;mean); } int main() { int numbers[] = { 1,7,3,4,5,6,7,8,9 }; // 9 elements // int numbers[] = { 1,7,3,4,5,6,7,8 }; // 8 elements int len = sizeof(numbers) / sizeof(numbers[0]); struct Result result = calculate_values(&amp;numbers, len); print_result(&amp;result); getchar(); return 0; } </code></pre> <p>See the the revised code her: <a href="https://codereview.stackexchange.com/questions/197296/calculate-min-max-mean-and-median-out-of-array-version-2">Calculate min, max, mean and median out of array Version 2</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:41:32.477", "Id": "380198", "Score": "0", "body": "Regarding efficiency, you can find the median of an array without sorting it. But doing so efficiently isn’t trivial." }, { "ContentLicense": "CC BY-SA 4.0", "Creatio...
[ { "body": "<p>This code looks good to me. There are a few things I would do differently.</p>\n\n<ul>\n<li>If you restructure things a bit you can compute the minimum and maximum more simply from the sorted array, since you have it.</li>\n<li><code>intdup</code> is only called once, which in my opinion is ground...
{ "AcceptedAnswerId": "197231", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T18:48:00.190", "Id": "197227", "Score": "11", "Tags": [ "c", "array", "statistics" ], "Title": "Calculate min, max, mean and median out of array" }
197227
<p>I'm trying to dispatch to my reducers the current status of my request. So far I'm wondering how refined the status publishing of my thunk action. </p> <p>I feel like my code is very verbose and I wonder if I can reduce the line quantity of it. </p> <p>I inform my store that the request have reached some step by dispatching a corresponding status.</p> <p>Here my code : </p> <pre><code>// set the status available for my code with function arguments planned export const postFileStatus = [ { type: 'POST_FILE',status: request}, { type: 'POST_FILE', status: success, response: res }, { type: 'POST_FILE', status: error, error: err } ] // dispatch the thunk to the redux middleware const thunkFile = () =&gt; dispatch =&gt; { // inform the request have started by retrieve the "request" status on my file { dispatch(postFileStatus.find(step =&gt; step.status === "request")); Axios.post("http://localhost:7500/api/files", { "word": state.word, "data": state.base64Data, "id" : state.wordId }, { "Content-Type":"multipart/form-data"} ) // inform the request have succeed by retrieve the "success" status on my file .then(res =&gt; {dispatch(postFileStatus.find(step =&gt; step.status === "success")) console.log(res) }) .catch(err =&gt; { // inform the request have failed by retrieve the "error" status on my file dispatch(postFileStatus.find(step =&gt; step.status === "error")) console.log(" error :", error.response) }); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T19:41:29.213", "Id": "197228", "Score": "3", "Tags": [ "javascript", "asynchronous", "redux" ], "Title": "Status dispatching of my redux-thunk async action (post request)" }
197228
<h1>What is it used for?</h1> <p>This is a different script from any python script which performs DoS attacks. It's designed to practice parameters fuzzing in the requests (it's requested which parameter you have to fuzz - and after choosed, requests will be made with the selected parameter combined with a 400 random characters string) so we will expect the server will be slower to elaborate the requests.</p> <p>This is not a recent code, and neither it's full-tested.</p> <pre><code>import sys import socket, urllib from urllib.parse import urlparse from threading import Thread from time import sleep import socks import string, random import re def send_requests(mapped_requests, map_count): while True: for i in range(len(mapped_requests)): spot = mapped_requests[i] junk = ''.join(random.choices(string.ascii_uppercase, k = 400)) (spot[2])[spot[4]] = junk # fuzzes the replacement spot headers = ( "%s {} HTTP/1.1\r\n" "Host: {}\r\n" "Connection: close\r\n" "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0\r\n" "Accept-Encoding: gzip\r\n" "Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7\r\n" "Cache-Control: no-cache\r\n{}" ) % spot[0].upper() parsed_url = spot[5] url_path = '/' if parsed_url.path == '' else parsed_url.path url_params = spot[3] if spot[0] == "get": path_and_params = "{}?{}".format(url_path, url_params) headers = headers.format(path_and_params, parsed_url.netloc, '\r\n') else: terminal_header = ( "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: {}\r\n" "{}\r\n\r\n" ).format(len(url_params), url_params) headers = headers.format(url_path, parsed_url.netloc, terminal_header) #print(headers) s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((parsed_url.netloc, 80)) s.sendall(headers.encode("utf-8")) except socket.error: sleep(1) finally: s.close() print("Mapped request at index {} has been sent.".format(i)) def create_threads(threads, mapped_requests, map_count): for t in range(0, threads): thread = Thread(target = send_requests, args = ( mapped_requests, map_count, )) thread.start() def target_is_ok(host): try: socket.gethostbyname(host) except socket.gaierror: return False else: return True def query_yes_no(question, default = "yes"): """ Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits &lt;Enter&gt;. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = { "yes": True, "y": True, "ye": True, "no": False, "n": False } if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") if __name__ == "__main__": print("\nCVE-2014-9912 and alike vulnerabilities exploitation sample" + "\n\n") if query_yes_no("Do you want to bind a persistent Tor session?"): socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True) s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("api.ipify.org" , 80)) s.sendall(b"GET / HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n") print("Your IP address is", ((s.recv(4096)).decode('utf-8')).rsplit("\r\n\r\n")[1]) s.close() sys.stdout.write("\nTarget: ") if not target_is_ok(re.sub('^https?://', '', input())): sys.exit("\nTarget is down.\n") print("\nTarget is up.") print("You need to map at least one request to the scheme of the attack.\n") map_count = 0 mapped_requests = [] while (query_yes_no("\nMap request to the attack scheme?")): valid_method = valid_url = valid_param = False while not valid_method and not valid_url: sys.stdout.write("Select HTTP request method (GET/POST): ") method = input().lower() if method in [ 'get', 'post' ]: valid_method = True sys.stdout.write("URL: ") url = input() if not url.startswith(( "http://", "https://" )): url = "http://" + url parsed_url = urlparse(url) if (parsed_url.netloc): valid_url = True if method == "post": sys.stdout.write("Put the post data: ") post_data = input() unparsed_params = post_data else: unparsed_params = parsed_url.query parsed_params = urllib.parse.parse_qs(unparsed_params) print("Parsed parameters:", parsed_params) sys.stdout.write("Select the parameter to fuzz: ") parameter = input() try: if (parsed_params[parameter]): print("Parameter found.") mapped_requests.append([ method, url, parsed_params, unparsed_params, parameter, parsed_url ]) print("Request mapped in index {}.".format(map_count)) map_count += 1 except KeyError: print("Could not map the request because an invalid parameter was entered.") else: print("Could not map the request because an invalid URL was entered.") else: print("Could not map the request because an invalid method was entered.") if map_count &lt; 1: sys.exit("Could not adjust the attack: at least one mapped HTTP request is needed.") print("\nA total of {} HTTP requests to repeatedly emulate has been mapped to the attack scheme.\n".format(map_count)) valid_threads = False while not valid_threads: sys.stdout.write("\nEnter a number of threads (eg. 1000): ") threads = input() if threads.isdigit(): threads = int(threads) valid_threads = True print("Starting the mapped attack.\n") create_threads(threads, mapped_requests, map_count) </code></pre> <p>It's required to install <code>pysocks</code> library. The script is made to be more elastic and to perform an efficient attack.</p> <h1>Usage</h1> <p>We will test it on our own website, obviously. So admit we have a website who gets GET or POST requests, with these two hosted PHP files:</p> <blockquote> <pre><code>&lt;?php // demo.php $str = $_GET['str']; $foo = $_GET['foo']; die('str: ' . $str . ' @ ' . 'foo: ' . $foo); ?&gt; </code></pre> </blockquote> <p>and</p> <blockquote> <pre><code>&lt;?php // demo_post.php $str = $_POST['str']; $foo = $_POST['foo']; die('str: ' . $str . ' @ ' . 'foo: ' . $foo); ?&gt; </code></pre> </blockquote> <p>We have something to attack - let's run the script.</p> <pre><code>~ $ python cwe119.py </code></pre> <p>We will get asked if we want to bind requests to Tor by default. Not in my case, since I'm testing my own website and I don't need to. It will gets printed then our IP to let you see if you are connected to Tor network or not.</p> <p>Put the target, and we will do so without putting the <code>www.</code> (eg. <code>http://example.org</code>): the script will print either the website is working or not. In the first case, we will get asked to map at least a request to send in loop to attack the website.</p> <p>Then we select the method of the request we have to map to the attack, GET or POST. Let's take example with GET (<code>demo.php</code>).</p> <p>So we will paste the URL of the request (<code>http://example.org/demo.php?str=hi&amp;foo=bar</code>) and the script will detect the parameters, parse and print them.</p> <p>After that, we have to choose choose the parameter to fuzz (<code>str</code> or <code>foo</code>), so if we choose for example <code>str</code> the script will continiously replace the value <code>hi</code> with a random capitalized string composed of 400 characters.</p> <p>If the mapping was correctly compiled, the script will say that it's been added to the list of the attack scheme:</p> <blockquote> <pre><code>Request mapped in index 0. </code></pre> </blockquote> <p>We can continue to map as many requests as we want to (index <code>1</code>, index <code>2</code>, index <code>3</code> and so on). When you finished, we will say to not map any more request to the attack scheme and then we will write the number of the threads to start.</p> <p>The similar procedure is for POST requests, it's needed to be at least a bit familiar with HTTP requests.</p> <h1>About Improvements and Other</h1> <p>It's very appreciated if someone has any suggestion or feature to propose for the project/script.</p>
[]
[ { "body": "<p>I know you know this but, <strong>DDoS is a serious offence in most countries</strong> </p>\n\n<p>Without permission <strong>NEVER</strong> use it on other people's websites, since this can result in you going to jail.</p>\n\n<ul>\n<li><code>\"%s\" % (\"something\")</code> is deprecated, use <a hr...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T20:57:54.853", "Id": "197232", "Score": "1", "Tags": [ "python", "multithreading", "socket" ], "Title": "cwe119.py - a semi-automated script to test your security against DoS attacks" }
197232
<p>I started practicing in web-scraping few days ago. I made this code to extract data from a wikipedia page. There are several tables that classify mountains based on their height. However there is a problem with the size of the matrices. Some of them contain 5 columns while others 4. So I made this algorithm to extract all the names and the attributes of the mountains into separate lists. My approach was to create a length list that contains the number of <code>&lt;td&gt;</code> within the <code>&lt;tr&gt;</code> tags. The algorithm finds which table contains four columns and fills the column in excess (in the case of 5 columns) with NONE. However, I believe that there is a more efficient and more pythonic way to do it especially in the part where I use the <code>find.next()</code> function repedetly. Any suggestions are welcomed. </p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd URL="https://en.wikipedia.org/wiki/List_of_mountains_by_elevation" content=requests.get(URL).content soup=BeautifulSoup(content,'html.parser') all_tables=soup.find_all("table",{"class":["sortable", "plainrowheaders"]}) mountain_names=[] metres_KM=[] metres_FT=[] range_Mnt=[] location=[] lengths=[] for table in range(len(all_tables)): x=all_tables[table].find("tr").find_next("tr") y=x.find_all("td") lengths.append(len(y)) for row in all_tables[table].find_all("tr"): try: mountain_names.append(row.find("td").text) metres_KM.append(row.find("td").find_next("td").text) metres_FT.append(row.find("td").find_next("td").find_next("td").text) if lengths[table]==5: range_Mnt.append(row.find("td").find_next("td").find_next("td").find_next("td").text) else: range_Mnt.append(None) location.append(row.find("td").find_next("td").find_next("td").find_next("td").find_next("td").text) except: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T23:17:03.163", "Id": "380125", "Score": "1", "body": "Is the code working as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T23:18:39.863", "Id": "380126", "Score": "0", "body": ...
[ { "body": "<p>You're just looping on the rows, but not on the cells:</p>\n\n<pre><code> for row in all_tables[table].find_all(\"tr\"):\n</code></pre>\n\n<p>Rather than using multiple <code>find_next(\"td\")</code> one after the other, add another loop using <code>row.find_all('td')</code> and append each row an...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-25T22:41:27.217", "Id": "197236", "Score": "5", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Python scraping tables" }
197236
<p>I am trying to access data from <a href="https://api.coinmarketcap.com/v2/ticker/" rel="nofollow noreferrer">Coinmarketcap API</a> in Python and came up with the following code:</p> <pre><code>def fetch_coin_prices(**kwargs): """Retrieve cryptocurrency data from CoinMarketCap and return a dictionary containing coin names with their current prices. Keyword arguments to this function are mapped to the CoinMarketCap API, refer to their documentation for their meaning: https://coinmarketcap.com/api/ """ response = requests.get( 'https://api.coinmarketcap.com/v2/ticker/', params=kwargs ) response.raise_for_status() coin_data = response.json() return coin_data.get('data', {}).values() data = fetch_coin_prices(limit=100, start=0, sort='id') </code></pre> <p>I am trying to write this data to a Redis HMSET that accepts a dictionary and I only want the properties 'id', 'name', 'symbol', 'rank', 'price' and 'volume_24h'. The price and volume properties are nested and therefore I haven't found a way to get everything in 1 go. My redis hmset needs to store data in key value form where key is the coin id and value is the CSV of the current coin.</p> <pre><code>hmset = {} fieldnames = ['id', 'name', 'symbol', 'rank' ,'price', 'volume_24h'] for row in data: subset = {} subset['id'] = row.get('id', None) subset['name'] = row.get('name', None) subset['symbol'] = row.get('symbol', None) subset['rank'] = row.get('rank', None) subset['price'] = row.get('quotes', {}).get('USD', {}).get('price', None) subset['volume_24h'] = row.get('quotes', {}).get('USD', {}).get('volume_24h', None) if all([subset[key] for key in subset]): csv_string = io.StringIO() csv_writer = csv.DictWriter(csv_string, fieldnames=fieldnames, extrasaction='ignore' , lineterminator=':') csv_writer.writerows(data_subset) hmset[subset['id']] = csv_string.getvalue() </code></pre> <p>This is what I have come up with so far but it looks very ugly in my opinion to access keys. Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T07:40:40.523", "Id": "380163", "Score": "2", "body": "what do you mean exactly with `The price and volume properties are nested`. please share some example data, and what you expect" }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>The way using <code>dict.get</code> certainly works, but can become a bit unreadable if you need to chain them.</p>\n\n<p>An alternative is to use exception handling in this case.</p>\n\n<pre><code>subset['volume_24h'] = row.get('quotes', {}).get('USD', {}).get('volume_24h', None)\n</code></pre>\n...
{ "AcceptedAnswerId": "197270", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T02:39:16.663", "Id": "197241", "Score": "4", "Tags": [ "python", "python-3.x", "hash-map", "redis" ], "Title": "Accessing a subset of keys from a nested dictionary in Python" }
197241
<p>My team and I are trying to implement a secure API and would appreciate some feedback on the following:</p> <ul> <li><p>If there are areas of improvement in the current code to improve security</p></li> <li><p>Recommendations on other secure API implementations, if any, that would fit our requirements better (see below)</p></li> <li><p>If there are any major loopholes in security based on this module.</p></li> </ul> <p>Here are some requirements, considerations, and caveats:</p> <ul> <li><p>The API clients/consumers are other web apps from our same company (internal yet public facing apps on a different sub-domain)</p></li> <li><p>We'd prefer not to go the OAuth2 route. We'd like this to be a programmatic interface using key-based authentication. Basically, it will be server to server authentication.</p></li> <li><p>API is already https</p></li> </ul> <p>We'd like this to be modular/flexible enough to use across different internal apps</p> <p>Please read code comments. We've gotten inspiration from multiple sources, especially the implementation of JWT in a slightly different manner.</p> <pre><code># Inspiration from: # - https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth # - https://codeburst.io/jwt-to-authenticate-servers-apis-c6e179aa8c4e # Typically, JWT's are used to provide consumer an access token after successful login. # Considering our use case, the consumer (another internal app) will initiate the JWT # Server will verify authenticity of request if it is able to decode JWT # We've also set specific headers that internal apps would need to provide module SecureAPI # Generates a secure payload for outgoing requests def self.secure_payload(options = {}, method = "get") # Get or Post request param_type = method == "get" ? "query" : "body" iat = Time.now.to_i # Reserved and Private claims token_payload = { # The "iat" (issued at) claim identifies the time at which the JWT was issued. iat: iat, # Expiration exp: iat + 60, # Private claim client_id: options[:client_id] } encoded_token = encode_token(token_payload, options[:shared_secret]) payload = { :headers =&gt; { "Authorization" =&gt; "Bearer" + ' ' + encoded_token, "JWT-Consumer" =&gt; options[:client_id] }, param_type.to_sym =&gt; { client_token: options[:client_token] } } payload end # Verifies incoming requests/JWT verifier def self.authenticate_request(request) # Client must provide these headers jwt_token = request.headers['Authorization'].split(' ').last shared_secret = Rails.application.secrets[request.headers['JWT-Consumer']] # Token must be decoded, unexpired, and verified using same hashing algo for successful auth # else will return unauthorized response to client decode_token(jwt_token, shared_secret) end def self.encode_token(payload, secret) JWT.encode payload, secret, 'HS512' end def self.decode_token(token, shared_secret) JWT.decode token, shared_secret, true, algorithm: 'HS512' end end </code></pre> <p></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T04:08:42.200", "Id": "197247", "Score": "3", "Tags": [ "ruby", "security", "ruby-on-rails", "api", "jwt" ], "Title": "Implementing secure API for use between other internal apps" }
197247
<p>I have a live search project and I don't know if it's secure enough or not. I don't access it directly, but I get data by JSON so I shouldn't worry about slashes or quotes, right?</p> <p>The PHP code:</p> <pre><code>&lt;?php if (isset($it_server)) { class search{ public function gettingvalues($search_value){ require_once('db_conx.php'); $dir = "usersimage/"; $search_value = htmlspecialchars($search_value,ENT_QUOTES,'UTF-8'); $sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'"; $query = mysqli_query($conx,$sql); if ($query) { if (mysqli_num_rows($query) &gt; 0) { while ($row = mysqli_fetch_array($query)) { $img = $row['img']; $name = $row['name']; $username = $row['username']; $json = array('img' =&gt; $img, 'name' =&gt; $name, 'username' =&gt; $username); $results[] = $json; } echo json_encode($results); }else{ $json['name'] = ''; $json['img'] = ''; $json['username'] = ''; $json['error'] = 'No results.'; $results[] = $json; echo json_encode($results); } }else{ $json['name'] = ''; $json['img'] = ''; $json['username'] = ''; $json['error'] = "There's a problem, please try later!"; $results[] = $json; echo json_encode($results); } } } }else{ header('location: 404'); die(); } ?&gt; </code></pre> <p>I call the function from index.php:</p> <pre><code>&lt;?php $its_server = 'yes'; if (isset($_POST['data'])) { require('search.php'); $search = new search; $search-&gt;gettingvalues($_POST['data']); header('Content-Type: application/json; charset=utf-8'); die(); } ?&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $('input').keyup(function(){ var value= $('input').val(); $.ajax({ type: "POST", url: "", data: {data: value}, datatype: "json", success: function(json_data) { var img = []; var username = []; var name = []; var html = ''; $.each(json_data, function(index, e) { if (e.error) { html += `${e.error}`; }else{ html += `${e.name} ${e.username} ${e.img}&lt;br&gt;`; } }) $("#feedback").html(html); } }) }); }); &lt;/script&gt; &lt;input type="text" name="search" placeholder="looking for?"&gt; &lt;div id="feedback"&gt;&lt;/div&gt; </code></pre> <p>I don't know if I'm doing well with security or not and it's a big deal to me. So what you see from 1-10, how secure is my page?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T08:28:55.790", "Id": "380175", "Score": "0", "body": "It makes me wonder where did you get the idea that JSON is *any* related to SQL. This statement is like \"I washed my hands, so I can go cross a road anywhere, no car will hit me...
[ { "body": "<p>One quite big security issue I see here is your vulnerability to SQL-Injection attacks. Even when you use <code>htmlspecialchars()</code>, there are still some ways to circumvent it, as shown in <a href=\"//stackoverflow.com/a/22117157\"><em>Is <code>htmlspecialchars</code> enough to prevent an SQ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T05:47:03.983", "Id": "197252", "Score": "1", "Tags": [ "php", "json", "ajax" ], "Title": "Live search project" }
197252
<p>Exercise: Checking if a sentence is considered valid under the following conditions:</p> <ul> <li>Numbers less than 13 are only allowed in their written form, e.g "twelve", but "14" is considered valid.</li> <li>Only 1 period marker is allowed and it must be the final character</li> <li>First letter must be uppercase</li> <li>number of quotation marks in the sentence must be even</li> </ul> <p>if the sentence meets all above criteria, it is considered valid.</p> <p>Here is my approach:</p> <pre><code>public class SentenceValidator implements ValidatesSentences { private static final int MINIMUM_ALLOWED_NUMBER = 13; public SentenceValidator() { //default (auto-generated without explicit declaration anyway) } /** * Takes a string sentence and returns if it meets the requirements * @param sentence -&gt; The string sentence to analyze for validity * @return boolean -&gt; if the string meets the validation requirements */ @Override public final boolean isSentenceConsideredValid(String sentence) { String temporary = guardTheSentence(sentence); return temporary.length() &gt; 1 &amp;&amp; areConditionsValid(temporary); } private boolean areConditionsValid(String sentence) { return isTheFirstCharacterAnUppercaseLetter(sentence) &amp;&amp; isTheCountOfQuotationMarksEven(sentence) &amp;&amp; isTheOnlyPeriodMarkTheLastCharacterOfTheSentence(sentence) &amp;&amp; isTheLowestNumberInTheSentenceGreaterThan13(sentence); } private String guardTheSentence(String sentence) { Objects.requireNonNull(sentence, "null is not an acceptable value"); return sentence.trim(); } private boolean isTheFirstCharacterAnUppercaseLetter(String sentence) { return Character.isLetter(sentence.charAt(0)) &amp;&amp; sentence.charAt(0) == sentence.toUpperCase().charAt(0); } private boolean isTheCountOfQuotationMarksEven(String sentence) { return (retrieveCountOfAGivenCharacter(sentence,'"') % 2) == 0; } private boolean isTheOnlyPeriodMarkTheLastCharacterOfTheSentence(String sentence) { return sentence.charAt(sentence.length() - 1) == '.' &amp;&amp; retrieveCountOfAGivenCharacter(sentence,'.') == 1; } private int retrieveCountOfAGivenCharacter(String sentence, Character charToCount) { int counter = 0; for (char c : sentence.toCharArray()) { if (c == charToCount) { counter++; } } return counter; } /** * We don't need really need to care about words for the numbers, that is trivial All we want to * check is for all numeric value(s) within the string and ensure none are below 13 * supports negative numbers using the optional (?:-) */ private boolean isTheLowestNumberInTheSentenceGreaterThan13(String sentence) { String temp = sentence.replaceAll("[^-?0-9]+", " "); temp = temp.trim(); if (temp.isEmpty()) { return true; } int lowestNumber = MINIMUM_ALLOWED_NUMBER; for (String number : temp.split(" ")) { lowestNumber = Math.min(lowestNumber, Integer.parseInt(number)); } return lowestNumber &gt;= MINIMUM_ALLOWED_NUMBER; } } public interface ValidatesSentences { boolean isSentenceConsideredValid(String sentence); } </code></pre> <p>A jump out problem I see already is the NumberFormatException when number is greater than a max int, I should use a long/Big Integer there and handle a NumberFormatException.</p>
[]
[ { "body": "<p>What you have here is a series of boolean-result conditions that you want to apply to a given String.</p>\n\n<ol>\n<li><p>The design can be expanded to allow <code>List</code> of conditions to be applied. This way you can add or remove conditions with minumal changes.</p></li>\n<li><p>You can lev...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T07:27:31.850", "Id": "197258", "Score": "2", "Tags": [ "java" ], "Title": "Checking if a sentence is considered valid" }
197258
<p>I'm using 1.8.0_162 version of Java and here is my task about stream framework</p> <pre><code>Map&lt;String, BigDecimal&gt; paymentAmountInfoMap = serviceResponse .getPayments() .stream() .collect(Collectors.groupingBy(x -&gt; String.valueOf(x.getDueDate().getYear()))) .entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -&gt; e.getValue() .stream() .map(ConsumerPolicyPayment::getPaymentAmount) .collect(Collectors.toList()).stream() .reduce(BigDecimal.ZERO, BigDecimal::add))); </code></pre> <p>and here is my serviceResponse object:</p> <pre><code> { "payments": [ { "paymentDate": { "dateValue": "2018-01-02", "formattedValue": "02 Ocak 2018" }, "dueDate": { "dateValue": "2018-01-24", "formattedValue": "24 Ocak 2018" }, "paymentAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "receiptNo": "7520387", "expectedAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "investmentDate": { "dateValue": null, "formattedValue": null }, "investmentAmount": { "numberValue": null, "formattedValue": null, "numberValueInUsd": null, "formattedValueInUsd": null }, "presentValue": { "numberValue": null, "formattedValue": null, "numberValueInUsd": null, "formattedValueInUsd": null }, "valueIncreaseRatio": null }, { "paymentDate": { "dateValue": "2017-12-01", "formattedValue": "01 Aralık 2017" }, "dueDate": { "dateValue": "2017-12-24", "formattedValue": "24 Aralık 2017" }, "paymentAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "receiptNo": "7440108", "expectedAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "investmentDate": { "dateValue": "2018-01-08", "formattedValue": "08 Ocak 2018" }, "investmentAmount": { "numberValue": 252.53, "formattedValue": "253", "numberValueInUsd": 56.46, "formattedValueInUsd": "57" }, "presentValue": { "numberValue": 194.58, "formattedValue": "195", "numberValueInUsd": 43.51, "formattedValueInUsd": "44" }, "valueIncreaseRatio": -0.2295 }, { "paymentDate": { "dateValue": "2017-11-01", "formattedValue": "01 Kasım 2017" }, "dueDate": { "dateValue": "2017-11-24", "formattedValue": "24 Kasım 2017" }, "paymentAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "receiptNo": "7362663", "expectedAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "investmentDate": { "dateValue": "2017-12-11", "formattedValue": "11 Aralık 2017" }, "investmentAmount": { "numberValue": 252.53, "formattedValue": "253", "numberValueInUsd": 56.46, "formattedValueInUsd": "57" }, "presentValue": { "numberValue": 197.74, "formattedValue": "198", "numberValueInUsd": 44.21, "formattedValueInUsd": "45" }, "valueIncreaseRatio": -0.2169 }, { "paymentDate": { "dateValue": "2017-10-02", "formattedValue": "02 Ekim 2017" }, "dueDate": { "dateValue": "2017-10-24", "formattedValue": "24 Ekim 2017" }, "paymentAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "receiptNo": "7285959", "expectedAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "investmentDate": { "dateValue": "2017-11-09", "formattedValue": "09 Kasım 2017" }, "investmentAmount": { "numberValue": 252.53, "formattedValue": "253", "numberValueInUsd": 56.46, "formattedValueInUsd": "57" }, "presentValue": { "numberValue": 197.83, "formattedValue": "198", "numberValueInUsd": 44.23, "formattedValueInUsd": "45" }, "valueIncreaseRatio": -0.2166 }, { "paymentDate": { "dateValue": "2017-09-05", "formattedValue": "05 Eylül 2017" }, "dueDate": { "dateValue": "2017-09-24", "formattedValue": "24 Eylül 2017" }, "paymentAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "receiptNo": "7212680", "expectedAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "investmentDate": { "dateValue": "2017-10-13", "formattedValue": "13 Ekim 2017" }, "investmentAmount": { "numberValue": 252.53, "formattedValue": "253", "numberValueInUsd": 56.46, "formattedValueInUsd": "57" }, "presentValue": { "numberValue": 199.99, "formattedValue": "200", "numberValueInUsd": 44.72, "formattedValueInUsd": "45" }, "valueIncreaseRatio": -0.2081 }, { "paymentDate": { "dateValue": "2017-08-01", "formattedValue": "01 Ağustos 2017" }, "dueDate": { "dateValue": "2017-08-24", "formattedValue": "24 Ağustos 2017" }, "paymentAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "receiptNo": "7137982", "expectedAmount": { "numberValue": 273, "formattedValue": "273", "numberValueInUsd": 61.04, "formattedValueInUsd": "62" }, "investmentDate": { "dateValue": "2017-09-08", "formattedValue": "08 Eylül 2017" }, "investmentAmount": { "numberValue": 252.53, "formattedValue": "253", "numberValueInUsd": 56.46, "formattedValueInUsd": "57" }, "presentValue": { "numberValue": 202.18, "formattedValue": "203", "numberValueInUsd": 45.21, "formattedValueInUsd": "46" }, "valueIncreaseRatio": -0.1994 }, { "paymentDate": { "dateValue": "2017-07-03", "formattedValue": "03 Temmuz 2017" }, "dueDate": { "dateValue": "2017-07-24", "formattedValue": "24 Temmuz 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "7060723", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-08-10", "formattedValue": "10 Ağustos 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 190.89, "formattedValue": "191", "numberValueInUsd": 42.68, "formattedValueInUsd": "43" }, "valueIncreaseRatio": -0.1907 }, { "paymentDate": { "dateValue": "2017-06-01", "formattedValue": "01 Haziran 2017" }, "dueDate": { "dateValue": "2017-06-24", "formattedValue": "24 Haziran 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "6992100", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-07-10", "formattedValue": "10 Temmuz 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 193.34, "formattedValue": "194", "numberValueInUsd": 43.23, "formattedValueInUsd": "44" }, "valueIncreaseRatio": -0.1803 }, { "paymentDate": { "dateValue": "2017-05-02", "formattedValue": "02 Mayıs 2017" }, "dueDate": { "dateValue": "2017-05-24", "formattedValue": "24 Mayıs 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "6919784", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-06-09", "formattedValue": "09 Haziran 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 195.61, "formattedValue": "196", "numberValueInUsd": 43.74, "formattedValueInUsd": "44" }, "valueIncreaseRatio": -0.1707 }, { "paymentDate": { "dateValue": "2017-04-03", "formattedValue": "03 Nisan 2017" }, "dueDate": { "dateValue": "2017-04-24", "formattedValue": "24 Nisan 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "6848263", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-05-15", "formattedValue": "15 Mayıs 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 197.19, "formattedValue": "198", "numberValueInUsd": 44.09, "formattedValueInUsd": "45" }, "valueIncreaseRatio": -0.164 }, { "paymentDate": { "dateValue": "2017-03-01", "formattedValue": "01 Mart 2017" }, "dueDate": { "dateValue": "2017-03-24", "formattedValue": "24 Mart 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "6776034", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-04-10", "formattedValue": "10 Nisan 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 199.45, "formattedValue": "200", "numberValueInUsd": 44.6, "formattedValueInUsd": "45" }, "valueIncreaseRatio": -0.1544 }, { "paymentDate": { "dateValue": "2017-02-01", "formattedValue": "01 Şubat 2017" }, "dueDate": { "dateValue": "2017-02-24", "formattedValue": "24 Şubat 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "6707743", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-03-13", "formattedValue": "13 Mart 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 201.38, "formattedValue": "202", "numberValueInUsd": 45.03, "formattedValueInUsd": "46" }, "valueIncreaseRatio": -0.1462 }, { "paymentDate": { "dateValue": "2017-01-02", "formattedValue": "02 Ocak 2017" }, "dueDate": { "dateValue": "2017-01-24", "formattedValue": "24 Ocak 2017" }, "paymentAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "receiptNo": "6637517", "expectedAmount": { "numberValue": 255, "formattedValue": "255", "numberValueInUsd": 57.01, "formattedValueInUsd": "58" }, "investmentDate": { "dateValue": "2017-02-13", "formattedValue": "13 Şubat 2017" }, "investmentAmount": { "numberValue": 235.88, "formattedValue": "236", "numberValueInUsd": 52.74, "formattedValueInUsd": "53" }, "presentValue": { "numberValue": 203.35, "formattedValue": "204", "numberValueInUsd": 45.47, "formattedValueInUsd": "46" }, "valueIncreaseRatio": -0.1379 } ], "repayments": [], "graphData": { "payments": { "2017": 3150, "2018": 273 }, "repayments": {} }, "totalPaymentAmount": { "numberValue": 3423, "formattedValue": "3.423", "numberValueInUsd": 765.28, "formattedValueInUsd": "766" }, "totalInvestmentAmount": { "numberValue": 2913.81, "formattedValue": "2.914", "numberValueInUsd": 651.44, "formattedValueInUsd": "652" }, "totalPresentValue": { "numberValue": 2373.53, "formattedValue": "2.374", "numberValueInUsd": 530.65, "formattedValueInUsd": "531" }, "remainingInstallmentCount": 54, "lastPaymentDate": { "dateValue": "2018-01-24", "formattedValue": "24 Ocak 2018" }, "nearestPaymentDate": { "dateValue": "2018-02-24", "formattedValue": "24 Şubat 2018" } } </code></pre> <p>What I want to achieve is like that:</p> <pre><code>{ "2017":432,45, "2018":25,1, "2019":3566,4 } </code></pre> <p>It is working but not the best practice.</p>
[]
[ { "body": "<p>You may extract out different parts of the code as methods like so:</p>\n\n<pre><code> Map&lt;String, BigDecimal&gt; paymentAmountInfoMap = \n serviceResponse.getAllPaymentsPerYearEntrySet()\n .stream()\n .collect(Collectors.toMap(Map.Entry::getKey, e -...
{ "AcceptedAnswerId": "197776", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T10:29:25.817", "Id": "197268", "Score": "2", "Tags": [ "java", "datetime", "collections", "stream" ], "Title": "Summing payments by year using Java Streams" }
197268
<p>After implementing suggestions from my previous <a href="https://codereview.stackexchange.com/questions/197076/shortest-job-first-preemptive/197177#197177">question</a> and after modifying I have written this code. Function <code>sortAccordingArrivalTime()</code> sorts <code>arrivalTime</code> <code>burstTime</code> and <code>priority</code> according to arrival time. I have tried to enter Arrival Time, Burst Time and Priority in respective order for each process at a time. Help me to improve this code and optimize it with more use of C++11 and C++14.</p> <p>scheduling.h</p> <pre><code>#ifndef SCHEDULING_H_ #define SCHEDULING_H_ #include &lt;vector&gt; using uint = unsigned int; class Scheduling { uint currActiveProcessID; uint timeCounter = 0; double avgWaitingTime; double avgTurnAroundTime; std::vector&lt;uint&gt; arrivalTime; //When process start to execute std::vector&lt;uint&gt; burstTime; //process wait to execute after they have arrived std::vector&lt;uint&gt; waitingTime; //total time taken by processes std::vector&lt;uint&gt; turnArountTime; public: Scheduling(uint num = 0); Scheduling(const Scheduling&amp;) = delete; Scheduling &amp;operator=(const Scheduling&amp;) = delete; Scheduling(Scheduling&amp;&amp;) = delete; Scheduling &amp;operator=(Scheduling&amp;&amp;) = delete; ~Scheduling() = default; void calcWaitingTime(); void calcTurnAroundTime(); void printInfo(); private: void sortAccordingArrivalTime(); }; #endif </code></pre> <p>priority.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::find #include &lt;iterator&gt; // std::begin, std::end #include &lt;limits&gt; //std::numeric_limits #include "scheduling.h" using uint = unsigned int; std::vector&lt;uint&gt; priority; Scheduling::Scheduling(uint n): waitingTime(n, 0) { arrivalTime.reserve(n); burstTime.reserve(n); waitingTime.reserve(n); turnArountTime.reserve(n); priority.reserve(n); std::cout &lt;&lt; "Enter Arrival Time, Burst Time, Priority in respective "; std::cout &lt;&lt; "order (eg 2 15 4)\n"; std::cout &lt;&lt; "Lower integer has higher priority"; for (uint i = 0; i &lt; n; i++) { uint arrivalVal, burstVal, priorityVal; std::cout &lt;&lt; "\nProcess " &lt;&lt; i+1 &lt;&lt; ": "; std::cin &gt;&gt; arrivalVal &gt;&gt; burstVal &gt;&gt; priorityVal; arrivalTime.push_back(arrivalVal); burstTime.push_back(burstVal); priority.push_back(priorityVal); } } void Scheduling::sortAccordingArrivalTime() { for (std::size_t i = 0; i &lt; arrivalTime.size(); i++) { for (std::size_t j = i+1; j &lt; arrivalTime.size(); j++) { if (arrivalTime[i] &gt; arrivalTime[j]) { uint temp = arrivalTime[i]; arrivalTime[i] = arrivalTime[j]; arrivalTime[j] = temp; temp = burstTime[i]; burstTime[i] = burstTime[j]; burstTime[j] = temp; temp = priority[i]; priority[i] = priority[j]; priority[j] = temp; } } } } void Scheduling::calcWaitingTime() { std::vector&lt;uint&gt; burstTimeCopy; std::copy(burstTime.begin(), burstTime.end(), std::back_inserter(burstTimeCopy)); //If entered arrival time are not sorted if (! (std::is_sorted(arrivalTime.begin(), arrivalTime.end())) ) { sortAccordingArrivalTime(); } while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(), [] (uint e) { return e == 0; }))) { auto maxArrivalTime = std::max_element(arrivalTime.begin(), arrivalTime.end()); if (timeCounter &lt;= *maxArrivalTime) { uint maxPriority = std::numeric_limits&lt;uint&gt;::max(); for (std::size_t i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; priority[i] &lt; maxPriority &amp;&amp; arrivalTime[i] &lt;= timeCounter) { maxPriority = priority[i]; currActiveProcessID = i; } } burstTimeCopy[currActiveProcessID] -= 1; for (std::size_t i = 0; i &lt; burstTimeCopy.size(); i++) { if (timeCounter &gt;= arrivalTime[i] &amp;&amp; i != currActiveProcessID &amp;&amp; burstTimeCopy[i] != 0) { waitingTime[i] += 1; } } timeCounter++; } else { uint maxPriority = std::numeric_limits&lt;uint&gt;::max(); for (std::size_t i = 0 ; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; priority[i] &lt; maxPriority) { maxPriority = priority[i]; currActiveProcessID = i; } } for (std::size_t i = 0; i &lt; burstTimeCopy.size(); i++) { if (i != currActiveProcessID &amp;&amp; burstTimeCopy[i] != 0) { waitingTime[i] += burstTimeCopy[currActiveProcessID]; } } timeCounter += burstTimeCopy[currActiveProcessID]; burstTimeCopy[currActiveProcessID] = 0; } } uint sum = 0; for (auto element: waitingTime) { sum += element; } avgWaitingTime = sum / waitingTime.size(); } void Scheduling::calcTurnAroundTime() { uint sum = 0; for (std::size_t i = 0; i &lt; arrivalTime.size(); i++) { uint val = burstTime[i] + waitingTime[i]; turnArountTime.push_back(val); sum += val; } avgTurnAroundTime = sum / turnArountTime.size(); } void Scheduling::printInfo() { std::cout &lt;&lt; "ProcessID\tArrival Time\tBurst Time\tPriority\tWaiting Time"; std::cout &lt;&lt; "\tTurnaround Time\n"; for (std::size_t i = 0; i &lt; arrivalTime.size(); i++) { std::cout &lt;&lt; i+1 &lt;&lt; "\t\t" &lt;&lt; arrivalTime[i] &lt;&lt; "\t\t" &lt;&lt; burstTime[i]; std::cout &lt;&lt; "\t\t" &lt;&lt; priority[i] &lt;&lt; "\t\t" &lt;&lt; waitingTime[i]; std::cout &lt;&lt; "\t\t" &lt;&lt; turnArountTime[i] &lt;&lt; '\n'; } std::cout &lt;&lt; "Average Waiting Time : " &lt;&lt; avgWaitingTime &lt;&lt; '\n'; std::cout &lt;&lt; "Average Turn Around Time : " &lt;&lt; avgTurnAroundTime &lt;&lt; '\n'; } int main() { int num; std::cout &lt;&lt; "Enter the number of processes\n"; std::cin &gt;&gt; num; Scheduling prioritySchedule(num); prioritySchedule.calcWaitingTime(); prioritySchedule.calcTurnAroundTime(); prioritySchedule.printInfo(); } </code></pre>
[]
[ { "body": "<p>A few things I noticed:</p>\n\n<p>the standard library includes a <code>swap</code> function I would suggest using it or at least put the swap algorithm in its own function.</p>\n\n<p>Instead of synchronized collections, it would simplify and increase maintainability to have an embedded class to h...
{ "AcceptedAnswerId": "197325", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T10:43:23.390", "Id": "197269", "Score": "1", "Tags": [ "c++", "c++11" ], "Title": "Priority Scheduling Algorithm Preemptive" }
197269
<p>The following is code that I used to do a task. the code runs fine but takes over 2 minutes to get executed. And this is with only one rule (Rule_1), the rule is checked using an .exe ( written in CPP).Actually there are many CSV files that are needed to pass through the rules.</p> <p>My question is will the program always use this much amount of time, because I have to implement more the 50 rule for the files, or there is any other way around?</p> <pre><code>import os import fnmatch import subprocess import xml.etree.ElementTree as ElementTree from xml.parsers.expat import ExpatError import sys from shutil import copyfileobj def locate(pattern, root="Z:/Automation/"): '''Locate all files matching supplied filename pattern in and below supplied root directory.''' for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename) csv_path_unrefined = [] for xml in locate("*.csv"): try: ElementTree.parse(xml) except (SyntaxError, ExpatError): csv_path_unrefined.append(xml) csv_path = [] for paths in csv_path_unrefined: if "results" in str(paths): csv_path.append(paths) def check_rule1(path): # path = "PWLLOGGER_DEMO.csv" file = 'ConsoleApplication9.exe "' + path + '"' # print(file) details = os.popen(file).read() log_file = open("logs/Rule_1.txt") state = log_file.read() with open('results/Rule_1_log.log', 'a+') as files: files.write("\n========" + path + "========\n") files.close with open('results/Rule_1_log.log', 'a+') as output, open('logs/Rule_1.txt', 'r') as input: copyfileobj(input, output) if "failed" in state: return False else: return True rule_1_passed = [] rule_1_failed = [] for paths in csv_path: result_r1 = check_rule1(paths) # print(result_r1) if result_r1 == False: rule_1_failed.append(paths) #print("Rule 1 has failed for " + paths) elif result_r1 == True: rule_1_passed.append(paths) #print("Rule 1 has passed for " + paths) open('logs/Rule_1.txt', 'w').close() print(rule_1_failed) print(rule_1_passed) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:22:27.627", "Id": "380191", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state...
[ { "body": "<p>Really, to answer your question, you need to profile your code. You need to understand what is taking up all that time. Just by looking at your code, it's impossible to tell, but my guess would be that the most time is spent in one of the following places:</p>\n\n<ul>\n<li><p>Running every <code>*...
{ "AcceptedAnswerId": "197317", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:05:54.257", "Id": "197271", "Score": "0", "Tags": [ "python" ], "Title": "Reducing execution time for a python program" }
197271
<p>I have the following command bonded to my button, It's supposed detect the current used theme and change it (Dark or Light).</p> <pre><code> var existingResourceDictionary = Application.Current.Resources.MergedDictionaries .Where(rd =&gt; rd.Source != null) .SingleOrDefault(rd =&gt; Regex.Match(rd.Source.OriginalString, @"(\/MaterialDesignThemes.Wpf;component\/Themes\/MaterialDesignTheme\.)((Light)|(Dark))").Success); if (existingResourceDictionary == null) throw new ApplicationException("Unable to find Light/Dark base theme in Application resources."); if (existingResourceDictionary.Source.ToString().Contains("Light")) { Settings.Default.Theme = true; Settings.Default.Save(); } else { Settings.Default.Theme = false; Settings.Default.Save(); } var source = $"pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.{(Settings.Default.Theme ? "Dark" : "Light")}.xaml"; var newResourceDictionary = new ResourceDictionary() { Source = new Uri(source) }; Application.Current.Resources.MergedDictionaries.Remove(existingResourceDictionary); Application.Current.Resources.MergedDictionaries.Add(newResourceDictionary); </code></pre> <p>and in the ViewModel (when I run the application) It should detect the last changes made with the button above and apply the theme. I'm basically getting the value from the Settings that I changed above: </p> <pre><code> var existingResourceDictionary = Application.Current.Resources.MergedDictionaries .Where(rd =&gt; rd.Source != null) .SingleOrDefault(rd =&gt; Regex.Match(rd.Source.OriginalString, @"(\/MaterialDesignThemes.Wpf;component\/Themes\/MaterialDesignTheme\.)((Light)|(Dark))").Success); if (existingResourceDictionary == null) throw new ApplicationException("Unable to find Light/Dark base theme in Application resources."); var source = $"pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.{(Settings.Default.Theme ? "Dark" : "Light")}.xaml"; var newResourceDictionary = new ResourceDictionary() { Source = new Uri(source) }; Application.Current.Resources.MergedDictionaries.Remove(existingResourceDictionary); Application.Current.Resources.MergedDictionaries.Add(newResourceDictionary); </code></pre> <p>The code is working fine but I feel like I could make it less repetitive and shorter?</p>
[]
[ { "body": "<p>You can substitute</p>\n\n<blockquote>\n<pre><code>if (existingResourceDictionary.Source.ToString().Contains(\"Light\"))\n{\n Settings.Default.Theme = true;\n Settings.Default.Save();\n}\nelse\n{\n Settings.Default.Theme = false;\n Settings.Default.Save();\n}\n</code></pre>\n</blockquo...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:31:53.837", "Id": "197272", "Score": "0", "Tags": [ "c#", "wpf", "mvvm" ], "Title": "Saving ResourceDictionary theme" }
197272
<p>To train my Python skills I have made a vocabulary trainer which runs on a terminal:</p> <pre><code>import random import os import sys FILE_PATH = "./words.txt" class Entry: def __init__(self, french, english): self.french = french self.english = english entries = [] if os.path.isfile(FILE_PATH): words = open(FILE_PATH, "r") for line in words: words = line.split(",") entries.append(Entry(words[0].strip(), words[1].strip())) def insert(): while True: french = raw_input("French word: ") if french == "#": return english = raw_input("English word: ") if english == "#": return entries.append(Entry(french, english)) backup_wordpairs() def query(): total = 0 right = 0 wrong = 0 while True: i = random.randint(0, len(entries) - 1) french = raw_input("French translation of " + entries[i].english + ": ") # TODO: Add a statistics which is displayed before leaving (x of y correct. Equal z percent). if french == "#": percentage = (right * 100) / total print("You answered " + str(right) + " question out of " + str(total) + " correct.") print("Percentage: " + str(percentage) + " %") return total = total + 1 if french.strip() == entries[i].french.strip(): print("Correct.") right = right + 1 else: print("Wrong!") wrong = wrong + 1 def printall(): if len(entries) == 0: print("No words stored.") return for i in range(len(entries)): print(entries[i].french + " : " + entries[i].english) def backup_wordpairs(): woerter = open(FILE_PATH, 'w') for wort_paar in entries: woerter.write(wort_paar.french + "," + wort_paar.english + "\n") woerter.close() def reset_list(): global entries entries = [] if os.path.isfile(FILE_PATH): os.remove(FILE_PATH) while True: command = raw_input("Please enter a command: ") if command == "add": insert() elif command == "test": query() elif command == "list": printall() elif command == "end": break elif command == "reset": reset_list() else: print("No known command.") print(" ------- Vocabulary becomes terminated. ---------- ") sys.exit() </code></pre> <p>My <a href="https://github.com/mizech/vocabulary-trainer/tree/98e47f84d1df752196589afd270ffaab70b4ad2b" rel="nofollow noreferrer">GitHub repository</a> (including a README-file with user-instructions and a screenshot).</p> <p>The application runs fine but I would appreciate feedback from more experienced Python-developers. What would you have done differently and why?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T05:08:45.130", "Id": "380341", "Score": "0", "body": "This can't be [tag:python-3.x], since you used `raw_input()`. I have retagged the question as [tag:python-2.x]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate"...
[ { "body": "<p>Currently your code is all over the place. You have global variables (which should be named in <code>ALL_CAPS</code> according to Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>), functions which modify these globals, then s...
{ "AcceptedAnswerId": "197278", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:34:11.900", "Id": "197273", "Score": "8", "Tags": [ "python", "python-2.x", "quiz" ], "Title": "Python vocabulary trainer for terminal" }
197273
<p>As in many teams, me and my coworkers are putting ticket number into beginning of each commit message. If your branches are starting with ticket number it is easy to create <code>prepare-commit-msg</code> hook to automate this action, and since I'm a front-end deveoper, I decided to write it as a nodejs script. Look at what I came up with and tell me how to make it better if you will.</p> <pre class="lang-js prettyprint-override"><code>#.git/hooks/prepare-commit-msg #!/usr/bin/env node const fs = require('fs') const { exec } = require('child_process') const COMMIT_EDITMSG = process.argv[2] exec('git symbolic-ref --short HEAD', (err, stdout) =&gt; { if (err) throw err fs.readFile( COMMIT_EDITMSG, 'utf8', (err, message) =&gt; { if (err) throw err fs.writeFile( COMMIT_EDITMSG, `${stdout.replace(/(-|_).*/, '')} ${message}`.replace(/\n/, ''), err =&gt; { if (err) throw err } ) } ) }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T00:09:31.380", "Id": "380492", "Score": "0", "body": "You most definitely want to be using `return console.error(...)` in all those error scenarios :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T0...
[ { "body": "<p>Outwith the improved error handling as per the comments, another improvement on this be to write the hook using a more synchronous approach e.g.</p>\n\n<pre><code>#.git/hooks/prepare-commit-msg\n#!/usr/bin/env node\n\nconst { readFileSync, writeFileSync } = require('fs')\nconst { execSync } = requ...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T11:51:48.173", "Id": "197275", "Score": "0", "Tags": [ "javascript", "node.js", "file-system", "git" ], "Title": "Git hook written on JavaScript" }
197275
<p>This is my naive approach:</p> <pre><code>$sample1 = [3, -20, 1, -19, -4, 6, 77, -1, 0, 6]; $sample3 = [4, 5, -7, 0, 2, 44, -3, -5, 66, -7]; $sample4 = [4, 25, 1, 6, 9, 5, 999, 4, 43, 2]; $sample2 = []; for ($i = 0; $i &lt; mt_rand(10, 30); $i++) { $sample2[] = mt_rand(-1000, 1000); } extractNumbersThatSquaresAreGreaterThan($sample1); extractNumbersThatSquaresAreGreaterThan($sample2); extractNumbersThatSquaresAreGreaterThan($sample3); extractNumbersThatSquaresAreGreaterThan($sample4); var_dump($sample1); //var_dump($sample2); var_dump($sample3); var_dump($sample4); function extractNumbersThatSquaresAreGreaterThan(&amp;$list, $boundary = 26) { foreach ($list as $key =&gt; $value) { if (pow($value, 2) &lt;= $boundary) { unset($list[$key]); } } } </code></pre> <p>Any hints for optimization? Is it possible, I've tried few, but in the end it was more complicated (and slower) solution</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T12:39:49.650", "Id": "380205", "Score": "0", "body": "Please fix the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T13:13:22.183", "Id": "380213", "Score": "0", "body": "@YourCommonS...
[ { "body": "<p>Hints? Ok. </p>\n\n<ol>\n<li><p>Don’t square the values, O(n), instead square-root the boundary. You’ll need an <code>or</code> in your test, though.</p></li>\n<li><p>Don’t <code>unset</code> values in the list. That requires shifting values in memory. Make a new list of same size, fill in val...
{ "AcceptedAnswerId": "197285", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T12:00:22.733", "Id": "197276", "Score": "1", "Tags": [ "php", "algorithm", "array" ], "Title": "PHP function to extract numbers from the list whose squares are exceed some threshold" }
197276
<p>I've posted the code for the following question. What could be improved?</p> <blockquote> <p>Q: Write a program that allows the user to type in a phrase and then outputs the acronym for that phrase.</p> <p>Note: The acronym should be all uppercase, even if the words in the phrase are not capitalized.</p> </blockquote> <pre><code>def main(): ## input the phrase phrase = input("Enter the phrase: ") ## split the phrase into substrings phrase_split = phrase.split() acronym = "" ## iterate through every substring for i in phrase_split: acronym = acronym + i[0].upper() print("The acronym for your phrase is ",acronym + ".") main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T16:13:57.913", "Id": "380241", "Score": "0", "body": "What would be – and what _should_ be – an acronym for a phrase with part in parentheses (or in dashes), like this one?" }, { "ContentLicense": "CC BY-SA 4.0", "Creati...
[ { "body": "<ol>\n<li>You should name your function more descriptively, maybe <code>acronym</code>.</li>\n<li>You should wrap your code under a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code></a> guard to allow importing parts of your scr...
{ "AcceptedAnswerId": "197282", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T12:52:42.990", "Id": "197281", "Score": "11", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Generate acronym from phrase" }
197281
<p>I am diving into Data Analysis with pandas, and I have just written this Python script to calculate the average of hotel review scores of each country. The dataset contains an individual average score for each customer review, like: 8.86 or 7.95. My goal was to average all these individual scores for a particular country. </p> <p>For example, if the hotels in United Kingdom got the following hotel review scores: 8.65, 7.89, 4.35, and 6.98, I would average these four scores and create a dataframe where the first column is "Country" and the second column is the "Overall Average Score" for that country.</p> <p>I tried to write a concise code as much as I could. Would you mind giving your opinions and recommendations about it? I'll be adding this to my portfolio. What should be kept and/or avoided in a professional and real-world setting?</p> <p>Script:</p> <pre><code># Average all scores that belong to a particular country. import pandas as pd # Reading original hotel reviews dataset. df = pd.read_csv(DATASET_PATH) # Getting a dataframe with two columns: 'Hotel_Address' and 'Average_Score'. df = df.loc[:, ["Hotel_Address", "Average_Score"]] # List of tuples. countries_w_avg_list = [] for _, row in df.iterrows(): address = row[0].split() country_name = address[len(address) - 1] countries_w_avg_list.append( (country_name, row[1]) ) # Getting the sum of all 'Average_Score' values for each country. d = {} # Empty dictionary. It will be a dictionary with list values, like: {"Netherlands": [sum, counter]} counter = 0 for country, individual_average in countries_w_avg_list: if country not in d: d[country] = [0, 0] d[country][0] += individual_average d[country][1] += 1 # Getting the average of all 'Average_Score' values for each country. for key, value in d.items(): d[key] = round((d[key][0] / d[key][1]), 2) # print(d) # Now, I believe there are two ways to transform this dictionary in the df I want. # 1 - Transform d in a df, and then transpose it. Then rename the columns. # 2 - Create a dataframe with the column names "Country" and "Overall Average Score" # and their values as d's keys as the value for the first column and d's values as the # values for the second column. df = pd.DataFrame({"Country": list(d.keys()), "Overall Average Score": list(d.values())}) print(df) </code></pre>
[]
[ { "body": "<p>You should probably use <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html\" rel=\"nofollow noreferrer\"><code>pandas.DataFrame.groupby</code></a>.</p>\n\n<p>The string manipulations to extract the countries can also be simplified using <a href=\"https:/...
{ "AcceptedAnswerId": "197286", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T13:28:35.800", "Id": "197283", "Score": "3", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Getting the average score for hotel scores in different countries using pandas" }
197283
<p>I have the following program that opens a Word document template using the OpenXML library and replaces a couple of phrases with their counterparts from what will be a database (right now its just dummy data). Something about the if-else struture in the nested <code>foreach</code> loops bothers me. Is there a better way I can accomplish this task? Would regular expressions be a more viable option?</p> <pre><code>using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; namespace OpenXmlSearchExample { class Program { static void Main(string[] args) { string templatePath = @"C:\users\example\desktop\template.dotx"; string resultPath = @"C:\users\example\desktop\OpenXmlExample.docx"; using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(templatePath)) { var body = document.MainDocumentPart.Document.Body; var paragraphs = body.Elements&lt;Paragraph&gt;(); // Iterate through paragraphs, runs, and text, finding the text we want and replacing it foreach (Paragraph paragraph in paragraphs) { foreach (Run run in paragraph.Elements&lt;Run&gt;()) { foreach (Text text in run.Elements&lt;Text&gt;()) { if (text.Text == "Plan") { text.Text = string.Format("{0} {1} Plan", DateTime.Now.Year, "Q2"); } else if (text.Text == "Project Name") { text.Text = "SUPER SECRET CODE NAME"; } else if (text.Text == "WO-nnnn Name") { text.Text = "Maintenance"; } else { Console.WriteLine(text.Text); Console.ReadKey(); } } } } // Save result document, not modifying the template document.SaveAs(resultPath); } } } } </code></pre>
[]
[ { "body": "<p>You can</p>\n\n<ul>\n<li>replace inner <code>foreach</code> loops with LINQ</li>\n<li>replace <code>if-else</code> with <code>switch</code></li>\n<li>replace <code>string.Format</code> with string interpolation</li>\n<li>add <code>const</code> modifier for path variables if they will be constants<...
{ "AcceptedAnswerId": "197289", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T13:29:25.197", "Id": "197284", "Score": "6", "Tags": [ "c#", "ms-word" ], "Title": "Modifying a Word document template with OpenXML" }
197284
<h1>Intro</h1> <p>You've mastered the Rubik's Cube and got bored solving it, so now you are looking for a new challenge. One puzzle similar to the Rubik's Cube caught your attention. It's called a Pyraminx puzzle, and is a triangular pyramid-shaped puzzle. The parts are arranged in a pyramidal pattern on each side, while the layers can be rotated with respect to each vertex, and the individual tips can be rotated as well. There are 4 faces on the Pyraminx. The puzzle should be held so that one face faces you and one face faces down, as in the image below. The four corners are then labeled <code>U</code> (for up), <code>R</code> (for right), <code>L</code> (for left), and <code>B</code> (for back). The front face thus contains the <code>U</code>, <code>R</code>, and <code>L</code> corners.</p> <p><em>Let's write down all possible moves for vertex U in the following notation:</em></p> <ul> <li>U - 120° counterclockwise turn of topmost tip (assuming that we're looking at the pyraminx from the top, and vertex U is the topmost);</li> <li>U' - clockwise turn for the same tip;</li> <li>u - 120° counterclockwise turn of two upper layer;</li> <li>u' - clockwise turn for the same layers.</li> </ul> <p><a href="https://i.stack.imgur.com/IQrVk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IQrVk.png" alt="enter image description here"></a></p> <p>For other vertices the moves can be described similarly</p> <p><a href="https://i.stack.imgur.com/QfLWl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QfLWl.png" alt="enter image description here"></a></p> <p>The first puzzle you bought wasn't assembled, so you get your professional pyraminx solver friend to assemble it. He does, and you wrote down all his moves notated as described above. Now the puzzle's faces have colors <code>faceColors[0]</code> (front face), <code>faceColors[1]</code> (bottom face), <code>faceColors[2]</code> (left face), <code>faceColors[3]</code> (right face). You want to know the initial state of the puzzle to repeat your friend's moves and see how he solved it.</p> <h1>Example</h1> <p>For <code>face_colors = ['R', 'G', 'Y', 'O']</code> and moves = <code>["B", "b'", "u'", "R"]</code>, the output should be</p> <pre><code>pyraminxPuzzle(faceColors, moves) = [['Y', 'Y', 'Y', 'Y', 'R', 'R', 'R', 'R', 'G'], ['G', 'R', 'O', 'O', 'O', 'G', 'G', 'G', 'G'], ['Y', 'O', 'Y', 'G', 'O', 'O', 'G', 'G', 'Y'], ['R', 'O', 'O', 'R', 'O', 'Y', 'Y', 'R', 'R']] </code></pre> <p><strong>Visual representation</strong></p> <p><a href="https://i.stack.imgur.com/3Aif7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Aif7.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/KD3q9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KD3q9.png" alt="enter image description here"></a></p> <p><em>Edit</em></p> <p>As requested bij @Jan Kuijken a map for each face to the corresponding index</p> <pre><code>""" L[2] : [ 4 | U[0] : [ 0, | R[3] : [ 8, 6, 5, 1 | 1, 2, 3, | 3, 7, 6, 8, 7, 3, 2, 0 ] | 4, 5, 6, 7, 8 ] | 0, 2, 1, 5, 4 ] ----------------------------------------------------------------------------- B[1] : [ 8, 7, 6, 5, 4, 3, 2, 1, 0 ] """ </code></pre> <h1>Tests</h1> <pre><code>import unittest class TestPyraminx(unittest.TestCase): def test1(self): exp_1 = [["Y","Y","Y","Y","R","R","R","R","G"], ["G","R","O","O","O","G","G","G","G"], ["Y","O","Y","G","O","O","G","G","Y"], ["R","O","O","R","O","Y","Y","R","R"]] colours = ["R", "G", "Y", "O"] moves = ["B", "b'", "u'", "R"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_1) def test2(self): exp_2 = [["R","R","R","R","R","R","R","R","R"], ["G","G","G","G","G","G","G","G","G"], ["Y","Y","Y","Y","Y","Y","Y","Y","Y"], ["O","O","O","O","O","O","O","O","O"]] colours = ["R", "G", "Y", "O"] moves = ["l", "l'"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_2) def test3(self): exp_3 = [["Y","O","R","G","G","G","G","G","G"], ["G","O","G","Y","O","O","Y","Y","Y"], ["R","G","R","R","O","Y","Y","Y","Y"], ["R","R","R","R","O","O","O","O","R"]] colours = ["R", "G", "Y", "O"] moves = ["l", "l'", "u", "R", "U'", "L", "R'", "u'", "l'", "L'", "r"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_3) def test4(self): exp_4 = [["R","R","R","G","R","R","G","G","G"], ["G","O","G","G","O","O","O","G","G"], ["Y","Y","Y","Y","Y","Y","Y","Y","Y"], ["R","R","R","R","O","O","O","O","O"]] colours = ["R", "G", "Y", "O"] moves = ["r"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_4) def test5(self): exp_5 = [["A","A","A","A","A","A","A","A","A"], ["B","B","B","B","B","B","B","B","B"], ["C","C","C","C","C","C","C","C","C"], ["D","D","D","D","D","D","D","D","D"]] colours = ["A", "B", "C", "D"] moves = ["l", "l'", "r'", "r", "u", "U", "u'", "R'", "L", "R", "L'", "B'", "U'", "b", "B", "b'"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_5) def test6(self): exp_6 = [["E","Y","E","G","Y","Y","R","G","G"], ["Y","E","Y","R","E","E","E","R","R"], ["G","G","G","Y","R","R","E","E","E"], ["R","G","R","R","G","G","Y","Y","Y"]] colours = ["R", "G", "Y", "E"] moves = ["b", "l", "r", "u"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_6) def test7(self): exp_7 = [["E","R","R","R","L","R","R","R","U"], ["L","U","U","U","E","U","U","U","R"], ["U","L","L","L","R","L","L","L","E"], ["R","E","E","E","U","E","E","E","L"]] colours = ["R", "U", "L", "E"] moves = ["U", "B", "R", "L"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_7) def test8(self): exp_8 = [["W","W","D","A","W","W","S","A","A"], ["A","D","D","A","D","D","D","A","A"], ["S","S","S","S","S","W","A","A","S"], ["W","W","W","D","D","S","W","S","D"]] colours = ["W", "A", "S", "D"] moves = ["l", "r'", "U'", "u", "r'", "B", "l'", "b'"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_8) def test9(self): exp_9 = [["W","S","D","S","W","S","S","W","A"], ["D","W","A","A","D","A","D","W","A"], ["S","A","A","D","S","W","W","S","A"], ["W","D","D","W","S","D","A","S","D"]] colours = ["W", "A", "S", "D"] moves = ["B'", "R'", "L", "U'", "B", "r'", "l", "B'", "L'", "r'", "L", "U", "u'", "U", "B'", "r", "L'", "R", "B", "r", "R'", "R", "U'", "U", "L", "r", "L", "B'", "U", "B", "R", "R'", "R", "u'", "l", "R'", "R", "B", "R'", "U", "u", "U", "u'", "B'", "r", "L'", "B'", "R'", "B'", "r", "R'", "r", "L", "R'", "B", "u", "B'", "B", "L", "U", "B", "B", "L", "R", "B", "R", "u'", "R'", "B", "u", "u'", "L'", "B", "R'", "l'", "U", "U'", "B", "r", "L'", "B", "r'", "U", "R", "R'", "u'", "r", "R'", "u'", "r'", "L'", "R'", "r'", "U", "u'", "B'", "U", "L'", "L'", "B"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_9) def test10(self): exp_10 = [["W","W","W","W","W","W","W","W","W"], ["A","A","A","A","A","A","A","A","A"], ["S","S","S","S","S","S","S","S","S"], ["D","D","D","D","D","D","D","D","D"]] colours = ["W", "A", "S", "D"] moves = ["L", "L", "L", "r'", "r'", "r'", "U", "U'", "U", "U'", "b", "b'", "b'", "b"] self.assertEqual(pyraminx_puzzle(colours, moves), exp_10) if __name__ == '__main__': unittest.main() </code></pre> <h1>Code</h1> <pre><code>def pyraminx_puzzle(face_colours, moves): move_position = { "U": [[0, 0], [3, 8], [2, 4]], "u": [[0, 0], [0, 1], [0, 2], [0, 3], [3, 8], [3, 3], [3, 7], [3, 6], [2, 4], [2, 6], [2, 5], [2, 1]], "L": [[2, 0], [1, 8], [0, 4]], "l": [[2, 0], [2, 1], [2, 2], [2, 3], [1, 8], [1, 3], [1, 7], [1, 6], [0, 4], [0, 6], [0, 5], [0, 1]], "R": [[3, 0], [0, 8], [1, 4]], "r": [[3, 0], [3, 1], [3, 2], [3, 3], [0, 3], [0, 8], [0, 7], [0, 6], [1, 4], [1, 6], [1, 5], [1, 1]], "B": [[1, 0], [2, 8], [3, 4]], "b": [[1, 0], [1, 1], [1, 2], [1, 3], [2, 8], [2, 3], [2, 7], [2, 6], [3, 4], [3, 6], [3, 5], [3, 1]] } puzzle = [[c for _ in range(9)] for c in face_colours] for move in reversed(moves): left = "'" not in move move_colors = { move: [puzzle[r][c] for r, c in move_position[move]] for move in move_position } current_color = shift_color(move_colors[move[0]], left) for idx, pos in enumerate(move_position[move[0]]): puzzle[pos[0]][pos[1]] = current_color[idx] return puzzle def shift_color(current_color, left): i = len(current_color) // 3 if left: return current_color[i:] + current_color[0:i] return current_color[-i:] + current_color[:-i] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T17:00:47.857", "Id": "380262", "Score": "0", "body": "Nice problem, could you also provide a drawing which maps the `x` index of `faceColours[x]` to the actual positions on the faces? (for an easier understanding)" }, { "Co...
[ { "body": "<h2>Trivial observations</h2>\n\n<p>You have a parameter named <code>face_colours</code>, and another parameter named <code>current_color</code>, as well as a function named <code>shift_color</code>. Pick one spelling convention and stick with it. American English generally <a href=\"https://docs.p...
{ "AcceptedAnswerId": "198255", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T13:54:10.653", "Id": "197287", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "CodeFights: Pyraminx puzzle" }
197287
<p>I am studying Java. Can you criticize my code and tell me what I need to do to make it better?</p> <p>I have code that reads a txt file(product base). It contains tabular data where lines are formatted as:</p> <p><code>id productName price quantity</code></p> <p>We launch the code with:</p> <p><code>-u id productName price quantity</code> - update line;</p> <p>or</p> <p><code>-d id</code> - delete line.</p> <p>So the logic is to find this line, create new File with updated line or without it, delete base file and rename new file.</p> <p>Last important thing: every element on textbase has own weight. It's <code>int []argsLength</code>. If the element size less that its weight, we fill empty space with whitespaces.</p> <p>simple for test(indents is correct):</p> <pre><code>1 Recorder 100.00 12 212 Rocket 182.00 400 99333 Hat 4500.00 5 1984711 Crocodile 2.5 4339 13247983Pistol 53500.903 </code></pre> <p><a href="https://ru.files.fm/u/5q3zb94a" rel="nofollow noreferrer">https://ru.files.fm/u/5q3zb94a</a></p> <h3>main:</h3> <pre><code>public class CRUD { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String filename = reader.readLine(); BufferedReader fileReader = new BufferedReader(new FileReader(filename)); int[] argsLength = new int[]{0, 8, 30, 8, 4}; FileCreator creator = new FileCreatorFactory().getFileCreator(args[0], args, argsLength, filename); String line; if (creator == null) { System.out.println("Unknow command"); return; } if ((line = creator.isLineIsset()) == null) { System.out.println("Unknow ID"); return; } File resultFile = creator.createNewFile(line); if (resultFile.length() == 0) { System.out.println("Error"); return; } reader.close(); fileReader.close(); Files.delete(new File(filename).toPath()); System.out.println("Result:" + (resultFile.renameTo(new File(filename)))); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <h3>FileCreatorFactory:</h3> <pre><code>package ru.kirstentasks.filecreator; public class FileCreatorFactory { public FileCreator getFileCreator(String arg,String[] args, int[] argsMaxLength,String filename) { switch (arg) { case "-u": return new idUpdater(filename,args,argsMaxLength); case "-d": return new idDeleter(filename,args,argsMaxLength); default: return null; } } } </code></pre> <h3>FileCreator:</h3> <pre><code>public abstract class FileCreator { protected String[] args; protected int[] argsMaxLength; protected String fileName; FileCreator(String fileName, String[] args, int[] argsMaxLength) { this.args = args; this.argsMaxLength = argsMaxLength; this.fileName = fileName; } public String isLineIsset() throws IOException { String result; BufferedReader reader = new BufferedReader(new FileReader(fileName)); while (!((result = reader.readLine()) == null)) { if (args[1].trim().equals(result.substring(0, argsMaxLength[1]).trim())) { reader.close(); return result; } } reader.close(); return null; } public abstract File createNewFile(String line); } </code></pre> <h3>idDeleter:</h3> <pre><code>package ru.kirstentasks.filecreator; import java.io.*; public class idDeleter extends FileCreator { private String fileName; idDeleter(String fileName, String[] args, int[] argsMaxLength) { super(fileName, args, argsMaxLength); this.fileName = fileName; } @Override public File createNewFile(String line) { BufferedReader fileReader; BufferedWriter fileWriter; File tempFile = new File(fileName + ".temp"); try { fileReader = new BufferedReader(new FileReader(fileName)); fileWriter = new BufferedWriter(new FileWriter(tempFile)); String temp; while (!((temp = fileReader.readLine()) == null)) { if (temp.equals(line)) { continue; } fileWriter.write(temp); fileWriter.newLine(); } fileReader.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return tempFile; } } </code></pre> <h3>idUpdater:</h3> <pre><code>package ru.kirstentasks.filecreator; import java.io.*; public class idUpdater extends FileCreator { private String filename; idUpdater(String filename, String[] args, int[] argsMaxLength) { super(filename, args, argsMaxLength); this.filename = filename; } @Override public File createNewFile(String line) { BufferedReader fileReader; BufferedWriter fileWriter; File tempFile = new File(filename + ".temp"); try { fileReader = new BufferedReader(new FileReader(filename)); fileWriter = new BufferedWriter(new FileWriter(tempFile)); String temp; while (!((temp = fileReader.readLine()) == null)) { if (temp.equals(line)) { temp = createLine(args, argsMaxLength); } fileWriter.write(temp); fileWriter.newLine(); } fileReader.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return tempFile; } private String createLine(String[] args, int[] argsLength) { if (args.length != argsLength.length) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 1; i &lt; args.length; i++) { sb.append(String.format("%-" + argsLength[i] + "s", args[i])); } return sb.toString(); } } </code></pre>
[]
[ { "body": "<h1>file format definition</h1>\n<p>You have some definition of the file format, like</p>\n<blockquote>\n<p>It contains tabular data where lines are formatted as:</p>\n<pre><code>id productName price quantity\n</code></pre>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p>Last important thing: every elem...
{ "AcceptedAnswerId": "197300", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T15:34:10.403", "Id": "197292", "Score": "7", "Tags": [ "java", "io" ], "Title": "Java, delete / update the line from the file by id" }
197292
<p>I did this small project where there are six one-liner anonymous methods that can swap case of a given string of any length. For example "heLLo, woRLd" ==> "HEllO, WOrlD". I used this string as the example to demonstrate how each of the function works. This string "heLLo, woRLd" can simply be replaced with Console.ReadLine() to get user anticipated inputs. I understand one-liners are not readable and maybe not considered good practice, and used variable names are not proper as well. This whole project was for fun. I believe that way I can learn more. My expectation is that someone can tell me if there are more ways to do this case-swapping (of course, has to be one-liner)?. I think I used 3 (kinda) algorithms to do the swapping. Moreover, all of the one-liners are void functions and all the succeeding functions are shorter than the preceding ones.</p> <pre><code>using System; using System.Linq; class x { static void Main(string[] args) { // one-liner string swapcase (new Action&lt;string&gt;(delegate (string x) { foreach (char i in x) { char b = i; b^= char.IsLetter(b) ? (char)32 : (char)0; Console.Write(b); } }))("heLLo, woRLd"); Console.WriteLine(); //one-liner string swapcase2 (new Action&lt;string&gt;(delegate (string x) { foreach (char i in x) { Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)); } }))("heLLo, woRLd"); Console.WriteLine(); // one-liner string swapcase3 ((Action&lt;string&gt;)(delegate (string x) { foreach (char i in x) { Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)); } }))("heLLo, woRLd"); Console.WriteLine(); //one-liner string swapcase4 ((Action&lt;string&gt;)((x) =&gt; { foreach (char i in x) { Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)); } }))("heLLo, woRLd"); Console.WriteLine(); //one-liner string swapcase5 "heLLo, woRLd".ToList().ForEach(i =&gt; Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i))); Console.WriteLine(); //one-liner string swapcase6 "heLLo, woRLd".ToList().ForEach(i =&gt; Console.Write(i^= char.IsLetter(i) ? (char)(1 &lt;&lt; 5) : (char)0)); Console.ReadLine(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T18:50:05.613", "Id": "380280", "Score": "0", "body": "You can also loop with `foreach (var c in \"heLLo, woRLd\") {...}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T12:02:16.570", "Id": "3803...
[ { "body": "<p>I find your code amusing but since this is not Code Golf but Code Review I'll review it from <em>our</em> perspective this is, as clean-code first.</p>\n\n<p>Even if you try to write compact code you should not use <em>magic</em> exressions and sacrifice readability. Instead encapsulate them in (l...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T17:29:38.057", "Id": "197295", "Score": "2", "Tags": [ "c#", "strings", "comparative-review" ], "Title": "String Swap-case one-liners (6 ways)" }
197295
<p>This question is a follow up of: <a href="https://codereview.stackexchange.com/questions/197227/calculate-min-max-mean-and-median-out-of-array#197230">Calculate min, max, mean and median out of array</a></p> <p>I took all the suggestions an reworked the code. Like the description of the excercise suggests i only use one function for all the computations. Also with the sorting the max and median values can now be calculated easier.</p> <p>I wonder if its good to return the Macro types <code>INT_MIN</code> <code>INT_MAX</code> and <code>NAN</code> for indicating no valid result?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include &lt;limits.h&gt; #include &lt;math.h&gt; struct Summary_data { long long smallest; long long largest; double median; double mean; }; static inline int cmp(void const *lhs, void const *rhs) { const int *left = (const int *)lhs; const int *right = (const int *)rhs; return (*left &gt; *right) - (*left &lt; *right); } int* intdup(const int * source, const size_t len) { assert(source); int * p = malloc(len * sizeof(*source)); if (p == NULL) exit(1); memcpy(p, source, len * sizeof(*source)); return p; } struct Summary_data calculate_values(const int* array, const size_t len) { assert(array); struct Summary_data summary_data = { 0 }; int* calc_array = intdup(array, len); size_t i; if (len &lt;= 0) { // dont bother to calc if invalid len free(calc_array); calc_array = NULL; summary_data.smallest = INT_MAX; summary_data.largest = INT_MIN; summary_data.mean = NAN; summary_data.median = NAN; return summary_data; } qsort(calc_array, len, sizeof *array, cmp); summary_data.smallest = calc_array[0]; summary_data.largest = calc_array[len - 1]; for (i = 0; i &lt; len; ++i) { summary_data.mean += calc_array[i]; } summary_data.mean /= len; if (len % 2 == 0) { // is even == return the arithmetic middle of the two middle values summary_data.median = (calc_array[(len - 1) / 2] + calc_array[len / 2]) / 2.0; } else { // is odd == retunr the middle summary_data.median = calc_array[len / 2]; } free(calc_array); calc_array = NULL; return summary_data; } void print_result(const struct Summary_data* summary_data) { assert(summary_data); printf("smallest: %i\n", summary_data-&gt;smallest); printf("largest: %i\n", summary_data-&gt;largest); printf("median: %g\n", summary_data-&gt;median); printf("mean: %g\n\n", summary_data-&gt;mean); } int main() { int test_array[] = { 1,7,3,4,5,6,7,8,9 }; // 9 elements // int test_array[] = { 1,7,3,4,5,6,7,8 }; // 8 elements int len = sizeof(test_array) / sizeof(test_array[0]); //len = 0; // test when len is invalid struct Summary_data summary_data = calculate_values(test_array, len); print_result(&amp;summary_data); getchar(); return 0; } </code></pre>
[]
[ { "body": "<h3>BUGS</h3>\n\n<ol>\n<li>when <code>calculate_values()</code> is called with a <code>len</code> of 0, the program may exit. this is because <code>calc_array</code> is created before the <code>len &lt;= 0</code> check, and <code>malloc(0)</code> is allowed by the standard to return 0. To fix this, e...
{ "AcceptedAnswerId": "197312", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T17:39:06.410", "Id": "197296", "Score": "2", "Tags": [ "c", "array", "statistics" ], "Title": "Calculate min, max, mean and median out of array Version 2" }
197296
<p>I did the following Excercise:</p> <blockquote> <p>simulate single inheritance in C. Let each "base class" contain a pointer to an array of pointers to functions (to simulate virtual functions as freestanding functions taking a pointer to a "base class" object as their first argument). Implement "derivation" by making the "base class" the type of the first member of the derived class.</p> <p>For each class, initialize the array of "virtual functions" appropriately. To test the ideas, implement a version of "the old Shape example" with the base and derived draw() just printing out the name of their class. Use only language features and library facilities available in standard C.</p> </blockquote> <p>I wonder if my approach is good? And as a side question: Is OOP relevant in practice with using c?</p> <p><strong>Edit</strong>: the goal is to simulate c++ like OOP constructs with the limited features of c.</p> <pre><code>#include &lt;stdio.h&gt; typedef void(*pfct)(struct Shape*); typedef struct { pfct draw; }Vtable; typedef struct{ // "Base class" Vtable* pvtable; }Shape; typedef struct{ // "Derived" from Shape Shape shape; int radius; }Circle; void draw(Shape* this) // "Virtual function" { (this-&gt;pvtable-&gt;draw)(this); } void draw_shape(Shape* this) { printf("Drawing Shape\n"); } void draw_circle(Shape* this) { Circle* pcircle = (Circle*)this; printf("Drawing Circle with radius = %i\n",pcircle-&gt;radius); } Shape* init_shape() { Shape* pshape = malloc(sizeof(Shape)); Vtable* pvtable = malloc(sizeof(Vtable)); pvtable-&gt;draw = &amp;draw_shape; pshape-&gt;pvtable = pvtable; return pshape; } Circle* init_circle(int radius) { Circle* pcircle = malloc(sizeof(Circle)); pcircle-&gt;shape = *init_shape(); pcircle-&gt;shape.pvtable-&gt;draw = &amp;draw_circle; pcircle-&gt;radius = radius; return pcircle; } int main() { Shape* myshape = init_shape(); Circle* mycircle = init_circle(5); draw(myshape); draw(mycircle); getchar(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T19:43:31.647", "Id": "380295", "Score": "1", "body": "I think your exercise's explanation should be a little more.. explained. It isn't clear what you are supposed to achieve." }, { "ContentLicense": "CC BY-SA 4.0", "Cre...
[ { "body": "<blockquote>\n <p>Simulate single inheritance in c<br>\n I wonder if my approach is good?</p>\n</blockquote>\n\n<h2>Function consistency</h2>\n\n<p>I'd expect <code>..._circle(Shape* this)</code> functions to take <code>Circle* this</code>. Let the <code>draw()</code> play with the pointer convers...
{ "AcceptedAnswerId": "197318", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T18:34:40.607", "Id": "197302", "Score": "0", "Tags": [ "object-oriented", "c", "polymorphism" ], "Title": "Drawing various types of shapes" }
197302
<p>I'm trying to ensure that a Sinatra hash always has a valid value.</p> <p>Is there a more-concise way to write this?</p> <pre><code>params[:v] = if [:icons,:list].include? (params[:v] ||= :list).downcase.to_sym then (params[:v] ||= :list).downcase.to_sym else :list end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-20T02:59:57.833", "Id": "384676", "Score": "0", "body": "I'm really unsure what your goal is here. Can you clarify?" } ]
[ { "body": "<p>I'd write this in multiple lines, so that you don't have to write out the complex conversion multiple times:</p>\n\n<pre><code>v = (params[:v] || :list).downcase.to_sym\nparams[:v] = if %i[icons list].include?(v) then v else :list end\n</code></pre>\n", "comments": [], "meta_data": { ...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T19:41:08.747", "Id": "197306", "Score": "1", "Tags": [ "ruby", "sinatra" ], "Title": "Ensure that a Sinatra hash always has a valid value" }
197306
<p>I have a form that I have broken into several different components in Angular. By the end of the form, all the data needs to be submitted together. </p> <p>My thought process was to create a provider to handle/save the form data and at the end of the form, use the provider to package it up so it can be sent to an API. I have two examples of my form components below. In total there are 6 components.</p> <p>This code works, but I feel I am not utilizing angular in the best possible way. Any suggestions/criticisms are greatly appreciated.</p> <h1>Form Data Provider</h1> <pre><code>import { Injectable } from '@angular/core'; interface membershipType { membershipId: number } interface primaryMember { firstName: string, lastName: string, phoneNumber: number, address: string, city: string, state: string, zip: number } @Injectable() export class MembershipFormProvider { membershipTypeData: membershipType; primaryMemberData: primaryMember constructor() { } setMembershipType(formData: membershipType){ this.membershipTypeData = formData; } getMembershipType(){ return this.membershipTypeData; } setPrimaryMember(formData: primaryMember){ this.primaryMemberData = formData; } getPrimaryMember(){ return this.primaryMemberData; } } </code></pre> <h1>First Form Component</h1> <h3>.ts File</h3> <pre><code>import { MembershipFormProvider } from '../../providers/membership-form/membership-form'; @IonicPage({ name: 'register-membership-type', defaultHistory: ['sign-in'] }) @Component({ selector: 'page-register-membership-type', templateUrl: 'register-membership-type.html', }) export class RegisterMembershipTypePage { selectedPlan: number = 1; constructor( public navCtrl: NavController, public navParams: NavParams, private formData: MembershipFormProvider) { } selectPlan(plan: number){ this.selectedPlan = plan; } submitData(){ let membershipType = { 'membershipId' : this.selectedPlan } this.formData.setMembershipType(membershipType); this.navCtrl.push('register-primary-member'); } </code></pre> <h3>.html file</h3> <pre><code>&lt;ion-header no-border&gt; &lt;ion-navbar color="primary"&gt; &lt;/ion-navbar&gt; &lt;/ion-header&gt; &lt;ion-content &gt; &lt;div padding-left class="header-content"&gt; &lt;h1&gt;Register&lt;/h1&gt; &lt;p&gt;We offer different membership plans, which one works best for you?&lt;/p&gt; &lt;/div&gt; &lt;ion-list&gt; &lt;ion-item padding-vertical (click)="selectPlan(1)"&gt; &lt;ion-icon *ngIf="selectedPlan == 1" item-start name="checkmark-circle-outline"&gt;&lt;/ion-icon&gt; &lt;h2&gt;Individual Membership&lt;/h2&gt; &lt;p&gt;1 Adult, 16 years or older&lt;/p&gt; &lt;p item-end&gt;$34.00&lt;/p&gt; &lt;/ion-item&gt; &lt;ion-item padding-vertical (click)="selectPlan(2)"&gt; &lt;ion-icon *ngIf="selectedPlan == 2" item-start name="checkmark-circle-outline"&gt;&lt;/ion-icon&gt; &lt;h2&gt;Dual Membership&lt;/h2&gt; &lt;p&gt;2 Adults or 1 Adult and 1 Child&lt;/p&gt; &lt;p item-end&gt;$49.00&lt;/p&gt; &lt;/ion-item&gt; &lt;ion-item padding-vertical (click)="selectPlan(3)"&gt; &lt;ion-icon *ngIf="selectedPlan == 3" item-start name="checkmark-circle-outline"&gt;&lt;/ion-icon&gt; &lt;h2&gt;Family Membership&lt;/h2&gt; &lt;p&gt;2 Adults and up to 4 Children&lt;/p&gt; &lt;p&gt;* Additional Adult $25.00&lt;/p&gt; &lt;p&gt;* Additional Child $14.00&lt;/p&gt; &lt;p item-end&gt;$69.00&lt;/p&gt; &lt;/ion-item&gt; &lt;/ion-list&gt; &lt;div padding&gt; &lt;button (click)="submitData()" class="submit-button" ion-button block&gt;Next&lt;/button&gt; &lt;/div&gt; &lt;/ion-content&gt; </code></pre> <hr> <h1>Second Form Component</h1> <h3>.ts File</h3> <pre><code>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { MembershipFormProvider } from '../../providers/membership-form/membership-form'; @IonicPage({ name: 'register-primary-member', defaultHistory: ['RegisterMembershipTypePage'] }) @Component({ selector: 'page-register-primary-member', templateUrl: 'register-primary-member.html', }) export class RegisterPrimaryMemberPage { constructor( public navCtrl: NavController, public navParams: NavParams, private formData: MembershipFormProvider) { } submitData(firstName,lastName,phoneNumber,address,city,state, zip){ let formData = { 'firstName' : firstName, 'lastName' : lastName, 'phoneNumber' : phoneNumber, 'address' : address, 'city' : city, 'state' : state, 'zip' : zip, }; this.formData.setPrimaryMember(formData); this.navCtrl.push('register-primary-member'); } } </code></pre> <h3>.html file</h3> <pre><code>&lt;ion-header no-border&gt; &lt;ion-navbar color="primary"&gt; &lt;/ion-navbar&gt; &lt;/ion-header&gt; &lt;ion-content padding&gt; &lt;div class="header-content"&gt; &lt;h1&gt;Register&lt;/h1&gt; &lt;p&gt;Your plan must have one primary member, please enter their information below&lt;/p&gt; &lt;/div&gt; &lt;ion-list no-lines&gt; &lt;ion-item&gt; &lt;ion-label floating&gt;First Name&lt;/ion-label&gt; &lt;ion-input [(ngModel)]="firstName"&gt;&lt;/ion-input&gt; &lt;/ion-item&gt; &lt;ion-item&gt; &lt;ion-label floating&gt;Last Name&lt;/ion-label&gt; &lt;ion-input [(ngModel)]="lastName"&gt;&lt;/ion-input&gt; &lt;/ion-item&gt; &lt;ion-item&gt; &lt;ion-label floating&gt;Phone Number&lt;/ion-label&gt; &lt;ion-input [(ngModel)]="phoneNumber"&gt;&lt;/ion-input&gt; &lt;/ion-item&gt; &lt;ion-item&gt; &lt;ion-label floating&gt;Address&lt;/ion-label&gt; &lt;ion-input [(ngModel)]="address"&gt;&lt;/ion-input&gt; &lt;/ion-item&gt; &lt;ion-item&gt; &lt;ion-label floating&gt;City&lt;/ion-label&gt; &lt;ion-input [(ngModel)]="city"&gt;&lt;/ion-input&gt; &lt;/ion-item&gt; &lt;ion-item class="select"&gt; &lt;ion-label floating&gt;State&lt;/ion-label&gt; &lt;ion-select [(ngModel)]="state" interface="popover"&gt; &lt;ion-option value="sc"&gt;SC&lt;/ion-option&gt; &lt;ion-option value="al"&gt;AL&lt;/ion-option&gt; &lt;/ion-select&gt; &lt;/ion-item&gt; &lt;ion-item&gt; &lt;ion-label floating&gt;Zip&lt;/ion-label&gt; &lt;ion-input [(ngModel)]="zip"&gt;&lt;/ion-input&gt; &lt;/ion-item&gt; &lt;/ion-list&gt; &lt;button (click)="submitData(firstName,lastName,phoneNumber,address,city,state, zip)" class="submit-button" ion-button block&gt;Next&lt;/button&gt; &lt;/ion-content&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T19:49:34.973", "Id": "197307", "Score": "1", "Tags": [ "javascript", "typescript", "angular-2+" ], "Title": "Angular form data over multiple components" }
197307
<p><strong>Description:</strong></p> <p>Given a binary tree, return all root-to-leaf paths.</p> <p><a href="https://leetcode.com/problems/binary-tree-paths/description/" rel="nofollow noreferrer">Leetcode</a></p> <blockquote> <pre><code>/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ </code></pre> </blockquote> <p><strong>Code:</strong></p> <pre><code>class Solution { public List&lt;String&gt; binaryTreePaths(TreeNode root) { List&lt;String&gt; paths = new ArrayList&lt;&gt;(); traverse(root, new ArrayList&lt;&gt;(), paths); return paths; } private void traverse(TreeNode root, List&lt;String&gt; path, List&lt;String&gt; paths) { if (root == null) return; path.add(""+root.val); if (root.left == null &amp;&amp; root.right == null) { paths.add(String.join("-&gt;", path)); } traverse(root.left, path, paths); traverse(root.right, path, paths); path.remove(path.size() - 1); } } </code></pre>
[]
[ { "body": "<p>It's a fine solution.\nTracking the values on the path,\ngrowing and shrinking while traversing to the leafs,\nfinally adding a concatenated values is natural and easy to understand.</p>\n\n<p>An alternative (and not necessarily better) approach that may perform better is to reduce the string crea...
{ "AcceptedAnswerId": "197313", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T20:04:57.317", "Id": "197308", "Score": "1", "Tags": [ "java", "algorithm", "recursion", "tree", "interview-questions" ], "Title": "Find all root to leaf paths in binary tree" }
197308
<p>Edit: This code was reworked and repostetd under a new question: <a href="https://codereview.stackexchange.com/questions/197752/non-generic-skip-list-implementation-in-c-version-2">Non generic Skip List implementation in C++ Version 2</a></p> <p>To sharpen my C++ skills I tried to implement a <a href="https://en.m.wikipedia.org/wiki/Skip_list" rel="nofollow noreferrer">skip list</a>. </p> <p>I was quite happy when it finally seemed to work correctly. Unfortunately, the implementation is kinda slow. When I run the <code>main</code> were I randomly insert / erase a map and my skip list, it's always like twice as slow as the map (I tried it with Visual Studio 2017 in Release).</p> <p>I wonder what can be improved to get the big performance gain. I suspect the use of vector in the skipnode and the random number generator. I wonder if there's a faster way to flip a coin to establish the levels. I would also appreciate it if you have any other suggestions to improve the code.</p> <p>One Note: I know it should be normally generic with templates. But first I want to make the code good before in the next step make it generic for any type.</p> <p><strong>skiplist.h</strong></p> <pre><code>#ifndef SKIP_LIST_GUARD #define SKIP_LIST_GUARD #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;functional&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;exception&gt; namespace Skiplist { struct Skipnode { Skipnode(int key, int val, int lvl); std::pair&lt;int, int&gt; kv; //first key, second value std::vector &lt;Skipnode*&gt; next; }; class Skiplist { public: Skiplist() :maxlvl{ 0 }, head{ nullptr }, m_mt(std::random_device()()) { } ~Skiplist(); void insert(int key, int val); bool erase(int key); //search for an element and erase it from the skip list Skipnode* find(int key) const; //find element by key and return the value int size() const; int get_maxlvl() const { return maxlvl; } void print() const; void debug_print() const; private: bool next_level() //flips a coin if true goes up one lvl // with every layer the chance is half so 1 = 50% 2 = 25% etc..... { std::uniform_int_distribution&lt;int&gt; dist(0, 1); return dist(m_mt); } Skipnode* head; //element before first element int maxlvl; // maximum level the nodes have reached so far std::mt19937 m_mt; //random generator member }; int get_random(int min, int max); } #endif </code></pre> <p><strong>skiplist.cpp</strong></p> <pre><code>#include "skiplist.h" namespace Skiplist { Skipnode::Skipnode(int key, int val, int lvl) { kv = std::make_pair(key, val); for (int i = 0; i &lt; lvl; ++i) //build all pointers for the lvl next.push_back(nullptr); next.shrink_to_fit(); //to not waste space } Skiplist::~Skiplist() { if (head == nullptr) return; Skipnode* currpos = head; //start on head while (currpos-&gt;next[0] != nullptr) { Skipnode* lastpos = currpos; currpos = currpos-&gt;next[0]; delete lastpos; } delete currpos; //delete last element } void Skiplist::insert(int key, int val) { //calculate max height of new node int new_node_lvl = 0; do { ++new_node_lvl; if (new_node_lvl == (maxlvl + 1)) { //new node can maximum grow by one lvl; ++maxlvl; if (maxlvl == 1) { //case first row needs to be created; head = new Skipnode(0, 0, 0); //make a empty head } head-&gt;next.push_back(nullptr); head-&gt;next.shrink_to_fit(); //to not waste to much space break; } } while (next_level()); //flip coin. every time it is true go to the next lvl Skipnode* new_node = new Skipnode(key,val,new_node_lvl); //create new node int currlvl = maxlvl - 1; //start on highest lvl Skipnode* currpos = head; //start on head while (true) { if (currpos-&gt;next[currlvl] == nullptr || currpos-&gt;next[currlvl]-&gt;kv.first &gt; key) { if (currlvl &lt; new_node-&gt;next.size()){ //if node will be on this lvl. Install node on it new_node-&gt;next[currlvl] = currpos-&gt;next[currlvl]; currpos-&gt;next[currlvl] = new_node; } --currlvl; // go to the next lvl if (currlvl &lt; 0) break; continue; } currpos = currpos-&gt;next[currlvl]; } } bool Skiplist::erase(int key) { Skipnode* currpos = head; //start on head int currlvl = maxlvl - 1; //start on highest lvl while (currlvl &gt;=0) { if (currpos-&gt;next[currlvl] == nullptr) { --currlvl; continue; } else if (currpos-&gt;next[currlvl]-&gt;kv.first &gt; key) { --currlvl; continue; } else if (currpos-&gt;next[currlvl]-&gt;kv.first == key) { //key found on current lvl --currlvl; //go down first before link is deleted if(currlvl+1 !=0) currpos-&gt;next[currlvl+1] = currpos-&gt;next[currlvl+1]-&gt;next[currlvl+1]; //take out pointer of found element from list else { //case end Skipnode* keynode = currpos-&gt;next[currlvl+1]; currpos-&gt;next[currlvl+1] = currpos-&gt;next[currlvl + 1]-&gt;next[currlvl + 1]; delete keynode; if (head-&gt;next[maxlvl - 1] == nullptr &amp;&amp; maxlvl &gt;1) { //no nodes on highest lvl head-&gt;next.pop_back(); //delete empty lvl --maxlvl; } return true; } continue; } currpos = currpos-&gt;next[currlvl]; } return false; } Skipnode* Skiplist::find(int key) const //find element by key and return value { Skipnode* currpos = head; //start on head int currlvl = maxlvl - 1; //start on highest lvl while (true) { if (currpos-&gt;next[currlvl] == nullptr || (currlvl &gt; 0 &amp;&amp; currpos-&gt;next[currlvl]-&gt;kv.first &gt;= key)) { --currlvl; if (currlvl &lt; 0) return nullptr; //element was not found; continue; } if (currlvl == 0 &amp;&amp; currpos-&gt;next[currlvl]-&gt;kv.first == key) { // element found currpos = currpos-&gt;next[currlvl]; return currpos; } currpos = currpos-&gt;next[currlvl]; } return nullptr; } int Skiplist::size() const { if (head == nullptr) return 0; //special case nothing is build yet int sz = 0; Skipnode* currpos = head; if (currpos-&gt;next.empty()) return sz; while (currpos-&gt;next[0] != nullptr) { ++sz; currpos = currpos-&gt;next[0]; } return sz; } void Skiplist::print() const //prints out all elements { Skipnode* currpos = head; while (currpos != nullptr) { if(currpos != head) std::cout &lt;&lt; currpos-&gt;kv.first&lt;&lt;"/"&lt;&lt; currpos-&gt;kv.second &lt;&lt; " "; currpos = currpos-&gt;next[0]; } std::cout &lt;&lt; "\n"; } void Skiplist::debug_print() const //messy debug routine to print with all available layers { Skipnode* currpos = head; int currlvl = currpos-&gt;next.size() - 1; currpos = currpos-&gt;next[currlvl]; if (head-&gt;next[0] == nullptr) return; while (currlvl &gt;= 0) { std::cout &lt;&lt; "lvl: " &lt;&lt; currlvl &lt;&lt; "\t"; Skipnode* lastpos = head; while (currpos != nullptr) { if (currlvl &gt; 0) { int void_count = 0; while (lastpos != nullptr &amp;&amp; lastpos-&gt;kv.first != currpos-&gt;kv.first) { lastpos = lastpos-&gt;next[0]; ++void_count; } for (int i = 0; i &lt; void_count-1; ++i) std::cout &lt;&lt; "-/-- "; } if(currpos != head) std::cout &lt;&lt; currpos-&gt;kv.first &lt;&lt; "/" &lt;&lt; currpos-&gt;kv.second &lt;&lt; " "; currpos = currpos-&gt;next[currlvl]; } std::cout &lt;&lt; "\n"; --currlvl; currpos = head; } std::cout &lt;&lt; "\n"; } 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); } } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;map&gt; #include &lt;ctime&gt; #include "skiplist.h" int main() try { constexpr int repeats = 30; constexpr int count_of_elements = 5000000; std::vector &lt;int&gt; rnd; std::map &lt;int, int &gt; mp; for (int i = 0; i &lt; repeats; ++i) { for (int j = 0; j &lt; count_of_elements; ++j) { //fill vector with 100.000 unique random elements int in = 0; while (true) { in = Skiplist::get_random(1, std::numeric_limits&lt;int&gt;::max()); bool twice = false; auto it = mp.find(in); if (it == mp.end()) break; } rnd.push_back(in); mp.insert(std::make_pair(in,i)); } std::cout &lt;&lt; rnd.size() &lt;&lt; "\n"; mp.clear(); std::cout &lt;&lt; '\n'; //fill map and skiplist and compare clock_t begin_sk = clock(); Skiplist::Skiplist sk; for (std::size_t i = 0; i &lt; rnd.size(); ++i) sk.insert(rnd[i], i); clock_t end_sk = clock(); std::cout &lt;&lt; "skiplist filled. Time:" &lt;&lt; double(end_sk - begin_sk) / CLOCKS_PER_SEC &lt;&lt; "\n"; clock_t begin_sk_d = clock(); for (std::size_t i = 0; i &lt; rnd.size(); ++i) sk.erase(rnd[i]); clock_t end_sk_d = clock(); std::cout &lt;&lt; "skiplist deleted. Time:" &lt;&lt; double(end_sk_d - begin_sk_d) / CLOCKS_PER_SEC &lt;&lt; "\n"; std::cout &lt;&lt; '\n'; clock_t begin_mp = clock(); std::map&lt;int, int&gt; mp; for (std::size_t i = 0; i &lt; rnd.size(); ++i) mp.insert(std::pair&lt;int, int&gt;(rnd[i], i)); clock_t end_mp = clock(); std::cout &lt;&lt; "map filled. Time:" &lt;&lt; double(end_mp - begin_mp) / CLOCKS_PER_SEC &lt;&lt; "\n"; clock_t begin_mp_d = clock(); for (std::size_t i = 0; i &lt; rnd.size(); ++i) mp.erase(rnd[i]); clock_t end_mp_d = clock(); std::cout &lt;&lt; "map deleted. Time:" &lt;&lt; double(end_mp_d - begin_mp_d) / CLOCKS_PER_SEC &lt;&lt; "\n"; std::cout &lt;&lt; '\n'; } std::cin.get(); } 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>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T21:08:14.993", "Id": "380308", "Score": "0", "body": "You might want to add a description of how a skiplist is supposed to work. From reading the code, I can't seem to wrap my head around what this weird tree structure does and what...
[ { "body": "<h1><code>skiplist.h</code></h1>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;random&gt;\n#include &lt;functional&gt;\n#include &lt;vector&gt;\n#include &lt;utility&gt;\n#include &lt;exception&gt;\n</code></pre>\n\n<p>A lot of these headers don't need to be in <code>skiplist.h</code>. Includ...
{ "AcceptedAnswerId": "197327", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T20:13:27.493", "Id": "197309", "Score": "4", "Tags": [ "c++", "performance", "collections", "skip-list" ], "Title": "Non generic Skip List implementation in C++" }
197309
<p>I'm working through the classic <em>Cracking the Coding Interview</em> book. I'm trying to solve the following graph problem: </p> <blockquote> <p>4.1) Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.</p> </blockquote> <p>I've written a solution in JavaScript and found it was a lot less complicated than the book's solution. Am I missing something? Why does the solution use a <code>Visiting</code> state? Can't we just use <code>Visited</code> instead? </p> <pre><code>function RouteBetweenNodes( node1, node2 ) { const q = new Queue() q.add( node1 ) while ( !q.isEmpty() ) { const node = q.remove() if ( node === node2 ) { return true } node.visited = true node.children.forEach( child =&gt; !child.visited &amp;&amp; q.add( child ) ) } return false } </code></pre> <p>Here is an implementation of a <code>Queue</code> for completeness:</p> <pre><code>class QueueNode { constructor( data ) { this.data = data this.next = null } } class Queue { constructor() { this.first = null this.last = null } add( item ) { const newNode = new QueueNode( item ) if ( this.last ) { this.last.next = newNode } else { this.first = newNode } this.last = newNode } remove() { if ( this.first ) { const data = this.first.data this.first = this.first.next if ( this.first == null ) { this.last == null } return data } throw Error( 'empty queue' ) } peek() { if ( this.first ) { return this.first.data } throw Error( 'empty queue' ) } isEmpty() { return this.first === null } } </code></pre> <p><a href="https://i.stack.imgur.com/8HXIx.png" rel="nofollow noreferrer">Here is the book's solution.</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T22:07:34.567", "Id": "380315", "Score": "1", "body": "Welcome to Code Review! I hope you get some good answers =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T22:24:26.600", "Id": "380316", ...
[ { "body": "<ul>\n<li><p>Your worst case performance (every node is connected to each other node but <code>node2</code>) is \\$\\mathcal{O}(n^2)\\$, up from the \"normal\" \\$\\mathcal{O}(n)\\$, because nodes can be added to the queue multiple times. This should also increase the average runtime. <strong>This ge...
{ "AcceptedAnswerId": "197316", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T21:51:44.433", "Id": "197314", "Score": "0", "Tags": [ "javascript", "algorithm", "graph" ], "Title": "Cracking the Coding Interview - 4.1 Graph Traversal" }
197314
<h2>Introduction</h2> <p>This is a follow-up to my <a href="https://codereview.stackexchange.com/q/195767/93301">previous question</a>. This code rocks new ground-up implementation of core functionality, which I made from combining @vnp’s and @JDługosz's answers. The core functionality got ~100 LOC decrease and insert gained 15-25% performance gain. It turns out that my remove tests didn't test anything at all in the previous version (now fixed), so I don't know how much performance was gained in remove, but I'm pretty sure the gain is paramount.</p> <p>Though there are some changes I didn't make. I state the reasons closer to the end of post.</p> <p><strong>Changes:</strong></p> <ul> <li>Uniform node location</li> </ul> <p>There is a single function to find the desired node with value or yet to be value. This is achieved through double pointers. Yes, double pointers.</p> <ul> <li><p>Using boolean conversion instead of <code>== nullptr</code></p></li> <li><p>Using default initialization of members</p></li> </ul> <p><strong>New functionality:</strong></p> <ul> <li>SFINAE</li> </ul> <p><code>try_insert</code> is now uniform for both rvalue and lvalue, and activated only if type is either copyable or moveable. Copy constructor checks for feature too. </p> <ul> <li><p>Copy constructor</p></li> <li><p>emplace</p></li> </ul> <p>This one was a little bit tricky to pull out. It had some exception issues, but should be okay. The only thing that makes me worried is alignment, though I guess doing SSE or some other hardware trick on BSTs is pretty much useless. </p> <ul> <li>size</li> </ul> <p>Now the tree knows its size and correctly maintains it.</p> <hr> <h2>Code</h2> <pre><code>#ifndef ALGORITHMS_BINARY_SEARCH_TREE_HPP #define ALGORITHMS_BINARY_SEARCH_TREE_HPP #include "binary_tree_iterator.hpp" #include &lt;ostream&gt; #include &lt;utility&gt; #include &lt;type_traits&gt; #include &lt;memory&gt; namespace shino { template &lt;typename ValueType&gt; class binary_search_tree { constexpr static bool v_copiable = std::is_copy_constructible_v&lt;ValueType&gt;; constexpr static bool v_moveable = std::is_move_constructible_v&lt;ValueType&gt;; struct node { //DO NOT MOVE ELEMENTS AROUND, emplace relies on this order const ValueType value; node* left = nullptr; node* right = nullptr; }; node* root = nullptr; std::size_t element_count = 0; public: using iterator = binary_tree_iterator&lt;node&gt;; binary_search_tree(binary_search_tree&amp;&amp; other) noexcept: root(std::exchange(other.root, nullptr)), element_count(std::exchange(other.element_count, 0)) {} binary_search_tree&amp; operator=(binary_search_tree&amp;&amp; other) noexcept { std::swap(root, other.root); std::swap(element_count, other.element_count); return *this; } template &lt;typename = std::enable_if_t&lt;v_copiable&gt;&gt; explicit binary_search_tree(const binary_search_tree&amp; other) { if (other.element_count == 0) return; root = new node(other.root-&gt;value); deep_copy(root-&gt;left, other.root-&gt;left); deep_copy(root-&gt;right, other.root-&gt;right); element_count = other.element_count; } template &lt;typename AnotherType, typename = std::enable_if_t&lt;std::is_same_v&lt;ValueType, std::decay_t&lt;AnotherType&gt;&gt; and (v_copiable || v_moveable)&gt;&gt; bool try_insert(AnotherType&amp;&amp; value) { auto insertion_point = find_node(value); if (*insertion_point) return false; *insertion_point = new node{std::forward&lt;AnotherType&gt;(value)}; ++element_count; return true; } template &lt;typename ... Args&gt; bool emplace(Args&amp;&amp; ... args) { std::unique_ptr&lt;char[]&gt; buffer = std::make_unique&lt;char[]&gt;(sizeof(node)); new (buffer.get()) node(std::forward&lt;Args&gt;(args)...); auto possible_node = reinterpret_cast&lt;node*&gt;(buffer.get()); auto insertion_point = find_node(possible_node-&gt;value); if (*insertion_point) { std::destroy_at(possible_node-&gt;value); return false; } possible_node-&gt;left = nullptr; possible_node-&gt;right = nullptr; *insertion_point = possible_node; buffer.release(); ++element_count; return true; } bool exists(const ValueType&amp; value) const { return *find_node(value) != nullptr; } bool delete_if_exists(const ValueType&amp; value) { if (element_count == 0) return false; auto child_ptr = find_node(value); if (!*child_ptr) return false; *child_ptr = find_replacement(*child_ptr); --element_count; return true; } std::size_t size() const { return element_count; } void clear() { clear_helper(root); } iterator begin() { return iterator{root}; } iterator end() { return {}; } ~binary_search_tree() { clear(); } private: void deep_copy(node* dest, node* source) { if (!source) return; if (source-&gt;left) { dest-&gt;left = new node(source-&gt;left-&gt;value); deep_copy(dest-&gt;left, source-&gt;left); } if (source-&gt;right) { dest-&gt;right = new node(source-&gt;right-&gt;value); deep_copy(dest-&gt;right, source-&gt;right); } } node* find_replacement(node* start_pos) { if (!start_pos-&gt;left) { auto replacement = start_pos-&gt;right; delete start_pos; return replacement; } auto descendant = start_pos-&gt;left; while (descendant-&gt;right) descendant = descendant-&gt;right; descendant-&gt;right = start_pos-&gt;right; delete start_pos; return start_pos-&gt;left; } void clear_helper(node* start_position) { if (!start_position) return; clear_helper(start_position-&gt;left); clear_helper(start_position-&gt;right); delete start_position; } node** find_node(const ValueType&amp; value) { auto* current = &amp;root; while (*current and (*current)-&gt;value != value) if (value &lt; (*current)-&gt;value) current = &amp;(*current)-&gt;left; else current = &amp;(*current)-&gt;right; return current; } }; } #endif //ALGORITHMS_BINARY_SEARCH_TREE_HPP </code></pre> <h2>Tests:</h2> <pre><code>#include "binary_search_tree.hpp" #include &lt;random&gt; #include &lt;unordered_set&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; std::vector&lt;int&gt; generate_unique_numbers(std::size_t size) { std::vector&lt;int&gt; result; if (size == 0) return {}; static std::mt19937_64 twister; std::uniform_int_distribution&lt;&gt; distribution{0, static_cast&lt;int&gt;(size - 1)}; std::unordered_set&lt;int&gt; numbers; while (numbers.size() != size) { numbers.insert(distribution(twister)); } return {numbers.begin(), numbers.end()}; } void run_randomized_insert_tests() { for (std::size_t i = 0; i &lt;= 5'000; ++i) { std::cout &lt;&lt; "running binary_search_tree insert test on size " &lt;&lt; i &lt;&lt; '\n'; auto numbers = generate_unique_numbers(i); shino::binary_search_tree&lt;int&gt; tree; for (auto x: numbers) tree.try_insert(x); std::sort(numbers.begin(), numbers.end()); std::size_t numbers_index = 0; for (auto x: tree) { if (x != numbers[numbers_index++]) throw std::logic_error{"tree binary_tree_iterator is broken on size " + std::to_string(i)}; } } } void remove_value(std::vector&lt;int&gt;&amp; vec, int x) { vec.erase(std::remove(vec.begin(), vec.end(), x), vec.end()); } void run_randomized_remove_tests() { static std::mt19937_64 twister; for (std::size_t i = 0; i &lt;= 1'000; ++i) { shino::binary_search_tree&lt;int&gt; tree; auto numbers = generate_unique_numbers(i); for (auto x: numbers) tree.try_insert(x); std::sort(numbers.begin(), numbers.end()); std::cout &lt;&lt; "running remove test on tree of size " &lt;&lt; i &lt;&lt; '\n'; for (std::size_t j = 0; j &lt; i; ++j) { std::bernoulli_distribution dist; if (dist(twister)) { tree.delete_if_exists(static_cast&lt;int&gt;(j)); remove_value(numbers, static_cast&lt;int&gt;(j)); } } std::size_t values_index = 0; for (auto x: tree) { if (numbers[values_index] != x) throw std::logic_error{"remove doesn't work correctly on " + std::to_string(i)}; ++values_index; } } } int main(){ std::cout &lt;&lt; "running randomized insert tests...\n"; run_randomized_insert_tests(); std::cout &lt;&lt; "randomized insert tests passed successfully\n"; std::cout &lt;&lt; "running randomized remove tests...\n"; run_randomized_remove_tests(); std::cout &lt;&lt; "randomized remove tests passed successfully\n"; } </code></pre> <hr> <h2>Not applied changes</h2> <ul> <li>Return iterator along with insert</li> </ul> <p>I don't think I have suitable iterator interface to implement at the moment. <code>shino::binary_tree_iterator</code> mentioned in <a href="https://codereview.stackexchange.com/questions/195919/generic-in-order-traversal-iterator-for-binary-trees">this post</a> might hinder the performance of those operations.</p> <ul> <li>Still using <code>!= nullptr</code> in <code>exists</code></li> </ul> <p>Linter was arguing that implicit conversion in that context is confusing. I gave in.</p> <hr> <h2>Concerns</h2> <p>Mostly I'd like to improve simplicity and readability of the code on this iteration, and improve usage of standard library. Though if you see any low hanging performance fruit, please let me know. As always, any other comments are welcome too.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T23:00:17.220", "Id": "380321", "Score": "0", "body": "I'd like this to reach boost level of quality. I wanted to apply for GSoC, but couldn't pass their coding test. I'm starting preparations for the next year already :)" } ]
[ { "body": "<h1>Memory management</h1>\n\n<ul>\n<li><code>clear</code> and <code>deep_copy</code> might overflow the callstack for large number of nodes if the tree is highly unbalanced.</li>\n<li>Prefer <code>std::unique_ptr</code> over raw owning pointers. <code>binary_search_tree::root</code>, <code>node::lef...
{ "AcceptedAnswerId": "197321", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-26T22:55:25.547", "Id": "197319", "Score": "5", "Tags": [ "c++", "tree", "c++17" ], "Title": "Better generic binary search tree in C++" }
197319
<pre><code>function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); //1* - Think of it like: give me a function that adds 3 to whatever you give it result = fn_inside(5); //2* - returns 8 result1 = outside(3)(5); // returns 8 </code></pre> <p>1*,2* - Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible.</p> <p>Questions</p> <p>1) What happens when we call <code>outside(3)</code>?</p> <ul> <li>1a) What does it return?</li> </ul> <p>2) Is <code>fn_inside(3);</code> a valid function call?</p> <p>3) How is <code>outside(3)(5)</code> valid when outside function definition accepts only one parameter?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T06:03:43.463", "Id": "380345", "Score": "0", "body": "Welcome to Code Review. This question doesn't reflect what the site is about. It's not on-topic to ask for an explanation of code that you do not understand. See [What topics can...
[ { "body": "<ol>\n<li><code>outside(3)</code> returns a function. Like you said, it returns a function takes one argument <code>n</code> and returns <code>n + 3</code>. Mathematically, this might be written as <em>f(n) = n + 3</em>.</li>\n<li><code>fn_inside</code> is a binding made to the return value of <code>...
{ "AcceptedAnswerId": "197330", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T05:11:48.257", "Id": "197328", "Score": "-3", "Tags": [ "javascript", "closure" ], "Title": "Javascript - How does this preservation of variable works in Closure javascript?" }
197328
<p>Honestly, I'm doing a practice and get blocked. <a href="https://www.hackerrank.com/challenges/maximum-palindromes/problem" rel="nofollow noreferrer">Problem link</a>.</p> <p>The problem is simple, given a string, calculate the number of max length palindromes (Any substring is valid, which means you can take any chars you want and reorder them as you want). Return the result modulo 1000000007.</p> <p>For example, given <code>amim</code>, the answer is <code>2</code> (<code>mim</code> and <code>mam</code>).</p> <h2>Full Code</h2> <pre><code>#!/bin/python3 import math import os import random import re import sys from itertools import permutations from functools import lru_cache # Complete the initialize function below. def initialize(s): # This function is called once before all queries. s = [ord(i) - 97 for i in s] results = [[0] * 26] for i, v in enumerate(s): result = results[i].copy() result[v] += 1 results.append(result) return results def count(s): result = [0] * 26 for i in s: result[i] += 1 return result factorial = lru_cache(None)(math.factorial) p = 1000000007 pow = lru_cache(None)(pow) # Complete the answerQuery function below. def answerQuery(l, r): # Return the answer for this query modulo 1000000007. counted1 = counted_list[l - 1] counted2 = counted_list[r] counted = [counted2[i] - counted1[i] for i in range(26)] left = 0 total = 0 divide = [] for temp in counted: left += temp &amp; 1 total += temp &gt;&gt; 1 divide.append(temp &gt;&gt; 1) total = factorial(total) total = total % p for i in divide: temp = factorial(i) temp = pow(temp, p - 2, p) total = total * temp result = total * (left or 1) return result % p if __name__ == '__main__': s = input() counted_list = initialize(s) q = int(input()) for q_itr in range(q): lr = input().split() l = int(lr[0]) r = int(lr[1]) result = answerQuery(l, r) print(result) </code></pre> <p>The code above can pass #0~#21 testcases and will fail in #22 due to timeout. (Just copy it to Problem link page given at the top)</p> <p>As #22 testcase is very huge, I cannot post it here. So here is the link:</p> <p><a href="https://files.fm/u/mekwpf8u" rel="nofollow noreferrer">https://files.fm/u/mekwpf8u</a></p> <p><em>If I can use numpy to rewrite this function, I think it will be better. But I cannot, I can only use the standard libs.</em></p> <h2>update</h2> <p>I use another customized <code>factorial</code> function but exceed memory usage limitation :/ But it really reduces the total time cost.</p> <pre><code>factorial_table = [1, 1] def factorial(n): if n &lt; len(factorial_table): return factorial_table[n] last = len(factorial_table) - 1 total = factorial_table[last] for i in range(last + 1, n + 1): total *= i factorial_table.append(total) return total </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T06:02:40.920", "Id": "380344", "Score": "0", "body": "Welcome to Code Review. Asking for advice on code yet to be written or implemented is off-topic for this site. See [What topics can I ask about?](https://codereview.stackexchange...
[ { "body": "<ul>\n<li><p>Do <code>% p</code> early.</p>\n\n<p>Since the test case is huge, I expect intermediate values you compute to be huge as well. Multiplication of large numbers is a very expensive operation. Try to keep your results in a native range. Consider e.g.</p>\n\n<pre><code>def modulo_factorial(n...
{ "AcceptedAnswerId": "197365", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T05:37:21.297", "Id": "197329", "Score": "4", "Tags": [ "python", "performance", "algorithm", "time-limit-exceeded" ], "Title": "Longest palindromes in a string" }
197329
<p>I need to process some data (one of its columns contains a json/dict with params- I need to extract those params to individual columns of their own; catch- some rows have some parameters, others have others.. but all rows put together have 1142 individual parameters.) and so I've written the following script, which works, but the sys, AWS EC2 instance, shut it down after about 64% of its execution.. The output just stopped and terminal shows "Killed". The systems guys at my company told me its a memory issue and it was killed by the os.<br> <strong>Can someone help me make this more memory efficient?</strong></p> <p>The raw data for this process is roughly 1GB in size.. I load it from a csv into a pandas dataframe of 2.2+ Mn rows and 11 columns.. 1 column has links- prbably around 60 - 80 chars, most of them. Two other columns have either a dict with key/value pairs or a get url with its set of parameters. The other columns have only null or simple short texts. I'm trying to get these parameters from the GET urls and links into their own individual dataframe columns- for most parameters I suspect most rows will have nulls but nonetheless I want this in seperate clean row column structure so I can proceed to analyze this data.</p> <p>My server has 32Gb of memory.</p> <p><strong>The code</strong></p> <pre><code>import pandas as pd, numpy as np, datetime, ast import sys qdata = pd.read_csv('q_data_parsed.csv') print qdata.shape fl = open('q_unique_params.txt','r') cols = fl.read() cols = ast.literal_eval(cols) print type(cols) print cols fl.close() global key_ def get_params(rw): try: return rw['params'][key_] except KeyError: print "KeyError" return "" except Exception as e: print key_, e return "" f = open('q_params_parsed.txt','w') f.write('\n') f.close() for col in cols: key_=col print key_ qdata["{}_param".format(key_)]=qdata.apply(get_params) f = open('qtr_params_parsed.txt','a') f.write('\n' + str(key_)) f.close() print qdata.shape print qdata.shape qdata.to_csv('q_data_parsed_to_col_full.csv') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T09:04:18.857", "Id": "380361", "Score": "0", "body": "You suspect that your program fails due to a memory issue. Are you able to reduce your input CSV from millions of rows down to a hundred or so and run the program to completion?"...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T06:14:01.297", "Id": "197331", "Score": "3", "Tags": [ "python", "memory-management", "pandas", "memory-optimization", "data-mining" ], "Title": "Pandas data extraction task taking too much memory. How to optimize for memory usage?" }
197331
<p>I have a java service class which will call a REST service and get response back.<br> It is working fine in developer environment where less requests are made, but I still wanted to get a review.</p> <p>My service method call is like:</p> <pre><code>private String getResponse(Object request, String cUri) { String responseStr = StringUtils.EMPTY; try { Gson requestJson = new GsonBuilder().disableHtmlEscaping().create(); String inputJson = requestJson.toJson(request); logger.debug("Input JSON : " + inputJson); responseStr = connect.getResponse(cUri, inputJson,config.getHttpClient()); logger.debug("Outut JSON for provided request" + responseStr); } catch (Exception e) { logger.error("Exception while getting response from service : " + e,e); } return responseStr; } </code></pre> <p>Here <code>config.getHttpClient());</code> is as follows:</p> <pre><code>public class Test { private static CloseableHttpClient httpClient; private static PoolingHttpClientConnectionManager connectionManager; public CloseableHttpClient getHttpClient() { if(httpClient != null){ return httpClient; } try { SSLContext sslContext = getSSLContext(); SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory( sslContext == null ? SSLContext.getDefault() : sslContext ,new String[] { "TLSv1", "TLSv1.2", "TLSv1.1" } ,null ,NoopHostnameVerifier.INSTANCE); Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry= RegistryBuilder.&lt;ConnectionSocketFactory&gt;create() .register("https", trustSelfSignedSocketFactory) .register("http", PlainConnectionSocketFactory.getSocketFactory()).build(); connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(Integer.parseInt(props.getProperty(Constants._CONNECTION_COUNT))); connectionManager.setDefaultMaxPerRoute(Integer.valueOf(props.getProperty(Constants._MAX_PER_ROUTE))); httpClient = HttpClientBuilder .create() .setConnectionManager(connectionManager) .setConnectionManagerShared(true) .build(); } catch (Exception e) { logger.error("Error in getting rest server connection" + e, e); } return httpClient; } private SSLContext getSSLContext(){ //return sslContext; } } </code></pre> <p><strong>And this Test class is initialized as Singleton bean.</strong></p> <p>And <code>public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient)</code> is as follows:</p> <pre><code>public class ConnectionHelper{ public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) throws Exception{ String responseStr = StringUtils.EMPTY; HttpPost request = new HttpPost(uri); StringEntity params = new StringEntity(inputJson); request.addHeader("Content-type", "application/json"); request.setEntity(params); try(final CloseableHttpResponse response= httpClient.execute(request)){ responseStr = EntityUtils.toString(response.getEntity(),"UTF-8"); }catch(Exception e){ logger.error("Error while exeucting on request " + e,e); }finally { httpClient.close(); } return responseStr; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T09:13:06.770", "Id": "197336", "Score": "2", "Tags": [ "java", "rest", "spring" ], "Title": "Create HttpClient using PoolingHttpClientConnectionManager" }
197336
<p>This is a python (2.7.13 according to <code>sys.version</code>) script that reads systemd service names from a file and gets their CPU and Memory usage. It does that by first getting the main PID of the service by either searching for it in /var/run (<strong>most</strong> services have a pidfile containing the main PID there, however, there are different ways in which they are created -- in a subfolder or not, with a specific name and etc., but almost all of them have the .pid extension) or if that fails, it just greps it. The first way isn't something that is the same for all services, but I put effort to do it, because it is a more optimized and a faster way to gather that information, while reading from an external grep is a hassle. After getting the PID I get all child processes and calculate their CPU usage from /proc stat files (this is the same thing that <code>psutil</code> does, I could just use it for CPU usage, but since I know the way and it works -- it is faster manually implemented, or is it..). For the memory usage I just skipped that part and directly used <code>psutil</code>. I would really like to improve the formatting and readability of my code, as well as its performance. And I do have a few questions like:</p> <ol> <li><p>Is it a good idea to make all those checks for a pidfile in /var/run just to save time from external grepping?</p></li> <li><p>Are all those nested <code>if</code>s there along with the <code>try</code> / <code>except</code> on top of them a good style, and if not, how would I be able to replace them?</p></li> <li><p>Is it a bad practice to manually implement the gathering of information about CPU usage, while still using an external library for memory usage?</p></li> </ol> <p>Any suggestions about formatting, styling, readability, optimization, etcetera are welcome. The script runs relatively fast (~0.8s/10services) on my machine, however, I have an SSD, and assuming it could run on a computer with an HDD or even slower CPUs the execution time could be a lot higher, especially if they are 100 services and not 10.</p> <pre><code>#!/usr/bin/env python # Exit codes: # 6 : Getopt Error. Probably wrong argument or misspell. # 7 : Global exception caught. Could be anything. # Import default system libraries. import getopt import os import subprocess import sys # from datetime import datetime # Uncomment if going to benchmark for speed. # Import external libraries. import psutil from pathlib import Path # startTime = datetime.now() # Start the timer for benchmarking. Must uncomment last line as well. # Get arguments and set configuration. def parse_args(): cfgfile = 'smon.conf' if len(sys.argv) &gt; 1: try: opts, args = getopt.getopt(sys.argv[1:], 'c:', ['config=']) except getopt.GetoptError: print("An error occured while parsing your arguments. Check the proper usage of the script.") sys.exit(6) for opt, arg in opts: if opt in ('-c', '--config'): cfgfile = str(arg) return cfgfile # Read services from the configuration file and add them into a list. def load_services(handlerlist, cfg): try: with open(cfg, "r") as servfile: for line in servfile: handlerlist.append(line.strip()) except: print("The file {} most probably does not exist. ".format(cfg)) return handlerlist # Read CPU and Memory usage of the processes. def read_stats(ss): cpud = {} memd = {} for pid in ss: with open(os.path.join('/proc/', str(pid), 'stat'), 'r') as pfile: pidtimes = pfile.read().split(' ') pname = str(pidtimes[1])[1:-1] cpud[pname] = '0' memd[pname] = '0' for pid in ss: # CPU times and usage can be found in the /proc/ filesystem in stat files. with open(os.path.join('/proc/', str(pid), 'stat'), 'r') as pfile: pidtimes = pfile.read().split(' ') pname = str(pidtimes[1])[1:-1] utime = int(pidtimes[13]) # utime is the 14th element in the stat file (man proc). stime = int(pidtimes[14]) # stime is the 15th element in the stat file (man proc). pidtotal = utime - stime with open('/proc/stat', 'r') as cfile: # Get total system CPU times. cputimes = cfile.readline().split(' ') cputotal = 0 for integ in cputimes[2:]: integ = int(integ) cputotal = cputotal + integ usg = (pidtotal / cputotal) * 100 # Process CPU usage is process cpu times / system cpu time. if usg &lt; 0: # Deny negative values usg = 0 newusg = int(cpud[pname]) + usg cpud[pname] = str(newusg) # Calculate the usage and add to it. phandler = psutil.Process(pid) # Generate a process class for the given PID. pmem = phandler.memory_percent() # Get memory usage in percents of services. newpmem = float(memd[pname]) + pmem memd[pname] = str(newpmem) return cpud, memd # Get the Process ID for each service in the configuration file. def get_pid(slist): pidchecks = [] # Predefine the list of PIDs. for svc in slist: cpuusage = 0 # Predefine the variable for CPU usage. try: # For every service, try to find its PID file in /var/run and read it. pidfpath = '/var/run/{}/{}.pid'.format(svc, svc) if not Path(pidfpath).exists(): # Most services have a /var/run/service/service.pid file. pidfpath = '/var/run/{}.pid'.format(svc) if not Path(pidfpath).exists(): # Some services use 'd' after their names for daemon. pidfpath = '/var/run/{}.pid'.format(svc + 'd') if not Path(pidfpath).exists(): # Others have a /var/run/service.pid file. pidfolder = '/var/run/{}'.format(svc) tmpc = os.listdir(pidfolder) for f in tmpc: # And others have various pidfiles like /var/run/service/pid. f = str(f) if 'pid' in f: pidfpath = pidfolder + '/' + f # Add the file to the dir path. with open(pidfpath, 'r') as pidf: mainpid = int(pidf.readline().strip()) # Read the PID number. Not sure if strip is needed. Have to check. except Exception as e: # If such a PID file does not exist, get Main PID from parsing systemctl. try: mainpid = int(subprocess.check_output("systemctl status {} | grep 'Main PID: ' | grep -Eo '[[:digit:]]*' | head -n 1".format(svc), shell=True)) except ValueError as e: # If systemctl returns nothing, then such a service does not exist. pass try: # Get all the children of the Main PID and append them to a list. mainproc = psutil.Process(mainpid) mchildren = mainproc.children(recursive=True) pidchecks.append(mainpid) for child in mchildren: pidchecks.append(child.pid) except psutil._exceptions.NoSuchProcess: # Return an error if there is no such process working. print("No running process with pid {} ({}). Probably the service isn't working.\n".format(str(mainpid), svc)) except psutil._exceptions.ZombieProcess: # Return an error if the process is a zombie process. print("The process with pid {} ({}) is a zombie process\n".format(str(mainpid), svc)) return pidchecks def main(): cfg = parse_args() # Get arguments for minimal mode and for the configuration file. services = [] # Predefine the services list. services = load_services(services, cfg) # Get the services into the list by using the cfg file. pidlist = get_pid(services) # Get PIDs of the services' processes. cpudic = {} # Predefine the dictionary for CPU usage. memdic = {} # Predefine the dictionary for RAM usage. cpudic, memdic = read_stats(pidlist) # Get stats into the dictionary. for (entry, usg) in cpudic.items(): # Print the results. print("CPU usage of process {}: {}%".format(entry, usg)) print("Memory usage of process {}: {}%\n".format(entry, memdic[entry])) try: main() # No need for main module check. except Exception as err: print("A global exception has occured.") print(err) sys.exit(7) # print("Time ran: {}".format(datetime.now() - startTime)) # Uncomment if going to benchmark. </code></pre>
[]
[ { "body": "<h2>Review</h2>\n\n<p><em>All pieces of code in this answer are untested.</em></p>\n\n<ol>\n<li><p>Follow the PEP-8 guidelines. You did this almost flawlessly, but:</p>\n\n<ul>\n<li><p>You missed a couple of variables. Variable names should follow the same naming convention as functions.<sup>1</sup><...
{ "AcceptedAnswerId": "197353", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T11:23:16.930", "Id": "197342", "Score": "6", "Tags": [ "python", "python-2.x", "linux" ], "Title": "Python script for monitoring systemd services (cpu/memory usage)" }
197342
<p>I've written my first C++ multithreaded application (as far as I can recall) which determines if a regex can be found in a string.</p> <p>This code works correct to the best of my knowledge.</p> <p>Could you gals/guys tell me what I could improve on this code?</p> <h2>main.cpp (one file):</h2> <pre><code>#include &lt;iostream&gt; #include &lt;chrono&gt; using namespace std::chrono; template&lt;typename T&gt; auto toMs(T &amp;&amp;time) { return duration_cast&lt;milliseconds&gt;(time).count(); } #include &lt;string&gt; #include &lt;regex&gt; void cxxregex(std::string const&amp;inputString, std::string const&amp;searchRegex) { auto startTime = steady_clock::now(); std::regex regexObj(searchRegex.data(), std::regex::extended); std::smatch matchObj; regex_search(inputString.begin(), inputString.end(), matchObj, regexObj); std::cout &lt;&lt; toMs(steady_clock::now() - startTime) &lt;&lt; "ms " &lt;&lt; matchObj[1] &lt;&lt; std::endl; } #include &lt;boost/regex.hpp&gt; void boostregex(std::string const&amp;inputString, std::string const&amp;searchRegex) { auto startTime = steady_clock::now(); boost::regex regexObj(searchRegex.data(), boost::regex::extended); boost::smatch matchObj; regex_search(inputString.begin(), inputString.end(), matchObj, regexObj); std::cout &lt;&lt; toMs(steady_clock::now() - startTime) &lt;&lt; "ms " &lt;&lt; matchObj[1] &lt;&lt; std::endl; } #include &lt;future&gt; void threadFcn( const int threadId, const std::string::const_iterator&amp; subStringBegin, const std::string::const_iterator&amp; subStringEnd, const boost::regex&amp; regexObj, std::promise&lt;std::pair&lt;size_t, std::string&gt;&gt;&amp; matchProm, const std::shared_future&lt;std::pair&lt;size_t, std::string&gt;&gt;&amp; matchFut) { boost::smatch matchObj; if (regex_search(subStringBegin, subStringEnd, matchObj, regexObj)) { // match is found! if (matchFut.wait_for(0s) != std::future_status::ready) // check of not already set matchProm.set_value(std::make_pair(threadId, matchObj[1]));// matchObj.str())); } } #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std::chrono_literals; void boostparregex(std::string const &amp;inputString, std::string const &amp;searchRegex) { auto nrOfCpus = std::thread::hardware_concurrency() / 2; std::cout &lt;&lt; "(Nr of CPUs: " &lt;&lt; nrOfCpus &lt;&lt; ") "; if (searchRegex.find("^") != std::string::npos || searchRegex.find("$") != std::string::npos) { //if (boost::regex_match(searchRegex, boost::regex("(.*\\^.*)|(.*\\$.*)"))) { std::cout &lt;&lt; "Start-of-line not supported multi-CPU. Defaulting to 1.\n"; nrOfCpus = 1; } auto startTime = steady_clock::now(); boost::regex regexObj(searchRegex.data(), boost::regex::extended); std::promise&lt;std::pair&lt;size_t, std::string&gt;&gt; foundThreadIdProm; auto foundThreadIdFut = foundThreadIdProm.get_future().share(); std::vector&lt;std::thread&gt; threadVector; threadVector.reserve(nrOfCpus); auto stringSizePerThread = inputString.length() / nrOfCpus; for (size_t threadId = 0; threadId &lt; nrOfCpus; threadId++) { // determine string start and end const auto begin = inputString.begin() + (threadId * stringSizePerThread); const auto end = inputString.end(); // all cpu's search to end of input string. they only differ in start // create thread threadVector.push_back(std::thread(threadFcn, (int)threadId, std::ref(begin), std::ref(end), std::ref(regexObj), std::ref(foundThreadIdProm), std::ref(foundThreadIdFut))); } if (foundThreadIdFut.wait_for(10s) == std::future_status::ready) std::cout &lt;&lt; toMs(steady_clock::now() - startTime) &lt;&lt; "ms. " &lt;&lt; "Thread " &lt;&lt; foundThreadIdFut.get().first &lt;&lt; ": " &lt;&lt; foundThreadIdFut.get().second &lt;&lt; std::endl; else std::cerr &lt;&lt; "Error: string not found!!" &lt;&lt; std::endl; for (auto&amp; thread : threadVector) thread.join(); // I'd rather detach... but then the references are destroyed, giving problems. } int main() { std::string s(1000000000, 'x'); { std::string s1 = "yolo" + s; std::cout &lt;&lt; "yolo + ... -&gt; cxxregex "; cxxregex(s1, "(yolo)"); std::cout &lt;&lt; "yolo + ... -&gt; boostregex "; boostregex(s1, "(yolo)"); std::cout &lt;&lt; "yolo + ... -&gt; boostparregex "; boostparregex(s1, "(yolo)"); } { std::string s2 = s + "yolo"; std::cout &lt;&lt; "... + yolo -&gt; cxxregex "; cxxregex(s2, "(yolo)"); std::cout &lt;&lt; "... + yolo -&gt; boostregex "; boostregex(s2, "(yolo)"); std::cout &lt;&lt; "... + yolo -&gt; boostparregex "; boostparregex(s2, "(yolo)"); } { std::string s3 = "yo" + s + "lo"; //std::cout &lt;&lt; "... + yolo -&gt; cxxregex "; cxxregex(s3, "(yo).*(lo)"); // doesn't even work std::cout &lt;&lt; "... + yolo -&gt; boostregex "; boostregex(s3, "(yo).*(lo)"); std::cout &lt;&lt; "... + yolo -&gt; boostparregex "; boostparregex(s3, "(yo).*(lo)"); } std::cin.ignore(); } </code></pre> <p>Typical output:</p> <pre class="lang-none prettyprint-override"><code>yolo + ... -&gt; cxxregex 0ms yolo yolo + ... -&gt; boostregex 1ms yolo yolo + ... -&gt; boostparregex (Nr of CPUs: 4) 14ms. Thread 0: yolo ... + yolo -&gt; cxxregex 5214ms yolo ... + yolo -&gt; boostregex 779ms yolo ... + yolo -&gt; boostparregex (Nr of CPUs: 4) 251ms. Thread 3: yolo ... + yolo -&gt; boostregex 1636ms yo ... + yolo -&gt; boostparregex (Nr of CPUs: 4) 1706ms. Thread 0: yo </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T12:27:14.867", "Id": "380382", "Score": "2", "body": "Is this all a _single_ file? Or several ones?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T15:10:32.337", "Id": "380401", "Score": "0",...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T11:23:28.090", "Id": "197343", "Score": "2", "Tags": [ "c++", "multithreading", "regex", "boost" ], "Title": "Determining if a regex can be found in a string" }
197343
<p>Thought this would be a fun thing to code, basically it is a simulation of the prisoners dilemma. I'm trying to improve my coding so any critiques about how to get better would be appreciated. Also if you have any suggestions for other strategies for the game, those would be appreciated as well. The goal is to have the lowest score. I think the part of the codes I am most worried about at the moment is the weird way I take the output from the strategies and put them into the play function, and everyone online says the eval function is dangerous.</p> <pre><code>from random import randint class Player(object): def __init__(self): pass class TFT(Player): def strat(): global lg #last game global round #round number global TFTv #TFT output variable if round==0: x=0 elif round !=0 and Player1=='TFT' and (lg=="out1" or lg=="out2"): x=0 elif round !=0 and Player2=='TFT' and (lg=="out1" or lg=="out3"): x=0 else: x=1 TFTv=[x] class Rand1(Player): def strat(): global Rand1v #Rand1 output variable x=randint(0,1) Rand1v=[x] class Rand2(Player): def strat(): global Rand2v #Rand2 output variable x=randint(0,1) Rand2v=[x] class Doomsday(Player): def strat(): global Doomsdayv #doomsday output variable if round==0: x=0 elif lg=="out1": x=0 elif Doomsdayv[0]==1: x=1 else: x=1 Doomsdayv=[x] class OpeningMenu(object): def open(): global MaxRounds global round global p1 #player 1 points global p2 #player 2 points MaxRounds=(int(input("How many rounds would you like?\n&gt; "))+1) round=0 p1=0 p2=0 global Player1 global Player2 players={'Description':'Player Name','Tit for Tat':'TFT','Random50/50':'Rand1',"Doomsday":'Doomsday'} print("Possible Players:", players) Player1=input("Player 1?\n&gt; ") Player2=input("Player 2?\n&gt; ") return Arena.play() class Counter(object): def count(): global p1 global p2 global lg global MaxRounds if round==MaxRounds: print(f"Player 1 score={p1}, and Player 2 score={p2}") elif lg=="out1": p1+=0 p2+=0 elif lg=="out2": p1+=0 p2+=60 elif lg=="out3": p1+=60 p2+=0 elif lg=="out4": p1+=30 p2+=30 else: pass class Arena(object): def play(): global lg global round global Player1 global Player2 eval(Player1).strat() eval(Player2).strat() R1=eval(Player1+'v')[0] R2=eval(Player2+'v')[0] round+=1 if round==MaxRounds: Counter.count() elif R1==R2==0: lg="out1" print("Neither Snitched") Counter.count() return Arena.play() elif R1==1 and R2==0: print("Player 1 snitched on Player 2") lg="out2" Counter.count() return Arena.play() elif R1==0 and R2==1: print("Player 2 snitched on Player 1") lg="out3" Counter.count() return Arena.play() else: print("Both Snitched") lg="out4" Counter.count() return Arena.play() OpeningMenu.open() </code></pre>
[]
[ { "body": "<h3>design</h3>\n\n<ol>\n<li><p>You seem to have designed your system arround changing a whole mess of global variables. please don't do this. It is impossible to understand what variables trigger what effects.</p></li>\n<li><p>Instead of outputing to a variable, and then getting that variable with e...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T11:31:56.383", "Id": "197344", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "game" ], "Title": "Axelrod Tournament" }
197344
<p>I wrote code to search by keyword, and it will check all of the values from the object property, including an array in the object. But apparently the code is not optimized as it takes some time to execute the function, and it is subject to client PC processing power.</p> <p>Here is the sample of the object:</p> <pre><code>{ clientId: "-LFQ1ojwCF8lSRq4J9sQ", desc: "description lorus ipsum etc", document: [ { doc: "photo", status: "ok", url: "https://www.google.com" } ], dt: "2018-06-24", dtactual: "2018-06-26", dtcreate: 1529905260612, dtexpected: "2018-06-25", dtmodify: 1529905260612, dtreceive: "2018-06-26", engineer: "engineer 001", equipment: [ { brand: "ruckus", imei: 123, imsi: 312, model: "R230-1220v6HW", serialNo: 123}, { brand: "", imei: "", imsi: "", model: "", serialNo: ""}, { brand: "", imei: "", imsi: "", model: "", serialNo: ""}, { brand: "", imei: "", imsi: "", model: "", serialNo: ""}, { brand: "", imei: "", imsi: "", model: "", serialNo: ""} ], iwoNum: "iwo num 2", key: "-LFpT2ajia6Wgnrd8lQH", onSiteSupport: { isSupport: true, supportTerm: "" }, pm: "project manager 001", poNum: "po no 002", preventMaintenance: true, projectType: "site installation", remark: "iwo remark", } </code></pre> <p>Imagine there are 50 or 100, or 1000 of the object in an array, and the user wishes to list the object that contains a specific keyword. So the code need to search every property to find the value.</p> <p>So below is my code (written in Typescript, but almost same with JS):</p> <pre><code>iwoLit = [] objectArray = [{...},{...},{...},...] //the details of the object in this array please refer to above object as it is too long to place at here. //Feel free to change any value in there. keyword = 'ruckus' searchFunction(){ objectArray.forEach(element =&gt; { let object = Object.assign({}, element); object['key'] = element.key; let keys = Object.keys(object) for (let i = 0; i &lt; keys.length; i++) { let prop = keys[i] let item = object[prop] if (typeof item == 'string') { let item2 = item.toString() let item3 = item2.toLowerCase() if (item3.indexOf(this.keyword.toLowerCase()) !== -1) { if (this.iwoList.length == 0) { this.iwoList.push(object); } else { for (let l = 0; l &lt; this.iwoList.length; l++) { if (object.key !== this.iwoList[l].key) { this.iwoList.push(object); return false } } } } } //to handle the array in the object let equipValue3 if (Array.isArray(item)) { item.forEach(element2 =&gt; { let itemKeys = Object.keys(element2) for (let j = 0; j &lt; itemKeys.length; j++) { let prop2 = itemKeys[j] let equipValue = element2[prop2] if (typeof equipValue == 'string' || typeof equipValue == 'number') { let equipValue2 = equipValue.toString() equipValue3 = equipValue2.toLowerCase() if (equipValue3.indexOf(this.keyword.toLowerCase()) !== -1) { if (this.iwoList.length == 0) { this.iwoList.push(object); } else { for (let k = 0; k &lt; this.iwoList.length; k++) { if (object.key !== this.iwoList[k].key) { this.iwoList.push(object); return false } } } } } } }) } } }); console.log(this.iwoList) } </code></pre> <p>Would be appreciated if someone can help me optimize the code. It is ok to separate in few functions, as long as the performance can be increased.</p> <p>Side info: Why do I want to make such a nested object? Because I am using noSQL, and this is the DB design.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T14:07:40.720", "Id": "380396", "Score": "0", "body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/51057581/1014587)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-27T21:34:01.397", ...
[ { "body": "<p>As always I suggest to use functional approach, which makes code more readable and concise. I wrote my version, which uses recursion to search through all properties. Each of present functions has single responsibility, which simplifies maintaining of the code. The code is written using ES6.</p>\n...
{ "AcceptedAnswerId": "197375", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T12:11:14.007", "Id": "197345", "Score": "0", "Tags": [ "javascript", "typescript", "nosql" ], "Title": "JS code that search through every property in a nested object" }
197345
<p>I used MySQL, but it was inconvenient so I made a wrapper. It works, but I'm unsure if there are any issues.</p> <p>Used node module - mysql2, bluebird</p> <p>sqlWarpper.js</p> <pre><code>'use strict' import mysql from 'mysql2/promise' import blueBird from 'bluebird' function sqlWrapper() { this.pool = null this.connection = null this.options = null this.lquery = null this.queryHistory = [] return this } /* Connection*/ sqlWrapper.prototype.open = function(msn, opt){ var self = this self.options = { errorIgnore: false, noDataIsFields: false, supportBigNumbers: true, bigNumberStrings: true, debugMode: false } if (typeof opt == 'object' &amp;&amp; Object.keys(opt).length &gt; 0) { Object.keys(opt).forEach(function(k, v) { self.options[k] = opt[k] }) } msn['Promise'] = blueBird if(self.options.debugMode == true){ console.log(chalk.cyan('------------------- Debug Mode -------------------')) } self.pool = mysql.createPool(msn) return self } sqlWrapper.prototype.ready = async function(callback) { if(typeof callback != 'function'){ return null } var self = this, error = null self.connect = await self.pool.getConnection((err, conn) =&gt; { if (err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { error = { code: err.code, msg: 'Database connection was closed.' } } if (err.code === 'ER_CON_COUNT_ERROR') { error = { code: err.code, msg: 'Database has too many connections.' } } if (err.code === 'ECONNREFUSED') { error = { code: err.code, msg: 'Database connection was refused.' } } } return conn }).catch((err) =&gt; { throw err }) if(error != null){ self.connect.release() throw error } const props = { lastQuery: function(){ return self.lquery }, queryList: function(){ return self.queryHistory }, query: function(sql, param) { if(typeof param == 'undefined'){ param = [] } else if(!Array.isArray(param)){ self.connect.rollback() self.connect.release() throw new Error('Query Parameter Not Array') } self.lquery = sql self.queryHistory.push(sql) try { return self.connect.query(sql, param) } catch(e) { self.connect.rollback() self.connect.release() throw e } }, insert: async function(sql, param){ if(typeof param != 'undefined' &amp;&amp; typeof param != 'object'){ param = [] } const [row, fields] = await this.query(sql, param) var val = row.insertId || 0 return Promise.resolve(val) }, getOne: async function(sql, param, field){ if(typeof param != 'undefined' &amp;&amp; typeof param != 'object'){ field = param param = [] } if(sql.indexOf(' limit ') == -1){ sql += ' limit 1' } var val = '', key = null const [row, fields] = await this.query(sql, param) if(typeof field != 'undefined'){ key = field } else { for(var i in row[0]){ if(key == null){ key = i break } } } if(typeof row[0] != 'undefined' &amp;&amp; key != null){ val = row[0][key] || '' } return Promise.resolve(val) }, getRow: async function(sql, param){ if(typeof param != 'undefined' &amp;&amp; typeof param != 'object'){ param = [] } if(sql.indexOf(' limit ') == -1){ sql += ' limit 1' } var val = [] const [row, fields] = await this.query(sql, param) if(typeof row[0] != 'undefined'){ val = row[0] } return Promise.resolve(val) }, getAll: async function(sql, param, start = 0, limit = 2){ if(typeof param != 'undefined' &amp;&amp; typeof param != 'object'){ limit = start start = param param = [] } var val = [] if(sql.indexOf(' limit ') == -1){ sql += ' limit ' + start + ',' + limit } const [row, fields] = await this.query(sql, param) if(typeof row != 'undefined'){ val = row } return Promise.resolve(val) }, rollback: function(){ self.connect.rollback() }, commit: function(){ self.connect.commit() }, chainStart: function(){ self.connect.beginTransaction() }, chainEnd: async function(type){ if(type == 'undefined' || type != 'commit'){ await self.connect.rollback() } else { await self.connect.commit() } await self.connect.release() } } try { await callback(props) } catch(e){ if(self.connect != null){ self.connect.rollback() self.connect.release() } throw e } } var sql = new sqlWrapper() export default sql </code></pre> <p>index.js</p> <pre><code>import sql from './sqlWrapper' const db = sql.open({ "connectionLimit": "10", "host":"localhost", "user": "test", "database": "test", "password": "1234" }, { debugMode: true}) db.ready( async (conn) =&gt; { try { await conn.chainStart() var ssn = await conn.insert('insert test1 (sn) values(?)', [ sn ]) var row = await conn.getOne('select * from test2 where sn = ?', [ ssn ], 'sn') console.log(row) } catch(e){ console.log('1-------------------------------------------') console.log(e) conn.chainEnd('rollback') console.log('-------------------------------------------1') return } console.log('finish') conn.chainEnd('commit') }).catch( (err) =&gt; { console.log('2-------------------------------------------') console.log(err) }) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T12:52:25.077", "Id": "197348", "Score": "2", "Tags": [ "javascript", "mysql", "node.js", "async-await" ], "Title": "Async/await Mysql wrapper" }
197348
<p>I've implemented Luhn checksum in Python version 3. I want your comments and opinion about my code. I know it's embarrassing code and that it doesn't follow python best practices but it works!.</p> <p>The <code>x</code> in <code>doubledigit</code> parameter means that if the boolean is <code>False</code>, the index of the number is odd so we don't have to double it, if it is <code>True</code> it means the index is even, so we double it.</p> <pre><code>import ast def doubledigit(n,x) : if x is True: doubledigit = n *2 sum=0 if doubledigit &gt;= 10 : sum = 1 + doubledigit % 10 else: sum = doubledigit else: sum = n return (sum) def sum (): total =0 prop = int(input("enter how many digits you want: " )) for i in range (0,prop): n = int(input("Enter your digit: " )) x = input("Enter True or False: ") total = total+doubledigit(n,ast.literal_eval(x)) return total def findx (n): if (n % 10 == 1 ): print("the check digit is 9") n += 9 if (n % 10 == 2 ): print("the check digit is 8") n += 8 if (n % 10 == 3 ): print("the check digit is 7") n += 7 if (n % 10 == 4 ): print("the check digit is 6") n += 6 if (n % 10 == 5 ): print("the check digit is 5") n += 5 if (n % 10 == 6 ): print("the check digit is 4") n += 4 if (n % 10 == 7 ): print("the check digit is 3") n += 3 if (n % 10 == 8 ): print("the check digit is 2") n += 2 if (n % 10 == 9 ): print("the check digit is 1") n += 1 if (n % 10 == 0): print("vaild checksum") return n print(findx(sum())) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T13:33:30.320", "Id": "380387", "Score": "2", "body": "Welcome to CodeReview.SE! It seems like there is a formatting error in your code. When I run it, I get \"SyntaxError: 'return' outside function\"." }, { "ContentLicense":...
[ { "body": "<h1>Coding style</h1>\n\n<p>First, have a read through the Python style guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.<br>\nThere's a lot of inconsistency in your coding style, and with the style guide, you should be able to remove all that. It wil...
{ "AcceptedAnswerId": "197354", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T13:12:02.110", "Id": "197349", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "checksum" ], "Title": "Luhn checksum in Python" }
197349
<p>I wrote JS to clone image and attached this action to button.<br> It works but I'm not sure that this better way to do it.</p> <p>My questions:</p> <ul> <li>is it correct to use querySelector to return elements, or is it better to add additional classes or id for buttons and pictures?</li> <li>use cloneNode is optimal or better use other ways in this case?</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>(function() { 'use strict'; document.querySelector('button[action="button"]').addEventListener('click', function() { let image = document.querySelector('img[alt="Dog"]'); let cln = image.cloneNode(true); document.getElementById('image-section').appendChild(cln); }); })();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;div id="overview"&gt; &lt;section class="section--center"&gt; &lt;button action="button"&gt;Yeah, I want more dogs!&lt;/button&gt; &lt;/section&gt; &lt;section class="section--center" id='image-section'&gt; &lt;img src="https://www.purina.com/sites/g/files/auxxlc196/files/styles/kraken_generic_max_width_480/public/HOUND_Beagle-%2813inch%29.jpg?itok=lN915WHC" alt="Dog" style="width: 150px"&gt; &lt;/section&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T13:41:53.470", "Id": "380719", "Score": "0", "body": "Just a minor nitpick: `<button>` elements do not have an `action` attribute in standard HTML. What you're probably looking for is `name`. Cf. https://developer.mozilla.org/en-US/...
[ { "body": "<p>Note: you're cloning a DOM element not an actual image..</p>\n\n<h2>About <code>.querySelector</code></h2>\n\n<p>The great thing about <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll\" rel=\"nofollow noreferrer\"><code>.querySelector</code></a> is that you can ...
{ "AcceptedAnswerId": "197355", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T13:40:16.307", "Id": "197352", "Score": "1", "Tags": [ "javascript", "beginner", "html", "image" ], "Title": "Сlone image in pure js" }
197352
<p>I solved the problem posted from <a href="https://www.makeschool.com/online-courses/tutorials/trees-and-mazes/generating-a-maze-with-dfs" rel="nofollow noreferrer">Make School Trees and Maze article</a>, which asks me to searching a maze using DFS and BFS in Python. </p> <p>Here's the final output from PyGame:</p> <p><img src="https://cdn.rawgit.com/MakeSchool-Tutorials/Trees-Mazes-Python/eccc9ce59ec5e8fdf259c42bb025ffbe085f6491/P0-Generating-a-Maze-with-DFS/dfs_solved_maze.png" alt="PyGame output image"></p> <p>I would like to ask for code review, as I paste my code snippet below: Here's my DFS and BFS solution for solve_maze.py code review for implementation.</p> <p>BFS solutino looks like this:</p> <p><img src="https://cdn.rawgit.com/MakeSchool-Tutorials/Trees-Mazes-Python/eccc9ce59ec5e8fdf259c42bb025ffbe085f6491/P1-Solving-the-Maze/bfs_solve_maze.gif" alt="PyGame output image"></p> <p>You can find my code for generating_maze here: <a href="https://github.com/Jeffchiucp/graph-maze-problem/tree/d7cdbec0d4b0a6cdf44577fd20508b018c6fd8b4" rel="nofollow noreferrer">https://github.com/Jeffchiucp/graph-maze-problem</a></p> <pre><code>import maze import generate_maze import sys import random BIT_SOLUTION = 0b0000010010010110 # Solve maze using Pre-Order DFS algorithm, terminate with solution def solve_dfs(m): stack = [] current_cell = 0 visited_cells = 1 while current_cell != m.total_cells -1: print(current_cell) unvisited_neighbors = m.cell_neighbors(current_cell) if len(unvisited_neighbors) &gt;= 1: # choose random neighbor to be new cell new_cell_index = random.randint(0, len(unvisited_neighbors) - 1) new_cell, compass_index = unvisited_neighbors[new_cell_index] # knock down wall between it and current cell using visited_cell m.visit_cell(current_cell, new_cell, compass_index) # push current cell to stack stack.append(current_cell) # set current cell to new cell current_cell = new_cell # add 1 to visited cells visited_cells += 1 else: m.backtrack(current_cell) current_cell = stack.pop() print("run") m.refresh_maze_view() m.state = 'idle' # Solve maze using BFS algorithm, terminate with solution def solve_bfs(m): """ create a queue set current cell to 0 set in direction to 0b0000 set visited cells to 0 enqueue (current cell, in direction) while current cell not goal and queue not empty dequeue to current cell, in direction visit current cell with bfs_visit_cell add 1 to visited cells call refresh_maze_view to update visualization get unvisited neighbors of current cell using cell_neighbors, add to queue trace solution path and update cells with solution data using reconstruct_solution set state to 'idle' """ queue = [] cur_cell = 0 in_direction = 0b0000 visited_cells = 0 queue.insert(0, (cur_cell, in_direction)) while not cur_cell == len(m.maze_array) - 1 and len(queue) &gt; 0: cur_cell, in_direction = queue.pop() m.bfs_visit_cell(cur_cell, in_direction) visited_cells += 1 m.refresh_maze_view() neighbors = m.cell_neighbors(cur_cell) for neighbor in neighbors: queue.insert(0, neighbor) m.reconstruct_solution(cur_cell) m.state = "idle" def print_solution_array(m): solution = m.solution_array() print('Solution ({} steps): {}'.format(len(solution), solution)) def main(solver='dfs'): current_maze = maze.Maze('create') generate_maze.create_dfs(current_maze) if solver == 'dfs': solve_dfs(current_maze) elif solver == 'bfs': solve_bfs(current_maze) while 1: maze.check_for_exit() return if __name__ == '__main__': if len(sys.argv) &gt; 1: main(sys.argv[1]) else: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T23:02:43.250", "Id": "381109", "Score": "0", "body": "I thought it was a fun problem to solve" } ]
[ { "body": "<h3>Kill the noise</h3>\n\n<p>It's great that the solution works, but it's full of elements that seem to serve no purpose, which makes it confusing and hard to read.</p>\n\n<ul>\n<li><code>visited_cells</code> is modified but never used</li>\n<li><code>BIT_SOLUTION</code> is defined but never used</l...
{ "AcceptedAnswerId": "197510", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T15:43:13.860", "Id": "197356", "Score": "5", "Tags": [ "python", "graph", "breadth-first-search", "depth-first-search" ], "Title": "Searching a maze using DFS and BFS in Python 3" }
197356
<p>Following is a <em>TimeBasedWill</em> I have written in Solidity to be built on the Ethereum Blockchain.</p> <p>I have tested the code using Remix IDE.</p> <p>I would like to get your comments and opinions about security loopholes, performance issues, and ways I can reduce the gas usage.</p> <p>TimeBasedWill.sol</p> <pre><code> pragma solidity ^0.4.23; import "browser/Ownable.sol"; import "browser/Arrays.sol"; /** * @title TimeBasedWill * @dev TimeBasedWill provides ether transfer functionalities to owner's * beneficiaries based on a timer. * - Owner can set the timer(in seconds) to approximately the time they think they'll die * They can change the expiry duration any time. * - Beneficiaries can be added/removed before the expiry time. * - Funds can be added/removed from the contract before the expiry time ONLY by the owner. * - Once the timer is up, anyone can call the function claimOwnership() and the funds * will be transferred to the beneficiaries. * - There are 2 additional functionalities which should be used VERY CAREFULLY * TranferOwnership - This will transfer the onwership of the contract to the new owner. * New Owner will now be able to control all funds in the contract. * RenounceOwnership - This will renounce the contracts ownership and transfer the funds * present in the contract back to the owner. */ contract TimeBasedWill is Ownable { using AddressArrayExtended for address[]; address[] private m_beneficiaries; uint private m_expiryTime; /** * @dev Throw an exception if called before the expiry time */ modifier beforeExpiry { require(now &lt; m_expiryTime, "This action should have been done only BEFORE expiry"); _; } /** * @dev Throw an exception if called after the expiry time */ modifier afterExpiry { require(now &gt;= m_expiryTime, "This action can be done only AFTER expiry"); _; } /** * @dev constructor which sets the original owner * @param expiryDuration timer will be set from now to (now + expiryDuration) * @notice Throws an exception if no funds are added to the contract */ constructor(uint expiryDuration) public payable { require(address(this).balance &gt; 0, "Please add some initial funds to the Will"); require(expiryDuration &gt;= 60, "Expiry time should be atleast 60 sec"); m_expiryTime = now + expiryDuration; } /** * @dev Changes the expiryDuration overriding the previous one * @notice Throws an exception if done after Expiry */ function changeExpiry(uint expiryDuration) onlyOwner beforeExpiry public { m_expiryTime = now + expiryDuration; } /** * @dev Adds the list of addresses as beneficiaries * @notice Throws an exception if onwer is added as benefeciary */ function approveAddresses(address[] beneficiaries) public { for (uint i = 0; i &lt; beneficiaries.length; i++) { addBeneficiary(beneficiaries[i]); } } // As of now, we can enter the same benefeciary multiple times function addBeneficiary(address newBeneficiary) public onlyOwner beforeExpiry { require(newBeneficiary != m_owner, "Cannot add owner as beneficiary"); require(newBeneficiary != address(0), "Enter a valid address"); m_beneficiaries.push(newBeneficiary); } /** * @dev Removes the benefeciary from the list of approved ones * @notice Throws an exception if benefeciary was not added originally */ function removeBeneficiary(address beneficiary) public onlyOwner beforeExpiry { require(m_beneficiaries.removeValue(beneficiary), "Address Not Found"); } /** * @dev Anyone can call this function after Expiry and funds will be transferred * from the contract to the benefeciaries */ function claimOwnership() public payable afterExpiry { uint num_beneficiaries = m_beneficiaries.length; require(num_beneficiaries &gt; 0, "Add some beneficiaries to distribute"); require(address(this).balance &gt;= num_beneficiaries * 1 wei, "Balance should be atleast num_beneficiaries * 1 wei"); uint shareOfAddress = address(this).balance/num_beneficiaries; for (uint i = 0; i &lt; num_beneficiaries; i++) { address value = m_beneficiaries[i]; value.transfer(shareOfAddress); } } /** * @dev The owner can add more funds to the contract */ function addFunds() public payable onlyOwner beforeExpiry { } /** * @dev The owner can remove funds from the contract */ function removeFunds(uint amount) public payable onlyOwner beforeExpiry { require(amount &gt; 0, "Add some value to remove funds"); require(address(this).balance &gt;= amount, "Balance insufficient to remove funds"); m_owner.transfer(amount); } } </code></pre> <p>Arrays.sol</p> <pre><code> pragma solidity ^0.4.23; /** * @dev Extended library for address array */ library AddressArrayExtended { /** * @dev Removes the address *value* from the list of _self[] * @notice Returns false if value is not found */ function removeValue(address[] storage _self, address value) public returns (bool) { require(_self.length &gt; 0, "No values added"); bool foundValue = false; // If found, push the last element to the found index and delete the // last element for (uint i = 0; i &lt; _self.length; i++) { if (_self[i] == value) { _self[i] = _self[_self.length-1]; foundValue = true; break; } } if (foundValue) { delete _self[_self.length-1]; _self.length--; } return foundValue; } } </code></pre> <p>Ownable.sol</p> <pre><code> pragma solidity ^0.4.23; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * Reference: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol */ contract Ownable { address internal m_owner; event OwnershipRenounced(address indexed owner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { m_owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == m_owner, "Only Owner allowed to modify contract"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address new_owner) public onlyOwner { _transferOwnership(new_owner); } function _transferOwnership(address new_owner) internal { require(new_owner != address(0)); emit OwnershipTransferred(m_owner, new_owner); m_owner = new_owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner payable { emit OwnershipRenounced(m_owner); m_owner.transfer(address(this).balance); m_owner = address(0); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T18:05:05.233", "Id": "380436", "Score": "1", "body": "Welcome to Code Review! I don't know whether we have any [tag:solidity] experts around, so it might take a while before this gets reviewed." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T15:45:13.887", "Id": "197357", "Score": "1", "Tags": [ "timer", "blockchain", "solidity" ], "Title": "Solidity code for TimeBasedWill (smart contract)" }
197357
<p>I wrote this class to generate a random "image," similar to a QR code, using strings. How can I make it better (I am a beginner in programming)?</p> <pre><code>import random """ N is the length of squared field to be generated""" class genImg(): def __init__(self, N): self.N = N self.field = [] def genField(self): for i in range(self.N): row = [] for j in range(self.N): row.append("|-|") self.field.append(row[:]) def getField(self): return self.field def fillField(self): field = self.getField() result = "" for i in field: row = "" for j in i: randNum = random.randint(1,100) if randNum % 2 == 0 or randNum % 3 == 0: j = '|0|' row += str(j) + " " result += row[:-1] + "\n" print(result) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T16:48:18.043", "Id": "380417", "Score": "1", "body": "Can you add an example output? I think it will make the question more attractive." } ]
[ { "body": "<ol>\n<li><p><code>genField()</code> generates an empty field. My first assumption given it's name is that it generates a random field. Call it something like <code>genEmptyField()</code> to make this clearer.</p></li>\n<li><p><code>fillField()</code> does not work unless <code>genField()</code> is c...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T16:05:40.877", "Id": "197359", "Score": "3", "Tags": [ "python", "ascii-art" ], "Title": "Generating pattern similar to QR code using strings" }
197359
<p>Rate my code and tell its quality like how well its formatted and all.</p> <p>I want to see how well its written. I have recently started learning Java. so some suggestions will also be appreciated.</p> <pre><code>package e.banksolutions; import java.util.Scanner; import java.util.Random; import java.util.Date; public class EBankSolutions { long accountNumber; // Variable for Storing account number long accountNumberGenerator=0000; // Variable for generating and assigning account number String AccountHolderName; // Variable for Storing account holder name String AccountType; // Variable for Storing account type in string int AccTypeNumVal; long accountBalance; // Variable to Store Current Account Balance. String password; //27-06-2018 //----------------------------------------------------------------------------// public void createAccount() throws InterruptedException { Random rand = new Random(); Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user System.out.println("----------------Welcome to Account Creation Portal-------------------"); //accountNumberGenerator++; //Incrementing the account number generator var accountNumber=rand.nextInt(1000);; //assigning the account number System.out.println("Enter Your Name(Without Space Between Name) : "); AccountHolderName=scan.next(); System.out.println("Enter New Password : "); //27-06-2018 password=scan.next(); //27-06-2018 System.out.println("Enter Your Account Type Savings/Current"); AccountType=scan.next(); /* if(AccountType == "Savings"){ AccTypeNumVal=1; } else if(AccountType == "Current"){ AccTypeNumVal=2; }*/ bal:System.out.println("Enter your starting balance : "); accountBalance=scan.nextLong(); if(accountBalance&lt;5000){ System.out.println("Oops!!! Your Account balance should be minimum 5000 or more.\nYou need to fill the form again."); System.exit(0); } System.out.println("Account Created Successfully.\nYour Account Number is: "+accountNumber+" Please Note it Down."); System.out.println("------------------------------------------------------------"); //Delay code below Thread.sleep(5000); System.out.flush(); } public void DisplayAccount() throws InterruptedException { System.out.println("Displaying Account Information for Account Number : "+accountNumber); System.out.println("------------------------------------------------------------"); System.out.println("Account Number : "+accountNumber); System.out.println("Account Name : "+AccountHolderName); System.out.println("Account Type : "+AccountType); System.out.println("Account balance : "+accountBalance); System.out.println("Your Password : _Hidden_"); //27-06-2018 System.out.println("------------------------------------------------------------"); Thread.sleep(5000); System.out.flush(); } public void DepositAmount() throws InterruptedException { Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user long depositAmt; System.out.println("---------------Welcome to Deposit Portal----------------"); System.out.println("You are Depositing amount for Account Number: "+accountNumber); System.out.println("\nEnter the Amount to Deposit : "); depositAmt=scan.nextLong(); accountBalance=accountBalance+depositAmt; System.out.println("Amount Deposited Successfully.. \nUpdated Balance: "+accountBalance); System.out.println("------------------------------------------------------------"); Thread.sleep(5000); System.out.flush(); } public void WithdrawAmount() throws InterruptedException { Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user long withdrawAmt; System.out.println("---------------Welcome to Deposit Portal----------------"); System.out.println("You are Withdrawing amount for Account Number: "+accountNumber); System.out.println("\nEnter the Amount to Withdraw : "); withdrawAmt=scan.nextLong(); accountBalance=accountBalance-withdrawAmt; System.out.println("Amount Withdrawn Successfully.. \nUpdated Balance: "+accountBalance); System.out.println("------------------------------------------------------------"); Thread.sleep(5000); System.out.flush(); } public void login() throws InterruptedException { int ch=0; Scanner scan = new Scanner(System.in); long accNum=0; String passWd="0"; System.out.println("Enter Account Number : "); accNum=scan.nextLong(); System.out.println("Enter Your Password : "); passWd=scan.next(); if (accNum==this.accountNumber &amp;&amp; passWd.equals(passWd)) { System.out.println("Logged In Successfully with account number: "+accountNumber+"\n-------------------------------------"); System.out.println("Choose Option Number From Below Menu"); System.out.println("1.Deposit Amount\n2.Withdraw Amount\n3.Display Account Info\n4.Close Account\n5.Exit"); ch=scan.nextInt(); switch(ch) { case 1: DepositAmount(); break; case 2: WithdrawAmount(); break; case 3: DisplayAccount(); break; case 4: System.out.println("You cannot close your account. Feature Coming Soon..."); break; case 5: System.exit(0); break; } } else if(accNum!=accountNumber &amp;&amp; passWd!=password) { System.out.println("You have Entered Incorrect Account Number or Password. Please Check Again."); Thread.sleep(5000); System.out.flush(); System.exit(0); } else{ System.out.println("Unknown Error Occured. Try Agian Later"); Thread.sleep(5000); System.out.flush(); System.exit(0); } } EBankSolutions() { accountNumber=0000; AccountHolderName="UNDEFINED"; AccountType="UNDEFINED"; accountBalance=0000; accountNumberGenerator=0000; AccTypeNumVal=9; } public static void main(String[] args) throws InterruptedException { Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user EBankSolutions a1 = new EBankSolutions(); int ch; int i=0; System.out.println("Welcome to Bank E Portal\n"); while(i!=5) { System.out.println("Select any Choice Number From below menu..."); System.out.println("1. Create Account\n2. Login\n3. Exit Portal"); System.out.print("Enter Your Choice Code 1-4: "); ch=scan.nextInt(); switch(ch) { case 1: a1.createAccount(); break; case 2: a1.login(); break; case 3: System.exit(0); break; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T17:19:24.853", "Id": "380425", "Score": "0", "body": "Hey, welcome to Code Review! It would help if you could add a short description of what your code does in the question body." } ]
[ { "body": "<p>Here are my comments in order of veverity:</p>\n\n<h2>Bugs</h2>\n\n<p><strong>1.1 String equality</strong><br>\nMake sure you do that properly (<code>passWd!=password</code>)</p>\n\n<p><strong>1.2 Withdrawal</strong><br>\nThere is no check of the requested amount against the deposit. </p>\n\n<p><s...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T16:11:40.640", "Id": "197360", "Score": "0", "Tags": [ "java", "beginner" ], "Title": "E-Bank Portal Java Application | Console Based" }
197360
<p>I'm attempting to solve <a href="https://open.kattis.com/problems/synchronizinglists" rel="nofollow noreferrer">the problem "Synchronizing Lists" on Kattis.com</a>.</p> <p>In a nutshell, the problem involves being given two lists: the lists are then to be sorted smallest-to-largest, correspondingly indexed elements paired together, then the second list is output, in the original order of the corresponding elements of the first list.</p> <p>While functional, my code runs afoul of the time limit when pitted against the second test case, after I submit it.</p> <pre><code>import sys class Correspondence(): def __init__(self, num1, num2, ID): self.num1 = num1 self.num2 = num2 self.ID = ID def SynchronizeLists(case_size): list1 = [] list2 = [] correspondences = [] results = [] for i in range(case_size): list1.append(int(sys.stdin.readline())) for i in range(case_size): list2.append(int(sys.stdin.readline())) sorted_list1 = list1[:] sorted_list1.sort() sorted_list2 = list2[:] sorted_list2.sort() for i in range(len(sorted_list1)): correspondence = Correspondence(sorted_list1[i], sorted_list2[i], i) correspondences.append(correspondence) for i in list1: results.append([correspondence.num2 for correspondence in correspondences if correspondence.num1 == i][0]) return results output = [] case_size = int(sys.stdin.readline()) while case_size != 0: output.extend(SynchronizeLists(case_size)) output.append('') case_size = int(sys.stdin.readline()) del output[-1] for i in output: print(i) </code></pre> <p>cProfile tells me this: </p> <pre><code> 126 function calls in 1.270 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 2 0.000 0.000 0.000 0.000 &lt;string&gt;:11(SynchronizeLists) 1 0.000 0.000 1.269 1.269 &lt;string&gt;:3(&lt;module&gt;) 11 0.000 0.000 0.000 0.000 &lt;string&gt;:33(&lt;listcomp&gt;) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:5(Correspondence) 11 0.000 0.000 0.000 0.000 &lt;string&gt;:6(__init__) 2 0.000 0.000 0.000 0.000 codecs.py:318(decode) 2 0.000 0.000 0.000 0.000 codecs.py:330(getstate) 2 0.000 0.000 0.000 0.000 {built-in method _codecs.utf_8_decode} 1 0.000 0.000 0.000 0.000 {built-in method builtins.__build_class__} 1 0.001 0.001 1.270 1.270 {built-in method builtins.exec} 2 0.000 0.000 0.000 0.000 {built-in method builtins.len} 12 0.000 0.000 0.000 0.000 {built-in method builtins.print} 46 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 2 0.000 0.000 0.000 0.000 {method 'extend' of 'list' objects} 25 1.269 0.051 1.269 0.051 {method 'readline' of '_io.TextIOWrapper' objects} 4 0.000 0.000 0.000 0.000 {method 'sort' of 'list' objects} </code></pre> <p>I'm not worried about <code>exec</code>, as I suspect that's simply a consequence of how I'm using cProfile. It seems like my biggest time sink involves input: <code>readline()</code>, to be precise.</p> <p>I've already tried swapping out all calls to <code>readline()</code> for calls to <code>input()</code>, but the results barely changed.</p> <p>How can I speed this up?</p>
[]
[ { "body": "<h3>Performance</h3>\n\n<p>The slowness comes from this bit:</p>\n\n<blockquote>\n<pre><code>for i in list1:\n results.append([correspondence.num2 for correspondence in correspondences if correspondence.num1 == i][0])\n</code></pre>\n</blockquote>\n\n<p>What do you think is the time complexity of ...
{ "AcceptedAnswerId": "197372", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T17:52:21.447", "Id": "197366", "Score": "4", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Synchronizing Lists" }
197366
<p>I'm caching the value of a configuration object in a private field:</p> <pre><code>private Configuration _config; public Congifuration Config { get { return _config = _config ?? GetConfig(); } } </code></pre> <p><code>Config</code> is populated by reading a JSON file from disk, so performance is an obvious concern.</p> <p>I like how concise this code is.</p> <p>But I'm wary of assigning on every access. Should I be concerned about performance? And/or (in case I'm missing something) functionality?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T17:58:50.560", "Id": "380432", "Score": "0", "body": "You should be more concerned about posting hypothetical code. Here, we require real code, so if you have any then please post your real world solution." }, { "ContentLice...
[ { "body": "<p>I'm not sure about the on-topicness of this question, it's short but it seems to be fine... I'll risk getting downvoted...</p>\n\n<hr>\n\n<p>As a matter of fact, you could just use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?view=netframework-4.7.2\" rel=\"nofollow noreferr...
{ "AcceptedAnswerId": "197368", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T17:57:35.363", "Id": "197367", "Score": "-1", "Tags": [ "c#", "performance", "lazy" ], "Title": "Shorthand private field caching of public property" }
197367
<p>I have built this small class as a small library to be able to talk to a server that uses <a href="http://www.capesoft.com/accessories/netsp.htm" rel="nofollow noreferrer">CapeSoft's NetTalk library</a> as socket library, and which uses the <a href="http://www.capesoft.com/docs/NetTalk10/NetTalkSimple.Htm" rel="nofollow noreferrer">Whole Packet Protocol</a>, which is a simple protocol made by CapeSoft for the communication between NetTalk Apps. However, I need to talk to this "REST" Server to get some Info for my Node App, and seeing that this Server does not work with Regular HTTP Protocol, I had to write this library myself.</p> <p>I wish to know if there is any way (which I'm sure there is) to better refactor this small class and improve the comprehension of it as well as it's comments in JavaScript.</p> <p>I am trying to improve my refactoring and clean coding skills. I want to be able to write the shortest code while still being simple to understand.</p> <p>I would appreciate much your help to improve this. I really wish to become top programmer.</p> <p>Following is my class module; <strong><em>any critique is welcome and well accepted</em></strong>.</p> <pre><code>const tls = require('tls'); const fs = require('fs'); /** * * * NetTalk Class: * Creates a NetTalk Object for making request to a NetTalk Service in WPP (Whole Packet Protocol). * */ class NetTalk { /** * Creates an instance of NetTalk. * @param {Number} port Port through which you wish to connect to NetTalk. * @param {String} server Server to which to connect. * @param {String} certificate Route where the certificate file (*.pem) is located * @param {String} [verify = '0'] verify the certificate? (default="0") * @memberof NetTalk */ constructor (port, server, certificate, verify = "0") { this.port = port; this.server = server; this.options = {ca:[ fs.readFileSync(certificate) ], rejectUnauthorized: false}; this.msgSize = 0; this.wholePackage = ''; this.socket = null; this.verify = verify; } /** * * Connects to the NetTalk Service. * @memberof NetTalk */ connect() { this.socket = tls.connect(this.port, this.server, this.options, () =&gt; { process.stdin.pipe(this.socket); process.stdin.resume(); }); this.socket.setTimeout(12000) this.socket.setEncoding('ascii'); this.socket.on('end', () =&gt; { console.log('Connection terminated.'); }); this.socket.on('timeout', ()=&gt; { console.log('Connection timed out.'); this.socket.destroy(); }); return new Promise((resolve, reject) =&gt; { this.socket.on('ready', () =&gt; { console.log(`client connected on port ${this.port} to server ${this.server}`); resolve(); }); this.socket.on('error', (err) =&gt; { reject({err:err, func:'connect'}); }); }); } /** * sends the request. * * @param {String} reqMsg Request Message to be sent to the service. * @returns {Promise} {Promise.&lt;resolve(data)|reject(error)&gt;} * @memberof NetTalk */ request(reqMsg) { return new Promise((resolve, reject) =&gt; { /*Adding 32 bit length Integer to the beginning of stream for compatibility with WPP (Whole Packet Protocol).*/ var message = new Buffer(reqMsg, 'binary'); var stream = new Buffer(4 + message.length); //declares the stream to be sent. stream.writeInt32LE(message.length, 0); //Must be in LittleEndian for compatibility. message.copy(stream, 4); this.socket.write(stream); this.socket.on('data', (data) =&gt; { let wholePackageSize = null; this.wholePackage += data; wholePackageSize = new Buffer(this.wholePackage, 'binary'); this.msgSize += data.length; if (wholePackageSize.readInt32LE(0) &lt;= this.msgSize){ this.socket.end(); resolve(this.wholePackage.slice(4, this.wholePackage.length)); } }); this.socket.on('timeout', ()=&gt; { this.socket.destroy(); reject({err:'Error!, server do not respond', func:'request'}) }); this.socket.on('error', err =&gt; { reject({err:err, func:'request'}); }) }); } } module.exports = {NetTalk}; </code></pre> <p>I add the link to the <a href="https://github.com/josnoc/Node-NetTalk-Library/tree/08c3066f92e46700471565278115d677c63e59cb" rel="nofollow noreferrer">GitHub project</a> as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T20:03:02.990", "Id": "380460", "Score": "0", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the titl...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T19:39:18.073", "Id": "197373", "Score": "2", "Tags": [ "javascript", "node.js", "serialization" ], "Title": "Whole Packet Protocol Communication Library in Node" }
197373
<p>Here is a class which I have written to create a simple <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)" rel="nofollow noreferrer">Stack</a> data structure which can be shared across multiple threads. </p> <p>It's a simple LIFO which has 2 operations: one to push onto the top of the stack and the other one to pop from the top of the stack.</p> <p>Please help me to find any issues with it.</p> <pre><code>package com.thread.test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ThreadSafeStack&lt;T&gt; { private List&lt;T&gt; list; private ReentrantReadWriteLock lock; public ThreadSafeStack() { this.list = new ArrayList&lt;T&gt;(); lock = new ReentrantReadWriteLock(); } public T pop() { try { lock.writeLock().lock(); if(!list.isEmpty()) { return list.remove(list.size()-1); } } finally { System.out.println("In finally"); lock.writeLock().unlock(); } return null; } public boolean push(T t) { try { lock.writeLock().lock(); return list.add(t); } finally { lock.writeLock().unlock(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T03:50:34.367", "Id": "380503", "Score": "0", "body": "I'm unfamiliar with thread safety in Java, but from a little research, should your data structure implementation make use of the `synchronized` keyword? I may be wrong if that is...
[ { "body": "<p>It is unclear what you are trying to achieve but one of the below implementations should suit your requirements:</p>\n\n<ul>\n<li><p><a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedDeque.html\" rel=\"nofollow noreferrer\">ConcurrentLinkedDeque</a> {since 1....
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T20:39:10.960", "Id": "197378", "Score": "3", "Tags": [ "java", "stack", "locking" ], "Title": "Threadsafe Stack" }
197378
<p>I am looking for "complete" producer-consumer sample using C++11 memory barrier.</p> <p>(I have derived following example from <a href="http://preshing.com/20130922/acquire-and-release-fences/" rel="nofollow noreferrer">Jeff's article</a> and added a line to make it complete.)</p> <pre><code>void SendTestMessage(void* param) { // Copy to shared memory using non-atomic stores. g_payload.tick = clock(); g_payload.str = "TestMessage"; g_payload.param = param; // Release fence. std::atomic_thread_fence(std::memory_order_release); // Perform an atomic write to indicate that the message is ready. g_guard.store(1, std::memory_order_relaxed); } bool TryReceiveMessage(Message&amp; result) { // Perform an atomic read to check whether the message is ready. int ready = g_guard.load(std::memory_order_relaxed); if (ready != 0) { g_guard.store(0, std::memory_order_relaxed); // Acquire fence. std::atomic_thread_fence(std::memory_order_acquire); // Yes. Copy from shared memory using non-atomic loads. result.tick = g_payload.tick; result.str = g_payload.str; result.param = g_payload.param; return true; } // No. return false; } </code></pre> <p>if you notice, i have added <code>g_guard.store(0, std::memory_order_relaxed);</code> just before acquire. </p> <p>This will help following ways</p> <ol> <li><p>It would avoid <code>TryReciveMessage</code> to cosnume same message if called multiple times before new message is written</p></li> <li><p>It would not add explicit memory fence and hence won't affect performance</p></li> <li>since <code>std::memory_order_relaxed</code> guarantees the ordering, it would get overwritten by <code>SendTestMessage</code> value if new load added after the <code>std::memory_order_acquire</code> is called. So, we will not miss any load.</li> </ol> <p>Please provide your comments and/or suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T21:03:49.253", "Id": "380470", "Score": "0", "body": "Can you provide some more context? Especially in multithreaded code it is very important for us to see how functions are expected to be called. Also, we have no idea what the typ...
[ { "body": "<p>It's always difficult, and sometimes impossible, to review a snippet of code without knowing how it is intended to be used. In this case, I can say confidently that this code will do the job. Whether that happens to be the job <em>you</em> want it to do is another thing entirely.</p>\n\n<p>As long...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T20:52:03.043", "Id": "197379", "Score": "0", "Tags": [ "c++", "c++11", "multithreading", "lock-free", "producer-consumer" ], "Title": "Lock free consumer producer using memory barrier" }
197379
<p>I made a post that follows from this <a href="https://codereview.stackexchange.com/questions/197174/generic-stack-data-structure-using-linked-lists/197180?noredirect=1#comment380142_197180">here</a>. I made most of changes that I could understand from the following link, and here is now an update to that original post. I just want to see if there is any major changes that I need to consider making and perhaps to gain some more insight into how to achieve making those changes.</p> <p>Here is the header file:</p> <pre><code>#ifndef Stack_h #define Stack_h template &lt;class T&gt; class Stack { private: struct Node { T data; Node* next; }; Node* _top; // Used for destructor to delete elements void do_unchecked_pop(); // Use for debugging purposes and for overloading the &lt;&lt; operator void show(std::ostream &amp;str) const; public: // Rule of 5 Stack() : _top(nullptr){} // empty constructor Stack&lt;T&gt;(Stack&lt;T&gt; const&amp; value); // copy constructor Stack&lt;T&gt;(Stack&lt;T&gt;&amp;&amp; move) noexcept; // move constuctor Stack&lt;T&gt;&amp; operator=(Stack&amp;&amp; move) noexcept; // move assignment operator ~Stack(); // destructor // Overload operators Stack&amp; operator=(Stack const&amp; rhs); friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, Stack&lt;T&gt; const&amp; data) { data.show(str); return str; } // Member functions void swap(Stack&amp; other) noexcept; bool empty() const; int size() const; void push(const T&amp; theData); void push(T&amp;&amp; theData); T&amp; top() const; void pop(); }; template &lt;class T&gt; Stack&lt;T&gt;::Stack(Stack&lt;T&gt; const&amp; value) : _top(nullptr) { for(Node* loop = value._top; loop != nullptr; loop = loop-&gt;next) { push(loop-&gt;data); } } template &lt;class T&gt; Stack&lt;T&gt;::Stack(Stack&lt;T&gt;&amp;&amp; move) noexcept : _top(nullptr) { move.swap(*this); } template &lt;class T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::operator=(Stack&lt;T&gt; &amp;&amp;move) noexcept { move.swap(*this); return *this; } template &lt;class T&gt; Stack&lt;T&gt;::~Stack() { while(_top != nullptr) { do_unchecked_pop(); } } template &lt;class T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::operator=(Stack const&amp; rhs) { Stack copy(rhs); swap(copy); return *this; } template &lt;class T&gt; void Stack&lt;T&gt;::swap(Stack&lt;T&gt; &amp;other) noexcept { using std::swap; swap(_top,other.top); } template &lt;class T&gt; bool Stack&lt;T&gt;::empty() const { return _top == nullptr; } template &lt;class T&gt; int Stack&lt;T&gt;::size() const { int size = 0; Node* current = _top; while(current != nullptr) { size++; current = current-&gt;next; } return size; } template &lt;class T&gt; void Stack&lt;T&gt;::push(const T &amp;theData) { Node* newNode = new Node; newNode-&gt;data = theData; newNode-&gt;next = nullptr; if(_top != nullptr) { newNode-&gt;next = _top; } _top = newNode; } template &lt;class T&gt; void Stack&lt;T&gt;::push(T&amp;&amp; theData) { Node* newNode = new Node; newNode-&gt;data = std::move(theData); newNode-&gt;next = nullptr; if(_top != nullptr) { newNode-&gt;next = _top; } _top = newNode; } template &lt;class T&gt; T&amp; Stack&lt;T&gt;::top() const { return _top-&gt;data; } template &lt;class T&gt; void Stack&lt;T&gt;::do_unchecked_pop() { Node* tmp = _top-&gt;next; delete _top; _top = tmp; } template &lt;class T&gt; void Stack&lt;T&gt;::pop() { if(_top == nullptr) { throw std::invalid_argument("the Stack is empty!"); } do_unchecked_pop(); } template &lt;class T&gt; void Stack&lt;T&gt;::show(std::ostream &amp;str) const { for(Node* loop = _top; loop != nullptr; loop = loop-&gt;next) { str &lt;&lt; loop-&gt;data &lt;&lt; "\t"; } str &lt;&lt; "\n"; } #endif /* Stack_h */ </code></pre> <p>Here is the main.cpp file that tests the latter:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;ostream&gt; #include "Stack.h" int main(int argc, const char * argv[]) { /////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// Stack Using Linked List ////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// Stack&lt;int&gt; obj; obj.push(2); obj.push(4); obj.push(6); obj.push(8); obj.push(10); std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Displaying Stack Contents---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Pop Stack Element -------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop(); std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Get the size of stack -------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.size() &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Re-Add Poped Element---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.push(10); std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Print top element --------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.top() &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T23:21:38.173", "Id": "380489", "Score": "0", "body": "Why are you so opposed to having a `Node` constructor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T23:27:48.623", "Id": "380490", "Sco...
[ { "body": "<p>((Note: the code changed while I was writing this review, so it might not match exactly.))</p>\n\n<p>Pretty decent code! There are only a few trouble spots.</p>\n\n<p>I'd start by suggesting that you add the necessary includes to the header file. For example, the class needs <code>std::ostream</co...
{ "AcceptedAnswerId": "197390", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T22:42:47.863", "Id": "197387", "Score": "3", "Tags": [ "c++", "linked-list" ], "Title": "Generic Stack Data Structure Using Linked Lists Follow Up" }
197387
<p>I have an autocomplete implementation in Python, and it passed all of the unit tests that I have included at the bottom.</p> <pre><code>#!python import random import time def get_words(filename): with open(filename, 'r') as f: words_list = f.read().split() return words_list print(words_list) def binarysearch(list_, item, left=None, right=None): if left is None and right is None: left = 0 right = len(list_) - 1 middle = (right + left) // 2 item_length = len(item) middle_item = list_[middle] if middle_item[:item_length].lower() == item.lower(): return find_all_words(list_, item, middle) elif middle_item[:item_length].lower() &lt; item.lower(): return binarysearch(list_, item, middle + 1, right) elif middle_item[:item_length].lower() &gt; item.lower(): return binarysearch(list_, item, left, middle - 1) elif left &gt; right: return None def find_all_words(list_, item, middle): predicted_words = [list_[middle]] item_length = len(item) left_match = True right_match = False left_index = middle right_index = middle while left_match: left_index -= 1 if left_index &lt; 0: left_match = False else: word = list_[left_index] if word[:item_length] == item: predicted_words.append(word) else: left_match = False while right_match: right_index += 1 if right_index &gt;= len(list_): right_match = False else: word = list_[right_index] if word[:item_length] == item: predicted_words.append(word) else: right_match = False return predicted_words def autocomplete(prefix=""): filename = "/usr/share/dict/words" words_list = get_words(filename) predicted_words = binarysearch(words_list, prefix) return predicted_words def benchmark(all_prefixes): t1 = time.time() for prefix in all_prefixes: autocomplete(prefix) t2 = time.time() return t2 - t1 def main(): all_words = get_words('/usr/share/dict/words') all_prefixes = set([word[:len(word)//2] for word in all_words]) time = benchmark(all_prefixes) print('Took {} seconds to benchmark {} prefixes on {} words'.format(time, len(all_prefixes), len(all_words))) # import sys # prefix = sys.argv[1] # words = autocomplete(prefix) # print(words) if __name__ == '__main__': main() # autocomplete_test.py #!python from autocomplete import insert_word from tries import Trie import unittest class TrieTest(unittest.TestCase): def test_init(self): trie = Trie() data, is_word = trie.root.data assert data == "" assert is_word is False assert trie.root.next == {} def test_insert_with_3_items(self): trie = Trie() assert trie.root.data == ('', False) assert trie.root.next == {} trie.insert("a") assert trie.root.next['a'] is not None assert len(trie.root.next) == 1 node = trie.root.next['a'] assert node.data == ('a', True) assert node.next == {} trie.insert("a") assert trie.root.next['a'] is not None assert len(trie.root.next) == 1 node = trie.root.next['a'] assert node.data == ('a', True) assert node.next == {} trie.insert("b") assert trie.root.next['b'] is not None assert len(trie.root.next) == 2 node = trie.root.next['b'] assert node.data == ('b', True) assert node.next == {} trie.insert("c") assert trie.root.next['c'] is not None assert len(trie.root.next) == 3 node = trie.root.next['c'] assert node.data == ('c', True) assert node.next == {} def test_inset_with_7_items(self): trie = Trie() words_list = ['a', 'app', 'apple', 'be', 'bee', 'beat', 'c'] for word in words_list: trie.insert(word) assert trie.root.data == ('', False) assert len(trie.root.next) == 3 assert trie.root.next['a'] is not None node = trie.root.next['a'] assert node.data == ('a', True) assert len(node.next) == 1 assert node.next['p'] is not None node = node.next['p'] assert node.data == ('ap', False) assert len(node.next) == 1 assert node.next['p'] is not None node = node.next['p'] assert node.data == ('app', True) assert len(node.next) == 1 assert node.next['l'] is not None node = node.next['l'] assert node.data == ('appl', False) assert len(node.next) == 1 assert node.next['e'] is not None node = node.next['e'] assert node.data == ('apple', True) assert len(node.next) == 0 assert trie.root.next['b'] is not None node = trie.root.next['b'] assert node.data == ('b', False) assert len(node.next) == 1 assert node.next['e'] is not None node = node.next['e'] assert node.data == ('be', True) assert len(node.next) == 2 assert node.next['e'] is not None node1 = node.next['e'] assert node1.data == ('bee', True) assert len(node1.next) == 0 assert node.next['a'] is not None node2 = node.next['a'] assert node2.data == ('bea', False) assert len(node2.next) == 1 assert node2.next['t'] is not None node = node2.next['t'] assert node.data == ('beat', True) assert len(node.next) == 0 assert trie.root.next['c'] is not None node = trie.root.next['c'] assert node.data == ('c', True) assert len(node.next) == 0 class AutocompleteTest(unittest.TestCase): def test_insert_word(): </code></pre>
[]
[ { "body": "<p>You don't seem to have used the <code>random</code> module, so that import can be deleted. In your first function <code>get_words()</code>, you have put a <code>print(words_list)</code> immediately after an unconditional return, which is unreachable. Unless this is for debugging, it is best to eit...
{ "AcceptedAnswerId": "197722", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-27T22:58:19.723", "Id": "197389", "Score": "3", "Tags": [ "python", "unit-testing", "binary-search", "trie", "autocomplete" ], "Title": "Autocomplete implementation in Python" }
197389
<p>I want to get this code reviewed for a function I wrote that pulls log messages from a MySQL table:</p> <pre><code>def get_logs_messages(request_id, destination=None): """ get logs from deployment table :param int request_id: request id of selected deployment. :param str destination: destination site :return: list of messagesfor selected deployment based on request id. :rtype: list """ conn = MySQLdb.connect(**dbconfig) query = "SELECT deployment_id " \ "from deployment " \ "WHERE request_id={request_id} " \ " {dest}".format( request_id=request_id, dest="AND DESTINATION = '{loc}'".format(loc=destination) if destination else "") cursor = conn.cursor() cursor.execute(query) data = cursor.fetchall() cursor.close() msgs = [] for item in data: query = "SELECT modified_dt , message from scripts_deployment_logs WHERE deployment_id = {}".format(item[0]) cursor = conn.cursor() cursor.execute(query) result = cursor.fetchall() for dt, msg in result: msgs.append("{dt}: {msg}".format(dt=str(dt), msg=msg)) cursor.close() conn.close() return msgs </code></pre> <p>I get a request ID from a web interface which is using a REST API to call this function, and this function retrieves the deployment id based on which it displays the logs. I am not very fluent with the MySQL part so I have used <code>mysql.connector</code> with simple SQL queries.</p>
[]
[ { "body": "<p>Instead of joining the data of two tables in Python, you should une an SQL <a href=\"https://dev.mysql.com/doc/refman/8.0/en/join.html\" rel=\"nofollow noreferrer\">join query</a> to ask the database do the work for you.</p>\n\n<p>You also should not inject parameters directly into the query and l...
{ "AcceptedAnswerId": "197408", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T01:58:21.167", "Id": "197392", "Score": "4", "Tags": [ "python", "performance", "python-2.x", "mysql" ], "Title": "Pulling log messages from a MySQL table" }
197392
<p>Many conditions need to be scanned for the first one that matches a set of tests. If there is a matching condition, that conditions <code>ConfigId</code> should be returned.</p> <p>I have a way to do the matching of conditions, but there are too many <code>continue</code> statements. Is there a better way to perform these checks?</p> <pre><code>private Integer match(List&lt;ConfitionEntity&gt; conditions, ActualDto actualDto) { if (CollectionUtils.isEmpty(conditions)) { return null; } Integer configId = null; for (ConfitionEntity condition : conditions) { boolean match = matchState(condition, actualDto); if (!match) { continue; } match = matchStatus(condition, actualDto); if (!match) { continue; } match = matchType(condition, actualDto); if (!match) { continue; } match = matchPre(condition, actualDto); if (!match) { continue; } match = matchMobile(condition, actualDto); if (!match) { continue; } match = matchAge(condition, actualDto); if (!match) { continue; } match = matchNumber(condition, actualDto); if (!match) { continue; } match = matchPassed(condition, actualDto); if (!match) { continue; } match = matchName(condition, actualDto); if (match) { configId = condition.getConfigId(); break; } } return configId; } </code></pre>
[]
[ { "body": "<p>You could take advantage of short circuit behavior, that is it will stop evaluating at the first \"false\"</p>\n\n<pre><code>for (QueueMsgPushConditionEntity condition : conditions) {\n\n if (matchQueueState(condition.getQueueState(), queueUpdatedDto.getState()) &amp;&amp;\n matchFirstPu...
{ "AcceptedAnswerId": "197396", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T04:00:45.363", "Id": "197394", "Score": "5", "Tags": [ "java" ], "Title": "Getting the right conditional ConfigId" }
197394
<p>I am a bit new to Python. This is my first code review, and I am excited to get a critique on how to make this (very simple) shift cipher more Pythonic, cleaner, and more organized.</p> <pre><code>alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] def shift(offset): message = input("Input Message You Would Like Encrypted:\n") new_message = '' for letter in message: letter = letter.lower() #doesn't handle upper-case yet if letter.isalpha(): shift_pos = alphabet.index(letter) + offset new_pos = alphabet[shift_pos] new_message += new_pos #these will not be shifted elif ' ' or '/t' or '/n' in letter: new_message += letter elif letter.isnumeric(): new_message += letter else: print("An error took place in recording the message. Check input.\n") print(new_message) shift(-1) </code></pre>
[]
[ { "body": "<h2>Bug</h2>\n\n<blockquote>\n<pre><code>elif ' ' or '/t' or '/n' in letter: \n new_message += letter\n</code></pre>\n</blockquote>\n\n<p>Provided that execution reaches that point (i.e. <code>letter.isalpha()</code> is false), this condition always evaluates to <code>True</code>, because the spac...
{ "AcceptedAnswerId": "197398", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T05:23:50.693", "Id": "197397", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "caesar-cipher" ], "Title": "Basic shift cipher in Python" }
197397