body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I used this <a href="https://declarations.com.ua/api/" rel="nofollow noreferrer">API</a> to download some data. </p>
<p>The code is supposed to create a dataframe table using specific fields of an object, and it seems to work, but running slow. </p>
<p>I think it would run faster if I used something instead of <code>json_nomarlize</code>.</p>
<pre class="lang-py prettyprint-override"><code>def create_table(data: List[dict]) -> pd.DataFrame:
"""
Creates pd.DataFrame using `infocard` values,
calculates `income` using `["unified_source"]["step_11"][k]` values.
Note that `[k]` keys are randomly generated.
Please see sample data at the end of the post.
"""
infocard_container = []
step_11_container = []
for i in range(len(data)):
infocard_container.append(json_normalize(data[i]["infocard"]))
step_11_subcontainer = []
try: # if document contains ["unified_source"]["step_11"] field
for k in data[i]["unified_source"]["step_11"].keys():
s_df = json_normalize(data[i]["unified_source"]["step_11"][k])[
["person", "sizeIncome"]
]
income_sum = s_df.loc[s_df["person"].eq("1")].sum()["sizeIncome"]
step_11_subcontainer.append(income_sum)
except KeyError: # if not, NaN would be appended
step_11_subcontainer.append(np.nan)
step_11_container.append(step_11_subcontainer)
df = pd.concat(infocard_container)
df["income"] = [sum(i) for i in step_11_container]
assert len(data) == len(df)
return df
</code></pre>
<hr>
<p>I need all <code>data[0]["infocard"]</code> values, and within <code>data[0]["unified_source"]["step_11"][k]</code> values, I need <code>person</code>, <code>sizeIncome</code> values (and <code>source_ua_company_code</code> if possible - it's not in the code). I'm adding all <code>sizeIncome</code> values if the <code>person</code> == 1</p>
<p>Sample data (data[0]):</p>
<pre class="lang-py prettyprint-override"><code>{'guid': 'nacp_3bb5b983-edd9...',
'infocard': {'first_name': 'NAME',
'patronymic': 'SNAME',
'last_name': 'SURNAME',
'office': '"OFFICE"',
'position': 'POSITION"',
'source': 'NACP',
'id': 'nacp_3bb5b983-edd9...',
'url': 'https://declarations.com.ua/declaration/nacp_3bb5b983-edd9...',
'document_type': 'Yearly',
'is_corrected': False,
'created_date': '2018-03-27T00:00:00',
'declaration_year': 2017},
'raw_source': {'url': 'https://public-api.nazk.gov.ua/v1/declaration/nacp_3bb5b983-edd9...'},
'unified_source': {'step_0': {'declarationType': '1',
'declarationYear1': '2017'},
'step_1': {'actual_cityType': '[hidden]',
'actual_country': '',
'actual_postCode': '[hidden]',
'actual_street': '[hidden]',
'actual_streetType': '[hidden]',
'changedName': False,
'city': '[hidden]',
'cityPath': '[hidden]',
'cityType': '[hidden]',
'city_extendedstatus': '1',
'corruptionAffected': 'No',
'country': '1',
'countryPath': '',
'district': '[hidden]',
'eng_actualAddress': '[hidden]',
'eng_actualPostCode': '[hidden]',
'eng_postCode': '',
'eng_sameRegLivingAddress': '[hidden]',
'firstname': 'NAME',
'housePartNum_extendedstatus': '1',
'lastname': 'SURNAME',
'middlename': 'SNAME',
'postCategory': '',
'postCategory_extendedstatus': '1',
'postCode': '[hidden]',
'postType': '',
'postType_extendedstatus': '1',
'previous_firstname': '',
'previous_lastname': '',
'previous_middlename': '',
'region': '[hidden]',
'responsiblePosition': 'Ні',
'sameRegLivingAddress': '[hidden]',
'street': '[hidden]',
'streetType': '[hidden]',
'ukr_actualAddress': '[hidden]',
'workPlace': 'workPlace',
'workPost': 'workPost',
'dnt_organization_group': 'n'},
'step_11': {'1493274700481': {'incomeSource': 'j',
'iteration': '1493274700481',
'objectType': 'salary',
'otherObjectType': '',
'person': '1',
'rights': {'1': {'citizen': '',
'eng_company_address': '',
'eng_company_code': '',
'eng_company_name': '',
'eng_firstname': '',
'eng_fullname': '',
'eng_lastname': '',
'eng_middlename': '',
'eng_middlename_extendedstatus': '',
'eng_postCode': '',
'eng_postCode_extendedstatus': '',
'otherOwnership': '',
'ownershipType': 'property',
'percent-ownership': '',
'postCode': '[hidden]',
'rightBelongs': '1',
'rights_cityPath': '',
'ua_apartmentsNum_extendedstatus': '',
'ua_city': '',
'ua_company_code': '',
'ua_company_name': '',
'ua_firstname': '',
'ua_houseNum_extendedstatus': '',
'ua_housePartNum_extendedstatus': '',
'ua_lastname': '',
'ua_middlename': '',
'ua_middlename_extendedstatus': '',
'ua_postCode': '',
'ua_postCode_extendedstatus': '',
'ua_street': '[hidden]',
'ua_streetType': '[hidden]',
'ua_street_extendedstatus': '',
'ukr_company_address': '',
'ukr_company_name': '',
'ukr_firstname': '',
'ukr_fullname': '',
'ukr_lastname': '',
'ukr_middlename': '',
'ukr_middlename_extendedstatus': ''}},
'sizeIncome': 44505.0,
'source_citizen': '_',
'source_eng_company_address': '',
'source_eng_company_code': '',
'source_eng_company_name': '',
'source_eng_fullname': '',
'source_ua_company_code': '000000',
'source_ua_company_code_extendedstatus': '0',
'source_ua_company_name': '_',
'source_ua_firstname': '',
'source_ua_lastname': '',
'source_ua_middlename': '',
'source_ua_sameRegLivingAddress': '',
'source_ukr_company_address': '',
'source_ukr_company_name': '',
'source_ukr_fullname': '',
'dnt_sizeIncome_hidden': False,
'dnt_objectType_encoded': 'salarymain',
'dnt_is_foreign': False},
'1493274779231': {'incomeSource': '1',
'iteration': '1493274779231',
'objectType': 'business',
'otherObjectType': '',
'person': '1',
'rights': {'1': {'citizen': '',
'eng_company_address': '',
'eng_company_code': '',
'eng_company_name': '',
'eng_firstname': '',
'eng_fullname': '',
'eng_lastname': '',
'eng_middlename': '',
'eng_middlename_extendedstatus': '',
'eng_postCode': '',
'eng_postCode_extendedstatus': '',
'otherOwnership': '',
'ownershipType': 'property',
'percent-ownership': '',
'postCode': '[hidden]',
'rightBelongs': '1',
'rights_cityPath': '',
'ua_apartmentsNum_extendedstatus': '',
'ua_city': '',
'ua_company_code': '',
'ua_company_name': '',
'ua_firstname': '',
'ua_houseNum_extendedstatus': '',
'ua_housePartNum_extendedstatus': '',
'ua_lastname': '',
'ua_middlename': '',
'ua_middlename_extendedstatus': '',
'ua_postCode': '',
'ua_postCode_extendedstatus': '',
'ua_street': '[hidden]',
'ua_streetType': '[hidden]',
'ua_street_extendedstatus': '',
'ukr_company_address': '',
'ukr_company_name': '',
'ukr_firstname': '',
'ukr_fullname': '',
'ukr_lastname': '',
'ukr_middlename': '',
'ukr_middlename_extendedstatus': ''}},
'sizeIncome': 19100.0,
'source_citizen': '',
'source_eng_company_address': '',
'source_eng_company_code': '',
'source_eng_company_name': '',
'source_eng_fullname': '',
'source_ua_company_code': '',
'source_ua_company_name': '',
'source_ua_firstname': '',
'source_ua_lastname': '',
'source_ua_middlename': '',
'source_ua_sameRegLivingAddress': '',
'source_ukr_company_address': '',
'source_ukr_company_name': '',
'source_ukr_fullname': '',
'dnt_sizeIncome_hidden': False,
'dnt_objectType_encoded': 'business',
'dnt_is_foreign': False},
'1493275433175': {'incomeSource': 'j',
'iteration': '1493275433175',
'objectType': 'pension',
'otherObjectType': '',
'person': '1',
'rights': {'1': {'citizen': '',
'eng_company_address': '',
'eng_company_code': '',
'eng_company_name': '',
'eng_firstname': '',
'eng_fullname': '',
'eng_lastname': '',
'eng_middlename': '',
'eng_middlename_extendedstatus': '',
'eng_postCode': '',
'eng_postCode_extendedstatus': '',
'otherOwnership': '',
'ownershipType': 'property',
'percent-ownership': '',
'postCode': '[hidden]',
'rightBelongs': '1',
'rights_cityPath': '',
'ua_apartmentsNum_extendedstatus': '',
'ua_city': '',
'ua_company_code': '',
'ua_company_name': '',
'ua_firstname': '',
'ua_houseNum_extendedstatus': '',
'ua_housePartNum_extendedstatus': '',
'ua_lastname': '',
'ua_middlename': '',
'ua_middlename_extendedstatus': '',
'ua_postCode': '',
'ua_postCode_extendedstatus': '',
'ua_street': '[hidden]',
'ua_streetType': '[hidden]',
'ua_street_extendedstatus': '',
'ukr_company_address': '',
'ukr_company_name': '',
'ukr_firstname': '',
'ukr_fullname': '',
'ukr_lastname': '',
'ukr_middlename': '',
'ukr_middlename_extendedstatus': ''}},
'sizeIncome': 20075.0,
'source_citizen': '_',
'source_eng_company_address': '',
'source_eng_company_code': '',
'source_eng_company_name': '',
'source_eng_fullname': '',
'source_ua_company_code': '',
'source_ua_company_code_extendedstatus': '2',
'source_ua_company_name': '_',
'source_ua_firstname': '',
'source_ua_lastname': '',
'source_ua_middlename': '',
'source_ua_sameRegLivingAddress': '',
'source_ukr_company_address': '',
'source_ukr_company_name': '',
'source_ukr_fullname': '',
'dnt_sizeIncome_hidden': False,
'dnt_objectType_encoded': 'pension',
'dnt_is_foreign': False}},
'step_3': {'1493273226784': {'city': '[hidden]',
'cityPath': '[hidden]',
'costAssessment': 0,
'costAssessment_extendedstatus': '2',
'costDate': 0,
'costDate_extendedstatus': '2',
'country': '1',
'district': '[hidden]',
'iteration': '1493273226784',
'objectType': '_',
'otherObjectType': '',
'owningDate': 'date',
'person': '1',
'postCode': '[hidden]',
'regNumber_extendedstatus': '1',
'region': '[hidden]',
'rights': {'1': {'citizen': '',
'eng_company_address': '',
'eng_company_code': '',
'eng_company_name': '',
'eng_firstname': '',
'eng_fullname': '',
'eng_lastname': '',
'eng_middlename': '',
'eng_middlename_extendedstatus': '',
'eng_postCode': '',
'eng_postCode_extendedstatus': '',
'otherOwnership': '',
'ownershipType': '_',
'percent-ownership': '50',
'postCode': '[hidden]',
'rightBelongs': '1',
'rights_cityPath': '',
'ua_apartmentsNum_extendedstatus': '',
'ua_city': '',
'ua_company_code': '',
'ua_company_name': '',
'ua_firstname': '',
'ua_houseNum_extendedstatus': '',
'ua_housePartNum_extendedstatus': '',
'ua_lastname': '',
'ua_middlename': '',
'ua_middlename_extendedstatus': '',
'ua_postCode': '',
'ua_postCode_extendedstatus': '',
'ua_street': '[hidden]',
'ua_streetType': '[hidden]',
'ua_street_extendedstatus': '',
'ukr_company_address': '',
'ukr_company_name': '',
'ukr_firstname': '',
'ukr_fullname': '',
'ukr_lastname': '',
'ukr_middlename': '',
'ukr_middlename_extendedstatus': '',
'dnt_ownershipType_encoded': 'ownproperty'}},
'totalArea': 32.3,
'ua_cityType': '_',
'ua_housePartNum_extendedstatus': '1',
'ua_postCode': '_',
'ua_street': '[hidden]',
'ua_streetType': '[hidden]',
'dnt_costDate_hidden': True,
'dnt_costAssessment_hidden': True,
'dnt_totalArea_hidden': False,
'dnt_objectType_encoded': 'apt'}}},
'related_entities': {'people': {'family': []},
'documents': {'corrected': [], 'originals': []},
'companies': {'owned': [], 'related': ['_'], 'all': ['_']}}}
</code></pre>
|
[] |
[
{
"body": "<p>Use some generators.</p>\n\n<p>Separate out your logic for iterating through your data. For instance, don't form a \"subcontainer\" list at all since you're just summing it. Also, use <code>values()</code> instead of <code>keys()</code> for your situation.</p>\n\n<pre><code>def step_11(datum: dict)\n for v in datum[\"unified_source\"][\"step_11\"].values():\n s_df = json_normalize(v)[\n [\"person\", \"sizeIncome\"]\n ]\n yield s_df.loc[s_df[\"person\"].eq(\"1\")].sum()[\"sizeIncome\"]\n\n...\ndf['income'] = [sum(step_11(d)) for d in data]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:20:45.420",
"Id": "446630",
"Score": "1",
"body": "`data` and `i` will raise a `NameError` unless they are global. Should this be `for v in datum[...].values()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:23:35.433",
"Id": "446631",
"Score": "0",
"body": "Yep - thank you; edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T08:06:36.227",
"Id": "446743",
"Score": "0",
"body": "@Reinderien that's just perfect, thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:31:52.257",
"Id": "229510",
"ParentId": "229500",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T10:39:10.120",
"Id": "229500",
"Score": "3",
"Tags": [
"python",
"pandas",
"hash-map"
],
"Title": "How do I efficiently create a dataframe from a list of dictionaries?"
}
|
229500
|
<p>This question was given in my college assignment to be done in C. After doing that, I rewrote the program again in rust.
I come from a C/Python background and this is my first rust program. Please critique it.
The Program is given inputs in the following format</p>
<pre><code>{num_items} {max_weight}
{item_weight_1} ... {item_weight_num_items}
</code></pre>
<p>The output is the number of items and the indices of the chosen items to be put in the bag</p>
<pre class="lang-rust prettyprint-override"><code>use std::io::{self, BufRead};
fn main() {
let reader = io::stdin();
let top_line: Vec<i32> = reader
.lock()
.lines()
.next()
.unwrap()
.unwrap()
.trim()
.split(' ')
.map(|s| s.parse().unwrap())
.collect();
let num_items: i32 = top_line[0];
let max_weight: i32 = top_line[1];
let items: Vec<i32> = reader
.lock()
.lines()
.next()
.unwrap()
.unwrap()
.trim()
.split(' ')
.map(|s| s.parse().unwrap())
.collect();
let s: (i32, i32) = (1..1 << num_items)
.map(|i| {
(
items
.iter()
.enumerate()
.filter(|&(t, _)| (i >> t & 1 == 1))
.map(|(_, elem)| elem.clone())
.sum::<i32>(),
i,
)
})
.map(|(elem, i)| (max_weight - elem, i))
.filter(|&(elem, _)| (elem >= 0))
.min_by(|(a, _), (b, _)| a.cmp(&b))
.unwrap();
let ans: Vec<i32> = (0..num_items)
.filter(|&t| (s.1 >> t & 1 == 1))
.map(|t| t + 1)
.collect();
println!("{}", ans.len());
println!(
"{}",
ans.iter()
.fold(String::new(), |acc, &arg| acc + &arg.to_string() + " ")
);
}
</code></pre>
<p>Example input</p>
<pre><code>6 44
14 13 21 8 56 3
</code></pre>
<p>Example output</p>
<pre><code>3
1 4 3
</code></pre>
|
[] |
[
{
"body": "<h2>General</h2>\n\n<ol>\n<li>You don't have any comments. I recommend you document what basic blocks of code are doing</li>\n<li>I recommend factoring out the parsing and algorithm parts of your code into different functions.</li>\n<li>Why prompt the user for the number of input items? You can trivially detect it from the second line input, unless this specifies a different value.</li>\n<li>Non-descriptive variable names: What does <code>s</code> contain? What does <code>ans</code> mean?</li>\n<li>The <code>itertools</code> crate is super helpful whenever iterators are involved</li>\n</ol>\n\n<h2>Input Capture / Parsing</h2>\n\n<ol>\n<li>Read in both lines at once: <code>let lines = io::stdin().lock().lines().take(2);</code></li>\n<li>Map over those lines, parsing the integers:</li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>let mut numbers = lines.map(|line| {\n line\n .trim()\n .split(' ')\n .map(|s| s.parse::<i32>().unwrap())\n});\n</code></pre>\n\n<ol start=\"3\">\n<li>Split the first line:</li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>let first_line = numbers.next().unwrap().take(2).collect::<Vec<_>>();\nassert_eq!(first_line.len(), 2);\n\nlet num_items = first_line[0];\nlet max_weights = first_line[1];\n</code></pre>\n\n<ol start=\"4\">\n<li>And grab the items from the second line: <code>let items = numbers.next().unwrap().collect::<Vec<_>>();</code></li>\n</ol>\n\n<h2>Algorithm Part 1 (<code>s</code>)</h2>\n\n<ol>\n<li>I'd specify the range as <code>1..(1 << num_items)</code> to really make clear that second <code>1</code> is being shifted, not the whole range.</li>\n<li>Personally, I prefer my tuples to be easily spotted. I'd set the iteration result a variable then use that in the tuple:</li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>.map(|i| {\n let sum = items\n .iter()\n .enumerate()\n .filter(|&(t, _)| (i >> t & 1 == 1))\n .map(|(_, elem)| elem.clone())\n .sum::<i32>();\n (sum, i)\n})\n</code></pre>\n\n<ol start=\"3\">\n<li>It's unclear what <code>.filter(|&(t, _)| (i >> t & 1 == 1))</code> is doing here, but usually bitwise comparisons can be expressed more clearly with other operations.</li>\n<li>Additionally, <code>i</code> and <code>t</code> should probably be renamed to be more clear.</li>\n<li>Also, those extra parenthesis around the closure return value should instead be used to group whichever operation takes precedence for clarity of the expression</li>\n<li><code>.map(|(_, elem)| elem.clone())</code> I think can be replaced with <code>.map(|(_, &elem)| elem)</code></li>\n<li>Recommend returning <code>(i, sum)</code> instead of <code>(sum, i)</code> to better match the pattern of <code>enumerate</code></li>\n<li>Extra parenthesis around the return value in <code>.filter(|&(elem, _)| (elem >= 0))</code></li>\n<li>I think <code>.min_by(|(a, _), (b, _)| a.cmp(&b))</code> can be replaced with <code>.min_by_key(|(x, _)| x)</code></li>\n<li>Doesn't look like you ever use <code>s.0</code> so you can ignore it with <code>let (_, s): (i32, i32) = ...</code></li>\n<li>In fact, it doesn't look like you use the <code>i</code> index at all after the first <code>.map(|i| {</code> so you don't need to pass it through the rest of the chain.</li>\n</ol>\n\n<h2>Algorithm Part 2 (<code>ans</code>)</h2>\n\n<ol>\n<li>You repeat <code>(x >> t & 1 == 1)</code> twice: here and above. Perhaps move it to a clearly-named function?</li>\n<li>I'd store the <code>ans.iter().fold(...)</code> in a variable before printing the result. Makes the eventual format string output easier to predict.</li>\n<li>Suggest using <code>format!</code> in the <code>fold</code>:</li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>.fold(|out, &num| format!(\"{}{} \", out, num))\n</code></pre>\n\n<ol start=\"4\">\n<li>Alternatively, you could use <code>join</code> instead of the <code>fold</code>:</li>\n</ol>\n\n<pre class=\"lang-rust prettyprint-override\"><code>ans.into_iter().map(|x| x.to_string()).collect::<Vec<_>>().join(\" \")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T21:08:25.123",
"Id": "229536",
"ParentId": "229502",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T10:55:13.963",
"Id": "229502",
"Score": "4",
"Tags": [
"beginner",
"rust",
"knapsack-problem"
],
"Title": "Solving the knapsack problem with user provided input"
}
|
229502
|
<p>I had a read about classes, <code>def</code>, <code>self</code>, <code>master</code>, <code>*args</code>, <code>**kwargs</code>, <code>__init__</code> and roots. Still trying to get my head around the whole thing.</p>
<p>I am struggling to structure my current code into classes and defs.</p>
<p>Here is my current code (below). It works perfectly fine, but I need to re-code it, re-structure it with classes, as I have been given a feedback from <a href="https://codereview.stackexchange.com/a/229330/">@BryanOakley</a> to structure it with classes:</p>
<pre><code>from tkinter import *
from tkinter.ttk import *
import glob
import os
from PIL import Image, ImageTk, ImageGrab
import tkinter as tk
import pyautogui
import datetime
import time
from pathlib import Path
#date & time
now = datetime.datetime.now()
root = tk.Tk()
root.title("SIGN OFF")
root.minsize(840, 400)
root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file='C:/Users/label/Desktop/Sign off project/tick.ico'))
# Frames
left_frame = tk.Frame()
right_frame = tk.Frame()
left_frame.pack(side="left", fill="both", expand=True)
right_frame.pack(side="right", fill="both", expand=True)
# Create a Tkinter variable
tkvar = tk.StringVar(root)
# Directory
directory = "C:/Users/label/Desktop/Sign off Project/sign off img"
choices = glob.glob(os.path.join(directory, "*.jpg"))
tkvar.set('...To Sign Off...') # set the default option
# On change dropdown callback.
def change_dropdown(*args):
""" Updates label2 image. """
imgpath = tkvar.get()
img = Image.open(imgpath)
img = img.resize((529,361))
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
p = None
def func(value):
global p
p = Path(value)
print('req:', p)
#Seperating widgets
choose_label = tk.Label(left_frame, text="Choose your sign off here:")
popupMenu = tk.OptionMenu(left_frame, tkvar, *choices,command = func)
display_label = label2 = tk.Label(left_frame, image=None)
open_button = tk.Button(left_frame, text="Open", command=change_dropdown)
choose_label.grid(row=1, column=1)
popupMenu.grid(row=2, column=1)
display_label.grid(row=3, column=1)
open_button.grid(row=4, column=1)
def user():
tk.Label(right_frame, text= "User: ", font = 'Helvetica 18 bold').grid(column = 1, row = 0, sticky = W)
user_input = os.getlogin()
tk.Label(right_frame, text = user_input, font='Helvetica 18 bold').grid(column = 1, row = 0, sticky = N)
user()
def var_states():
text_file = open("logfile.txt", "a")
text_file.write("TIME: %s, USER: %s, One %d, Two %d, Three %d, Four %d, Five %d, Six %d, Seven %d, Eight %d, Nine %d, Ten %d, Eleven %d, Twelve %d, Func %s\n" % (now,os.getlogin(), var1.get(), var2.get(), var3.get(), var4.get(), var5.get(), var6.get(), var7.get(), var8.get(), var9.get(), var10.get(), var11.get(), var12.get(), p))
text_file.close()
#checkboxes
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
var4 = IntVar()
var5 = IntVar()
var6 = IntVar()
var7 = IntVar()
var8 = IntVar()
var9 = IntVar()
var10 = IntVar()
var11 = IntVar()
var12 = IntVar()
tk.Checkbutton(right_frame, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1).grid(column = 1, row = 1, sticky = W)
tk.Checkbutton(right_frame, text="May Contain Statement.", variable=var2).grid(column = 1, row = 2, sticky = W)
tk.Checkbutton(right_frame, text="Cocoa Content (%).", variable=var3).grid(column = 1, row = 3, sticky = W)
tk.Checkbutton(right_frame, text="Vegetable fat in addition to Cocoa butter", variable=var4).grid(column = 1, row = 4, sticky = W)
tk.Checkbutton(right_frame, text="Instructions for Use.", variable=var5).grid(column = 1, row = 5, sticky = W)
tk.Checkbutton(right_frame, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6).grid(column = 1, row = 5, sticky = W)
tk.Checkbutton(right_frame, text="Nutritional Information Visible", variable=var7).grid(column = 1, row = 7, sticky = W)
tk.Checkbutton(right_frame, text="Storage Conditions", variable=var8).grid(column = 1, row = 8, sticky = W)
tk.Checkbutton(right_frame, text="Best Before & Batch Information", variable=var9).grid(column = 1, row = 9, sticky = W)
tk.Checkbutton(right_frame, text="Net Weight & Correct Font Size.", variable=var10).grid(column = 1, row = 10, sticky = W)
tk.Checkbutton(right_frame, text="Barcode - Inner", variable=var11).grid(column = 1, row = 11, sticky = W)
tk.Checkbutton(right_frame, text="Address & contact details correct", variable=var12).grid(column = 1, row = 12, sticky = W)
def save():
var_states()
tk.Button(right_frame, text = "Save", command = save).grid(column = 1, row = 13, sticky = W)
root.mainloop()
</code></pre>
<p>What needs to be put into classes and what doesn't? I was thinking of having a <code>left_frame</code> and <code>right_frame</code> as two separate classes, or is that not needed?</p>
<p><strong>UPDATE</strong></p>
<p>Here is where I got to.. Am I heading in the right direction?</p>
<pre><code>from tkinter import *
from tkinter import ttk
import glob
import os
from PIL import Image, ImageTk, ImageGrab
import tkinter as tk
import pyautogui
import datetime
import time
from pathlib import Path
class App:
def __init__(self, master):
#frames
left_frame = Frame(master)
right_frame = Frame(master)
left_frame.pack(side="left", fill="both", expand=True)
right_frame.pack(side="right", fill="both", expand=True)
# Create a Tkinter variable
App.tkvar = StringVar()
# Directory
directory = "C:/Users/label/Desktop/Sign off Project/sign off img"
choices = glob.glob(os.path.join(directory, "*.jpg"))
App.tkvar.set('...To Sign Off...') # set the default option
# On change dropdown callback.
def change_dropdown(*args):
""" Updates label2 image. """
imgpath = App.tkvar.get()
img = Image.open(imgpath)
img = img.resize((529,361))
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
#Seperating widgets
self.choose_label = Label(left_frame, text="Choose your sign off here:")
self.popupMenu = OptionMenu(left_frame, App.tkvar, *choices)
self.display_label = label2 = Label(left_frame, image=None)
self.open_button = Button(left_frame, text="Open", command=change_dropdown)
self.choose_label.grid(row=1, column=1)
self.popupMenu.grid(row=2, column=1)
self.display_label.grid(row=3, column=1)
self.open_button.grid(row=4, column=1)
root = Tk()
root.minsize(840, 400)
app = App(root)
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:32:37.883",
"Id": "446443",
"Score": "0",
"body": "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 the title to simply state the task accomplished by the code. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<h2>Import sanity</h2>\n\n<p>These three:</p>\n\n<pre><code>from tkinter import *\nfrom tkinter.ttk import *\nimport tkinter as tk\n</code></pre>\n\n<p>are not all needed at the same time. The first is the messiest - it simply floods your namespace with all tk symbols. The second is similarly messy. You're better off with:</p>\n\n<pre><code>import tkinter as tk\nimport tkinter.ttk as ttk\n</code></pre>\n\n<h2>Path handling</h2>\n\n<p>Especially since you're in Windows, you should rethink your handling of paths. This:</p>\n\n<pre><code>directory = \"C:/Users/label/Desktop/Sign off Project/sign off img\"\nchoices = glob.glob(os.path.join(directory, \"*.jpg\"))\n</code></pre>\n\n<p>has a few issues. You should probably be using a relative path, first of all. Using an absolute path in a situation like this creates more complicated and fragile code.</p>\n\n<p>Also, consider using the stuff from <code>pathlib</code> to simplify and clean up your filename operations.</p>\n\n<p>My <em>guess</em> is that you'll end up with something like:</p>\n\n<pre><code>from pathlib import Path\n\nchoices = Path('sign off img').glob('*.jpg')\n</code></pre>\n\n<h2>Args</h2>\n\n<pre><code>def change_dropdown(*args):\n</code></pre>\n\n<p><a href=\"https://effbot.org/tkinterbook/button.htm#Tkinter.Button.config-method\" rel=\"nofollow noreferrer\">The documentation</a> does not mention any args to the callback - so simply delete <code>*args</code>.</p>\n\n<h2>Global code</h2>\n\n<pre><code>root = Tk()\nroot.minsize(840, 400)\napp = App(root)\nroot.mainloop()\n</code></pre>\n\n<p>Put this in a main function:</p>\n\n<pre><code>def main():\n root = Tk()\n root.minsize(840, 400)\n app = App(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:59:01.427",
"Id": "229507",
"ParentId": "229503",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229507",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T11:24:10.807",
"Id": "229503",
"Score": "3",
"Tags": [
"python",
"gui",
"tkinter"
],
"Title": "How to structure tkinter with classes?"
}
|
229503
|
<p>I'm very new to C++ and made this code using the Eigen library to port an old and slow python code which computes the three-dimensional proper orthogonal decomposition (POD) from a set of temporal point cloud data.</p>
<p>In this case the data is a obtained from a CFD (computational fluid dynamics) simulation as a cloud of 106x60x60 points and for each point three velocity components are written. An example can be seen <a href="https://drive.google.com/open?id=1Gk-QczvFPfL1F6vixsPvvPd3WUejiX9n" rel="nofollow noreferrer">here</a>. It is stored in the input/OFout folder. The physical time associated with each cloud is retrieved from the times.txt file.</p>
<p>This data is concatenated in a big matrix which is used for several mathematical operations like calculating a projection matrix, obtaining the eigenvalues and eigenvectors of it and calculating the POD modes. Finally, these modes are written out to different files in the output/mode folder.</p>
<p>My aim is to improve both the C++ aspect (syntax, making it easier to read, more idiomatic, object oriented...) as well as the performance of the code. Tips/pointers regarding how to parallelise it would also be nice.</p>
<p>The code I wrote is the following:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <Eigen/Dense>
#define MSIZE 381600 // Rows of matrix (number of points)
#define TSIZE 1804 // Size of time data (number of snapshots)
#define VSIZE 3 // Size of the variable (1 if scalar, 3 if vector)
#define NSIZE 20 // Size of output POD modes (number of modes to write)
using namespace Eigen;
int main()
{
MatrixXd m = MatrixXd::Zero(MSIZE * VSIZE, TSIZE);
MatrixXd pm = MatrixXd::Zero(TSIZE, TSIZE);
// READING INPUT FILES
std::string t;
std::string timedir = "../input/times.txt";
std::ifstream timefile(timedir);
std::cout << t << std::endl;
for (size_t k = 0; k < TSIZE; k++)
{
if (timefile.is_open())
{
timefile >> t;
while (t.back() == '0') // Remove trailing zeros
{
t.pop_back();
}
}
std::string dir = "../input/OFout/" + t + "/pointCloud_U.xy";
std::ifstream file(dir);
if (file.is_open())
{
for (size_t i = 0; i < MSIZE; i++)
{
for (size_t j = 0; j < VSIZE; j++)
{
file >> m(i + MSIZE * j, k);
}
}
std::cout << "Finished reading file " + std::to_string(k + 1) + " of " + std::to_string(TSIZE) << std::endl;
file.close();
}
else
{
std::cout << "Unable to open file" << std::endl;
}
}
// COMPUTING NORMALISED PROJECTION MATRIX
std::cout << "Computing projection matrix..." << std::flush;
for (size_t i = 0; i < TSIZE; i++)
{
for (size_t j = 0; j < TSIZE; j++)
{
pm(i, j) = (1.0 / TSIZE) * (m.col(i).dot(m.col(j).transpose()));
}
}
std::cout << " Done" << std::endl;
// COMPUTING SORTED EIGENVALUES AND EIGENVECTORS
std::cout << "Computing eigenvalues..." << std::flush;
SelfAdjointEigenSolver<MatrixXd>
eigensolver(pm);
if (eigensolver.info() != Success)
abort();
VectorXd eigval = eigensolver.eigenvalues().reverse();
MatrixXd eigvec = eigensolver.eigenvectors().rowwise().reverse();
std::cout << " Done" << std::endl;
// COMPUTING POD MODES
std::cout << "Computing POD modes..." << std::flush;
MatrixXd podx = MatrixXd::Zero(MSIZE, TSIZE);
MatrixXd pody = MatrixXd::Zero(MSIZE, TSIZE);
MatrixXd podz = MatrixXd::Zero(MSIZE, TSIZE);
for (size_t i = 0; i < TSIZE; i++)
{
for (size_t j = 0; j < TSIZE; j++)
{
podx.col(i) = podx.col(i) + (1.0 / (eigval(i) * TSIZE)) * sqrt(eigval(i) * TSIZE) * eigvec(j, i) * m.block<MSIZE, 1>(0 * MSIZE, j);
pody.col(i) = pody.col(i) + (1.0 / (eigval(i) * TSIZE)) * sqrt(eigval(i) * TSIZE) * eigvec(j, i) * m.block<MSIZE, 1>(1 * MSIZE, j);
podz.col(i) = podz.col(i) + (1.0 / (eigval(i) * TSIZE)) * sqrt(eigval(i) * TSIZE) * eigvec(j, i) * m.block<MSIZE, 1>(2 * MSIZE, j);
}
}
std::cout << " Done" << std::endl;
// WRITING SORTED EIGENVALUES
std::cout << "Writing eigenvalues..." << std::flush;
std::ofstream writeEigval("../output/chronos/A.txt");
if (writeEigval.is_open())
{
writeEigval << std::scientific << std::setprecision(10) << eigval;
writeEigval.close();
}
std::cout << " Done" << std::endl;
// WRITING CHRONOS
std::cout << "Writing chronos..." << std::flush;
for (size_t i = 0; i < NSIZE; i++)
{
std::string chronos = "../output/chronos/chronos_" + std::to_string(i) + ".dat";
std::ofstream writeChronos(chronos);
for (size_t j = 0; j < TSIZE; j++)
{
writeChronos << std::scientific << std::setprecision(10) << sqrt(eigval(i) * TSIZE) * eigvec(j, i) << '\n';
}
writeChronos.close();
}
std::cout << " Done" << std::endl;
// WRITING POD MODES
std::cout << "Writing POD modes..." << std::flush;
std::string xyz = "xyz_";
std::string modeHead = "../output/mode/mode_U";
for (size_t j = 0; j < VSIZE; j++)
{
for (size_t i = 0; i < NSIZE; i++)
{
std::string modeTail = std::to_string(i) + ".dat";
std::ofstream writeMode(modeHead + xyz.at(j) + xyz.at(3) + modeTail);
if (writeMode.is_open())
{
if (j == 0)
{
writeMode << std::scientific << std::setprecision(6) << podx.col(i);
}
else if (j == 1)
{
writeMode << std::scientific << std::setprecision(6) << pody.col(i);
}
else if (j == 2)
{
writeMode << std::scientific << std::setprecision(6) << podz.col(i);
}
writeMode.close();
}
}
}
std::cout << " Done" << std::endl;
}
</code></pre>
<p>Thanks for your insights!</p>
|
[] |
[
{
"body": "<ol>\n<li>Instead of <code>#define</code> use <code>enum</code> or <code>constexpr</code> for the constant numbers.</li>\n<li>I don't think that the number of time data or number of points should be absolute constants - rather they should be determined during runtime. Else you have to recompile your code each time you receive new data.</li>\n<li>Better declare some sort of output path instead of relying on <code>../</code>, also you need to make sure that the directories exist, else it will fail to save.</li>\n<li>You don't want to store small pieces of data over huge amount of files and directories. Better make a serialization standard for yourselves and store a sizable amount of data inside each file. Also, consider binary save/load for better speed, accuracy, and consistency, though, it will be less readable for humans and portability might suffer a bit - some odd platforms use less common endianess.</li>\n<li><p>You can speed up the loop</p>\n\n<pre><code>for (size_t i = 0; i < TSIZE; i++)\n{\n for (size_t j = 0; j <= i; j++)\n {\n pm(j, i) = pm(i, j) = (1.0 / TSIZE) * (m.col(i).dot(m.col(j).transpose()));\n }\n}\n</code></pre>\n\n<p>Note: by <code>dot</code> function I expect to see scalar pruduct, so it is odd for me to see that you transpose the vector inside it. Use operator * for matrix multiplication.</p></li>\n<li><p>I am not too familiar with these Matrices classes, but most likely, it will be better if you replace</p>\n\n<pre><code>podx.col(i) = podx.col(i) + (1.0 / (eigval(i) * TSIZE)) * sqrt(eigval(i) * TSIZE) * eigvec(j, i) * m.block<MSIZE, 1>(0 * MSIZE, j);\n</code></pre>\n\n<p>with</p>\n\n<pre><code>podx.col(i) += (eigvec(j, i) / sqrt(eigval(i) * TSIZE)) * m.block<MSIZE, 1>(0 * MSIZE, j);\n</code></pre>\n\n<p>also, what to do if <code>eigval(i) == 0.</code> or too close to it?</p></li>\n<li>If you plan to grow your project you'd better eventually replace <code>std::cout</code> with a usage of a logger class as <code>std::cout</code> is not thread friendly despite being technically thread safe. Also, in this, case move the code inside a class and each relevant section move inside a function with a sensible name.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T10:47:49.717",
"Id": "449354",
"Score": "0",
"body": "\"Instead of `#define` use `enum` for the constant numbers.\" No, use `constexpr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:22:37.637",
"Id": "449369",
"Score": "0",
"body": "@L.F. I see constexpr being better when you require computation or non trivial classes. But for simple integer constants?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:31:03.267",
"Id": "449370",
"Score": "0",
"body": "Still better. For both semantics and consistency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:35:53.897",
"Id": "449372",
"Score": "0",
"body": "@L.F. edited and made recommendation for both."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T07:19:51.413",
"Id": "230586",
"ParentId": "229504",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T11:47:02.643",
"Id": "229504",
"Score": "4",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "3D Proper Orthogonal Decomposition: C++ implementation"
}
|
229504
|
<p>I have a worksheet I use with a small handful of colleagues on a daily basis to share information with about orders we place. To make sure we always have the same up to date info we use a shared excel workbook I created. I know this is not preferred, but this is all that is available in my company.</p>
<p>To prevent us from overwriting our existing data with new orders I created this code:</p>
<pre class="lang-vb prettyprint-override"><code>If ActiveWorkbook.MultiUserEditing Then 'in case of multiple users, make sure all data is accepted.
ActiveWorkbook.AcceptAllChanges
End If
ActiveWorkbook.Save 'save to retrieve latest version from server.
Sheets("Database").AutoFilterMode = False 'disengage autofilter so hidden lines won't be overwritten
Dim I As String
If Sheet2.Range("A:A").Find(What:=User(), LookIn:=xlValues) Is Nothing Then
I = Sheet2.Range("A" & Rows.Count).End(xlUp).Row + 1 'determine next available blank row.
Else
I = Sheet2.Range("A:A").Find(What:=User(), LookIn:=xlValues).Row
End If
Range("Database!A" & I).Value = User()
ActiveWorkbook.Save
Dim MyLine(0 To 15) As Variant
MyLine(0) = Application.WorksheetFunction.Max(Range("Database!A:A")) + 1 'determine next available line number and auto-fill on next blank row.
If Range("Form!C6") = "" Then 'if multi-line box is empty, copy over material type box.
MyLine(1) = Range("Form!B3").Value
Else 'if multi-line box is filled, copy over multi-line box.
MyLine(1) = Range("Form!C6").Value
End If
MyLine(2) = Range("Form!B4").Value 'copy over all info filled in the form to next blank row on database
MyLine(3) = Range("Form!B5").Value
MyLine(4) = Range("Form!B6").Value
MyLine(5) = Range("Form!B7").Value
MyLine(6) = Range("Form!B8").Value
MyLine(7) = "LA" & Range("Form!B9").Value
MyLine(8) = Range("Form!B10").Value
MyLine(10) = Range("Form!B11").Value
MyLine(9) = Range("Maintenance!D2").Value 'auto-fill phone number from filtered results on contacts sheet
MyLine(14) = Environ$("UserName") 'Pull username from system
MyLine(15) = Now 'pull current time from system
MyLine(11) = Range("Form!B12").Value
If Range("Form!B5") = "Stores" Then 'in case of stores orders auto fill PO box and set PO text as black
MyLine(12) = "None"
MyLine(13) = "None"
Range("Database!N" & I).Font.ColorIndex = 0
End If
Range("Database!A" & I & ":Database!P" & I).Value = MyLine
ActiveWorkbook.SaveCopyAs ("C:\Redacted\" & Format(Now(), "DD-MM-YYYY hh mm ss") & ".xlsm") 'save backup with form still filled in, named for current date and time.
Sheet1.Range("Form!B3:B14").ClearContents
Sheet1.Range("Form!C3").ClearContents
Sheet1.Range("Form!C6:C7").ClearContents
Range("Database!A1").AutoFilter 'switch auto-filter for database back on
ActiveWorkbook.Save 'save to database to ensure latest version is available.
Beep 'Audio prompt saying macro is done.
End Sub
</code></pre>
<p>My structure includes a fair number of saves to update the server file, as the code runs fairly slowly. If it is interrupted at any point, due to this structure no information will be overwritten. This is all to account for multiple users clicking this button at the same time on different machines, interrupting each others saves.</p>
<p>Currently I get around this by "Claiming" the next available line at the start of the run, and restarting on that line the next time the button is clicked (when someone else's save action is complete) however this is very heavy on Save actions, and due to it being a server located file, this slows down the macro significantly. Is there a better structure I can use to account for multiple users clicking the button at the same time, preventing any information being overwritten at any cost?</p>
<p>PS I know using Activeworkbook and the like is discouraged, and I'm currently reviewing my code to amend this. I'm just looking for ideas about above issue.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:51:40.950",
"Id": "446432",
"Score": "0",
"body": "Is there more code that isn't shown here where the comment `'!!code adding the new info to the next available blank row runs here` is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:55:26.477",
"Id": "446433",
"Score": "0",
"body": "Yes @pacmaninbw, however this isn't very relevant to this structure. It's a glorified copy paste from the first sheet where we enter our data to the second sheet where we keep our records. This is the action that cannot be interrupted at any cost hence this structure around it. Sorry if this isn't very clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:03:27.013",
"Id": "446434",
"Score": "0",
"body": "To be able to provide the best review possible, we need all the code at least in the function. Questions that obviously don't have all the code will be put on hold with the reason being `Lack of Concrete Context`. To put a question on hold requires 5 reviewers to vote to close the question. You might want to take a look at the help pages at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:06:21.097",
"Id": "446435",
"Score": "2",
"body": "You might want to look at a database solution where all the data is stored in a database and each user has their own workbook with data that gets pulled from the database. MariaDB and MySQL are 2 free database systems. Don't use MS Access because it doesn't lock the database properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:10:24.047",
"Id": "446436",
"Score": "1",
"body": "@pacmaninbw I understand. I cut out the code as it is not where the problem is, the data save action takes a few seconds at most, however the saves take significantly longer to complete. I have now amended my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:18:00.687",
"Id": "446438",
"Score": "0",
"body": "I have looked into other database options but since I am in a very restricted work environment I have very little available to me. I will keep trying to get access to a proper database solution in the long run."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:34:16.247",
"Id": "229506",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "VBA code to account for multiple users too heavy on save actions"
}
|
229506
|
<h3>Selection Sort</h3>
<blockquote>
<p>The selection sort algorithm sorts a list by finding the minimum
element from the right unsorted part of the list and putting it at the
left sorted part of the list. The algorithm maintains two sub-lists in
a given input list.</p>
<p>1) The sub-list which is already sorted.<br>
2) Remaining sub-list which
is unsorted.</p>
<p>In every iteration of selection sort, the minimum element from the
unsorted sub-list is picked and moved to the sorted sub-list.</p>
</blockquote>
<p>I've been trying to implement the Selection Sort algorithm using Python magic functions such as <code>__iter__</code> and I'd appreciate it if you'd review the code for changes/improvements. </p>
<h3>Code</h3>
<pre><code>"""
This class returns an ascending sorted integer list
for an input integer list using Selection Sort method.
Sorting:
- In-Place (space complexity O(1))
- Efficiency (time complexity O(N^2))
- Unstable Sort (Order of equal elements might change)
"""
class SelectionSort(object):
"""
"""
def __init__(self, input_list:list)->list:
self.input_list = input_list
self.__iter__()
def __iter__(self)->list:
"""
Iterates through the list and swaps the min from the right side
to sorted elements from the left side of the list.
"""
# Is the length of the list
input_length = len(self.input_list)
# Iterates through the list to do the swapping
for element_index in range(input_length - 1):
min_index = element_index
# Iterates through the list to find the min index
for finder_index in range(element_index+1, input_length):
if self.input_list[min_index] > self.input_list[finder_index]:
min_index = finder_index
# Swaps the min value with the pointer value
if element_index is not min_index:
self.input_list[element_index], self.input_list[min_index] = self.input_list[min_index], self.input_list[element_index]
print(self.input_list)
return self.input_list
SelectionSort([10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1])
</code></pre>
<h3>Solution from Geeks by Geeks</h3>
<p>I'm not so sure about Sorting Stability, it says the following implementation is not stable. However, Selection Sort can be made stable:</p>
<pre><code>import sys
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_index = i
for j in range(i+1, len(A)):
if A[min_index] > A[j]:
min_index = j
A[i], A[min_index] = A[min_index], A[i]
for i in range(len(A)):
print("%d" %A[i])
</code></pre>
<h3>Reference</h3>
<ul>
<li><a href="https://www.geeksforgeeks.org/selection-sort/" rel="nofollow noreferrer">Selection Sort (Geeks for Geeks)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Selection_sort" rel="nofollow noreferrer">Selection Sort (Wiki)</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:04:08.630",
"Id": "446565",
"Score": "1",
"body": "Are you sure this is an unstable sorting implementation? I'm not convinced that it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:24:18.893",
"Id": "446570",
"Score": "1",
"body": "nevermind, I misread the code. It does indeed look unstable."
}
] |
[
{
"body": "<p>This is mostly pretty good. Only a couple of things:</p>\n\n<p>Delete this -</p>\n\n<pre><code> print(self.input_list)\n</code></pre>\n\n<p>You should leave printing to the caller.</p>\n\n<p>Also - why the class at all? This really boils down to a single function. You only have one member variable, and only one method.</p>\n\n<p>There's another issue - this class results in \"surprising mutation\". Iterating over it modifies one of its members. This is another argument for a simple function. If you keep the class, you could possibly</p>\n\n<ul>\n<li>Cache the sorted output, as a separate list from the input list, and/or</li>\n<li>store a copy of the input list instead of the input list itself.</li>\n</ul>\n\n<p>That last point speaks to another issue - you assume that you're being passed a list, which isn't strictly necessary; all you need is an iterable. If you create a list from the input, you place fewer demands on your caller.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:23:12.767",
"Id": "229513",
"ParentId": "229509",
"Score": "6"
}
},
{
"body": "<p>I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:</p>\n\n<pre><code>def __init__(self, input_list:list)->list:\n self.input_list = input_list\n self.__iter__()\n</code></pre>\n\n<p>You are constructing the object (and calling the constructor) simply to call <code>self.__iter__()</code>. There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it <em>may</em> be appropriate.</p>\n\n<p>I'll also point out, you're attempting to violate at least two \"contracts\" with your usage of <code>__init__</code> and <code>__iter__</code>:</p>\n\n<ul>\n<li><p><a href=\"https://docs.python.org/3/reference/datamodel.html#object.__init__\" rel=\"nofollow noreferrer\"><code>__init__</code> must return None</a>:</p>\n\n<blockquote>\n <p>no non-None value may be returned by <code>__init__()</code>; doing so will cause a TypeError to be raised at runtime.</p>\n</blockquote>\n\n<p>Now, you aren't <em>actually</em> returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.</p></li>\n<li><p><a href=\"https://docs.python.org/3/reference/datamodel.html#object.__iter__\" rel=\"nofollow noreferrer\"><code>__iter__</code> should return an iterator</a>:</p>\n\n<blockquote>\n <p>This method should return a new iterator object that can iterate over all the objects in the container</p>\n</blockquote>\n\n<p>The problem is, you're returning a list, and a list isn't an <strong>iterator</strong>, it's an <strong>iterable</strong> (it <em>has</em> an iterator). This isn't just a theoretical problem. Note how this can bite you:</p>\n\n<pre><code>class T:\n def __iter__(self):\n return [1, 2, 3]\n\nfor n in T():\n print(n)\n\n# TypeError: iter() returned non-iterator of type 'list'\n</code></pre></li>\n</ul>\n\n<p>Use of \"dunder\" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.</p>\n\n<hr>\n\n<p>And on the subject of type hints, you could make use of a <code>TypeVar</code> to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:</p>\n\n<pre><code>def selection_sort(input_list: list) -> list:\n</code></pre>\n\n<p>The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in <code>input_list</code> and that of the list that <code>selection_sort</code> returns. This can lead to subtle issues where it won't be able to help you with types:</p>\n\n<pre><code>lst: List[int] = [1, 2, 3]\nsorted_list = selection_sort(input_list)\nx = sorted_list[0] # It has no idea what type x is\n</code></pre>\n\n<p>You can fix this by introducing a <code>TypeVar</code> that tells it that the element type remains consistent. I'm also changing from using <code>list</code> to <code>List</code> since <code>list</code> doesn't seem to support generics yet:</p>\n\n<pre><code>from typing import List, TypeVar\n\nT = TypeVar(\"T\")\n\n# The sort returns the same element type T that it received\ndef selection_sort(input_list: List[T]) -> List[T]:\n . . .\n</code></pre>\n\n<p>Now, it is able to infer the type of <code>x</code>, and can give you better completions and type warnings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:19:52.580",
"Id": "229524",
"ParentId": "229509",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229524",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:20:04.950",
"Id": "229509",
"Score": "8",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"sorting"
],
"Title": "Selection Sort Algorithm (Python)"
}
|
229509
|
<p>I have made a class which wraps the JSForce Salesforce API Client: </p>
<pre class="lang-js prettyprint-override"><code>import jsforce = require('jsforce');
export class SalesforcePortalClient {
salesforceConsumerKey: string;
salesforceConsumerSecret: string;
salesforceUsername: string;
salesforcePassword: string;
constructor(salesforceConsumerKey: string, salesforceConsumerSecret: string, salesforceUsername: string, salesforcePassword: string) {
this.salesforceConsumerKey = salesforceConsumerKey,
this.salesforceConsumerSecret = salesforceConsumerSecret,
this.salesforceUsername = salesforceUsername,
this.salesforcePassword = salesforcePassword
}
private getConnection(): jsforce.Connection {
return new jsforce.Connection({
oauth2: {
clientId: this.salesforceConsumerKey,
clientSecret: this.salesforceConsumerSecret,
redirectUri: 'http://localhost:3000/callback',
loginUrl: 'https://test.salesforce.com'
}
})
}
private async login(): Promise<jsforce.Connection> {
let conn = this.getConnection()
await conn.login(this.salesforceUsername!, this.salesforcePassword!)
return conn
}
async getInstanceId(): Promise<string> {
return this.login().then(l => l.instanceUrl)
}
async postApexRest(projectTitle: string, organisationName: string): Promise<any> {
return await this.login().then(l => l.apex.post('/loadData/', this.buildPayload(organisationName, projectTitle)))
}
private buildPayload = (organisationName: string, projectName: string) => {
return {
"projectName": projectName,
"organisationName": organisationName,
}
}
}
</code></pre>
<p>I have some ideas about how this could be improved but not sure how to implement them, for example:</p>
<ul>
<li><p>Is there a way to perform <code>login()</code> either when the class is instantiated or when it is first used and make it available at class level, so the token can be re-used rather than re-created on every request?</p></li>
<li><p>It seems like there is a fair amount of boilerplate in the arguments and constructor, is there anyway to reduce this whilst maintaining the same behaviour?</p></li>
</ul>
<p>Also, I would welcome any suggestions on ways to improve this, as someone new to TypeScript.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:10:58.533",
"Id": "446858",
"Score": "0",
"body": "Why did you feel the need for a wrapper?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:59:50.240",
"Id": "229514",
"Score": "1",
"Tags": [
"object-oriented",
"typescript",
"wrapper",
"salesforce-apex"
],
"Title": "TypeScript Salesforce client library wrapper"
}
|
229514
|
Bucket sort is mainly useful when input is uniformly distributed over a range. Use this tag for implementations of the Bucket sort algorithm.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:01:57.230",
"Id": "229516",
"Score": "0",
"Tags": null,
"Title": null
}
|
229516
|
LaTeX is a document preparation system widely used in academia for the communication and publication of scientific documents in many fields. Use this tag for questions related to LaTeX.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:04:41.677",
"Id": "229518",
"Score": "0",
"Tags": null,
"Title": null
}
|
229518
|
Typesetting is the composition of text by means of arranging physical types or the digital equivalents. Use this tag for questions related to any typesetting system.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:06:32.287",
"Id": "229520",
"Score": "0",
"Tags": null,
"Title": null
}
|
229520
|
IndexedDB is a way to persistently store data inside a user's browser. Use this tag for questions related to the IndexedDB API.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:11:13.040",
"Id": "229523",
"Score": "0",
"Tags": null,
"Title": null
}
|
229523
|
<p>I've made a few things in Java, and now I'm learning C#.<br>
The code passes the tests with 100% final score. <br>I want to know what things can be improved in my code.</p>
<blockquote>
<p><strong><em>Task description</em></strong> </p>
</blockquote>
<hr>
<blockquote>
<p>A non-empty array A consisting of N integers is
given.</p>
<p>A permutation is a sequence containing each element from 1 to N once,
and only once.</p>
<p>For example, array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2 is a permutation, but array A such that:
A[0] = 4
A[1] = 1
A[2] = 3 is not a permutation, because value 2 is missing.
</code></pre>
<p>The goal is to check whether array A is a permutation.</p>
<p>Write a function:</p>
<p>class Solution { public int solution(int[] A); }</p>
<p>that, given an array A, returns 1 if array A is a permutation and 0 if
it is not.</p>
<p>For example, given array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2 the function should return 1.
</code></pre>
<p>Given array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3 the function should return 0.
</code></pre>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [1..1,000,000,000].</p>
</blockquote>
<pre><code>public static int solution(int[] A)
{
int[] orderedPermut = new int[A.Length];
int[] unrepeated = new int[A.Length];
int orderedPermutSum = 0, unrepeatedSum = 0;
for ( int i = 0; i < A.Length; i++ )
{
orderedPermutSum += i + 1;
orderedPermut[i] = i + 1;
if ( A[i] >= A.Length + 1 || unrepeated[ A[i] - 1 ] != 0 )
/*number is greater than A's length, or it's repeated,
/*therefore,A's not a permutation.*/
return 0;
else
{
unrepeated[A[i] - 1] = A[i];
unrepeatedSum += A[i];
}
}
if ( orderedPermutSum == unrepeatedSum )
{
return 1;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>I checked the solution to this problem in codesays (answered by Sheng).<br> One thing I can improve from his better solution is that he followed the same approach, but didn't check if the sum of a proper and ordered permutation was correct, so he didn't use an ordered array. <br>I used two counters, one that I knew was correct, and another one that could go wrong, but if I think about it, if no elements were repeated, nor out of range, then checking for the sum to be right wasn't necessary, because it must be a permutation if that was the case. Checking for negative numbers was something I could also do, and then decide it was not a permutation, no tests tried arrays with negative numbers, though</p>\n\n<pre><code>class Solution {\n public static int solution(int[] A) {\n int[] counter = new int [A.length];\n for(int i= 0; i< A.length; i++){\n if (A[i] < 1 || A[i] > A.length) {\n // Out of range\n return 0;\n }\n else if(counter[A[i]-1] == 1) {\n // met before\n return 0;\n }\n else {\n // first time meet\n counter[A[i]-1] = 1;\n }\n }\n return 1;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:59:32.913",
"Id": "229527",
"ParentId": "229525",
"Score": "2"
}
},
{
"body": "<p>One of the unfortunate things you'll notice about coding challenges is that the requirements often force you to write code that isn't ideal. I'm going to call these out, even though in this case they're outside of your control.</p>\n\n<p><strong>Silly requirement:</strong> The method is named <code>solution</code>. This name tells us nothing about the behavior of the function. Also (although less importantly), it goes against the C# method naming convention of <code>PascalCase</code>. A much better name would be something like <code>IsPermutation</code>.</p>\n\n<p><strong>Silly requirement:</strong> The parameter is named <code>A</code>. Single-letter variable names are almost never a good idea. Also (although less importantly), it goes against the C# parameter naming convention of <code>camelCase</code>. It's hard to be descriptive about the context here (since it's just a coding challenge and not a \"real life\" business problem), but even something like <code>values</code> would be better.</p>\n\n<p><strong>Silly requirement:</strong> The return type of the function is <code>int</code>. The given array is either a permutation of 1..N or it isn't. We don't have a range of possible return values; we have a true/false condition. A better return type would be <code>bool</code>.</p>\n\n<p><strong>Algorithm inefficiency:</strong> There's no need to initialize two new <code>int[]</code>. As you discovered, one new array is sufficient to track unique values.</p>\n\n<p><strong>Algorithm inefficiency:</strong> Again, you've already discovered this. If an array has the correct elements in some order, its sum will necessarily match that of the unordered array. Meanwhile the converse is not true; there are many arrays with the same sum which are not permutations. So you needn't bother tracking the sum at all.</p>\n\n<p><strong>Syntax:</strong> If you take only one piece of my advice, let it be this one: <em>for loops are not the answer</em>. If you are iterating over the indexes of an array, and the only thing you use the index for is to grab the <code>ith</code> element, <em>use a foreach</em>. The situation where you actually <em>need</em> to know the index, and therefore need a for loop, is very rare.</p>\n\n<p><strong>Semantics:</strong> Does an array of <code>int</code> take less space in memory than an array of <code>bool</code>? I don't know, and I don't care. If all I'm tracking is true/false values, I'm going to choose a <code>bool[]</code>. Because that choice tells the person reading the code <em>why</em> I created the variable.</p>\n\n<p><strong>Formatting:</strong> Another major difference between formatting conventions in C# and Java (besides the PascalCase/camelCase conventions I already mentioned) is C#'s convention of putting opening curly braces on the next line (known as <a href=\"https://en.wikipedia.org/wiki/Indentation_style#K&R_style\" rel=\"noreferrer\">K&R style</a>).</p>\n\n<hr>\n\n<p>With all of that advice applied, and some XML documentation comments (which enable Intellisense information when hovering or typing in Visual Studio), we'll end up with something like this:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Check whether the given array contains each integer 1..N exactly once.\n/// </summary>\n/// <returns>\n/// True if <paramref name=\"values\" /> is a permutation of 1..N,\n/// False otherwise.\n/// </returns>\npublic static bool IsPermutation(int[] values)\n{\n var seen = new bool[values.length];\n\n foreach (var value in values)\n {\n if (value < 1 || value > values.length)\n {\n // Out of range: not a permutation\n return false;\n }\n else if (seen[value - 1])\n {\n // Duplicated value: not a permutation\n return false;\n }\n else\n {\n // Value is OK. Mark as seen.\n seen[value - 1] = true;\n }\n }\n\n // All values in range, no duplicates: a valid permutation\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:50:09.043",
"Id": "446505",
"Score": "2",
"body": "I asked a general question about this kind of reviews where you challenge the challenge itself :) -> https://codereview.meta.stackexchange.com/questions/9345/reviewing-programming-challenge-requirements-and-givens"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:53:54.320",
"Id": "446507",
"Score": "1",
"body": "Good idea. My thinking was to bridge the gap between a good solution to the challenge, and good \"real life\" code. I'm interested in how valuable the community finds that type of feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:56:00.660",
"Id": "446510",
"Score": "0",
"body": "So am I. I've also commented on challenge requirements in some of my reviews, but never to this extend. I find it an interesting way of reviewing :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T09:11:57.813",
"Id": "446537",
"Score": "5",
"body": "`Single-letter variable names are almost never a good idea.` Just to extend, they are a good idea when dealing with maths. E.g. `Multiply(int a, int b)` is perfectly acceptable because \"number1\" etc isn't better. But the answer is correct that for dore general data purposes, single letter variables are usually bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:17:54.973",
"Id": "447123",
"Score": "2",
"body": "The Meta question brought me here. The only change I would suggest is to put the `Silly Requirement` points into a single section `Silly Requirements` after the observations about the OP's code, not before. Perhaps make the silly requirements a list of bullet points. I don't see a problem with challenging the challenge."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:33:44.547",
"Id": "229533",
"ParentId": "229525",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:35:51.667",
"Id": "229525",
"Score": "6",
"Tags": [
"c#",
"beginner",
"programming-challenge",
"array",
"combinatorics"
],
"Title": "Codility's Permutation Check in C#"
}
|
229525
|
<p>This is my first attempt at some basic OOP programming. A version of battleships played within the terminal. Any feedback would be great; especially in regards to readability and proper naming conventions. </p>
<p>I would really like to improve the strike function of the computer class to make it play more intelligently, any tips on that specifically? </p>
<p>ocean.py</p>
<pre><code>class Ocean:
"""Creates 2D array the represents an ocean grid
to veiw your ship positions
Class contains all functions needed for placing
ships on the ocean grid"""
def __init__(self, width=10, height=10):
self.ocean = [["~" for i in range(width)] for i in range(height)]
def __getitem__(self, point):
row, col = point
return self.ocean[row][col]
def __setitem__(self, point, value):
row, col = point
self.ocean[row][col] = value
def view_ocean(self):
for row in self.ocean:
print(" ".join(row))
# Two functions check a coordinate input is on the grid
def valid_col(self, row):
try:
self.ocean[row]
return True
except IndexError:
return False
def valid_row(self, col):
try:
self.ocean[0][col]
return True
except IndexError:
return False
# Two functions check for valid board space for ship placement
def can_use_col(self, row, col, size):
valid_coords = []
for i in range(size):
if self.valid_col(col) and self.valid_row(row):
if self.ocean[row][col] == "~":
valid_coords.append((row, col))
col = col + 1
else:
col = col + 1
else:
return False
if size == len(valid_coords):
return True
else:
return False
def can_use_row(self, row, col, size):
valid_coords = []
for i in range(size):
if self.valid_row(row) and self.valid_col(col):
if self.ocean[row][col] == "~":
valid_coords.append((row, col))
row = row + 1
else:
row = row + 1
else:
return False
if size == len(valid_coords):
return True
else:
return False
# Corresponding fucntions set ship counters on valid space
def set_ship_col(self, row, col, size):
for i in range(size):
self.ocean[row][col] = "S"
col = col + 1
def set_ship_row(self, row, col, size):
for i in range(size):
self.ocean[row][col] = "S"
row = row + 1
</code></pre>
<p>radar.py</p>
<pre><code>class Radar:
"""Creates a grid to track the state of an opponent's ocean grid"""
def __init__(self, width=10, height=10):
self.radar = [["." for i in range(width)] for i in range(height)]
def __getitem__(self, point):
row, col = point
return self.radar[row][col]
def __setitem__(self, point, value):
row, col = point
self.radar[row][col] = value
def view_radar(self):
for row in self.radar:
print(" ".join(row))
</code></pre>
<p>ship.py</p>
<pre><code>class Ship:
def __init__(self, ship_type, size):
self.ship_type = ship_type
self.size = size
self.coords = []
def plot_vertical(self, row, col):
for i in range(self.size):
self.coords.append((row, col))
row = row + 1
def plot_horizontal(self, row, col):
for i in range(self.size):
self.coords.append((row, col))
col = col + 1
def check_status(self):
if self.coords == []:
return True
else:
return False
</code></pre>
<p>player.py</p>
<pre><code>from ocean import Ocean
from radar import Radar
from ship import Ship
import os
class Player:
ships = {"Aircraft Carrier": 5, "Crusier": 4, "Destroyer": 3,
"Submarine": 2}
def __init__(self, name):
self.ocean = Ocean()
self.radar = Radar()
self.name = name
self.fleet = []
# Function uses player input to set up fleet positions on a player board.
# For each ship, a ship object containing relevant coordinates is appended to self.fleet
def set_fleet(self):
input("Pick a coordinate between 0 and 9 for the columns and rows on your board")
input("Boats are placed form right to left.")
for ship, size in self.ships.items():
flag = True
while flag:
self.view_console()
try:
print("Place your %s" % (ship))
row = int(input("Pick a row -----> "))
col = int(input("Pick a column -----> "))
orientation = str(input("Vertical or Horizontal? (choose v or h) -----> "))
if orientation in ["v", "V"]:
if self.ocean.can_use_row(row, col, size):
self.ocean.set_ship_row(row, col, size)
boat = Ship(ship, size)
boat.plot_vertical(row, col)
self.fleet.append(boat)
flag = False
else:
input("Overlapping ships, try again")
elif orientation in ["h", "H"]:
if self.ocean.can_use_col(row, col, size):
self.ocean.set_ship_col(row, col, size)
boat = Ship(ship, size)
boat.plot_horizontal(row, col)
self.fleet.append(boat)
flag = False
else:
input("Overlapping ships, try agin")
else:
continue
self.view_console()
input()
os.system('clear')
except ValueError:
print("Don't you remember your training?\nType a number..\n")
# Function displays player ocean/radar in readable format
def view_console(self):
self.radar.view_radar()
print("| |")
self.ocean.view_ocean()
# Function checks status of ship objects within player fleet
def register_hit(self, row, col):
for boat in self.fleet:
if (row, col) in boat.coords:
boat.coords.remove((row, col))
if boat.check_status():
self.fleet.remove(boat)
print("%s's %s has been sunk!" % (self.name, boat.ship_type))
# Player interface for initiating in-game strikes,
# updates the state of the boards of both players
def strike(self, target):
self.view_console()
try:
print("\n%s Pick your target..." % (self.name))
row = int(input("Pick a row -----> "))
col = int(input("Pick a column -----> "))
if self.ocean.valid_row(row) and self.ocean.valid_col(col):
if target.ocean.ocean[row][col] == "S":
print("DIRECT HIT!!!")
target.ocean.ocean[row][col] = "X"
target.register_hit(row, col)
self.radar.radar[row][col] = "X"
else:
if self.radar.radar[row][col] == "O":
print("Area already hit....Check your radar!")
self.strike(target)
else:
print("Negative...")
self.radar.radar[row][col] = "O"
else:
print("Coordinates out of range...")
self.strike(target)
except ValueError:
print("You need to provide a number....\n")
self.strike(target)
input()
os.system('clear')
</code></pre>
<p>computer.py</p>
<pre><code>from player import Player
from ship import Ship
import random
class Computer(Player):
def __init__(self):
super().__init__(self)
self.name = "Computer"
# Automated version of set_fleet function from Player
def set_compu_fleet(self):
positions = ["v", "h"]
for ship, size in self.ships.items():
flag = True
while flag:
row = random.randint(0, 9)
col = random.randint(0, 9)
orientation = random.choice(positions)
if orientation == "v":
if self.ocean.can_use_row(row, col, size):
self.ocean.set_ship_row(row, col, size)
boat = Ship(ship, size)
boat.plot_vertical(row, col)
self.fleet.append(boat)
flag = False
else:
row = row + 2
elif orientation == "h":
if self.ocean.can_use_col(row, col, size):
self.ocean.set_ship_col(row, col, size)
boat = Ship(ship, size)
boat.plot_horizontal(row, col)
self.fleet.append(boat)
flag = False
else:
col = col + 2
else:
continue
# Automated strike function
def compu_strike(self, target):
row = random.randint(0, 9)
col = random.randint(0, 9)
if self.radar.radar[row][col] == ".":
input("...Target acquired....%s, %s" % (row, col))
if target.ocean.ocean[row][col] == "S":
print("DIRECT HIT!")
target.ocean.ocean[row][col] = "X"
target.register_hit(row, col)
self.radar.radar[row][col] = "X"
else:
print("Missed....recalibrating")
self.radar.radar[row][col] = "O"
else:
self.compu_strike(target)
</code></pre>
<p>battlshipspvp.py</p>
<pre><code>from player import Player
import os
# Player versus player mode
class BattleshipsPVP:
"""creates a game of battlehsips"""
def __init__(self):
start = input("Begin? (y or n) -----> ")
if start in ["y", "Y"]:
self.playPVP()
else:
print("Aborted...")
def playPVP(self):
p1name = input("Player 1, state your name! -----> ")
p1 = Player(p1name)
p1.set_fleet()
p1.view_console()
self.clear_screen()
p2name = input("\n\nPlayer 2, state your name! -----> ")
p2 = Player(p2name)
p2.set_fleet()
p2.view_console()
self.clear_screen()
flag = True
while flag is True:
p1.strike(p2)
if self.fleet_sunk(p2) is True:
self.victory_message(p1, p2)
flag = False
else:
self.clear_screen()
p2.strike(p1)
if self.fleet_sunk(p1) is True:
self.victory_message(p2, p1)
flag = False
else:
self.clear_screen()
print("\nThanks for playing!")
# Function checks remaining ship counters on a player's board
def fleet_sunk(self, player):
ship_counters = 0
"""Traverses grid looking for 's' counters"""
for row in range(len(player.ocean.ocean)):
for col in range(len(player.ocean.ocean)):
if player.ocean.ocean[row][col] == "S":
ship_counters += 1
if ship_counters == 0:
return True
else:
return False
def clear_screen(self):
input("\nNext Turn?")
os.system('clear')
def victory_message(self, winner, loser):
print("\n\n\n*****************************************")
print("%s's fleet has been destroyed, %s wins!" % (loser.name, winner.name))
print("*****************************************")
</code></pre>
<p>battleshipscomp.py</p>
<pre><code>from battleshipspvp import BattleshipsPVP
from computer import Computer
from player import Player
class BattleshipsCOMP(BattleshipsPVP):
def __init__(self):
start = input("Begin? (y or n) -----> ")
if start in ["y", "Y"]:
self.playCOMP()
else:
print("Aborted...")
def playCOMP(self):
pname = input("Player 1, state your name! -----> ")
p = Player(pname)
p.set_fleet()
p.view_console()
self.clear_screen()
c = Computer()
print("Computer setting its fleet...")
c.set_compu_fleet()
self.clear_screen()
flag = True
while flag is True:
p.strike(c)
if self.fleet_sunk(c) is True:
self.victory_message(p, c)
flag = False
else:
self.clear_screen()
c.compu_strike(p)
if self.fleet_sunk(p) is True:
self.victory_message(c, p)
flag = False
else:
self.clear_screen()
print("\nThanks for playing!")
</code></pre>
<p>playbattleships.py</p>
<pre><code>from battleshipspvp import BattleshipsPVP
from battleshipscomputer import BattleshipsCOMP
# Script initiates game of battleships
def playbattleships():
print("\n\n***********************")
print("Welcome to Battleships!")
print("***********************\n")
print("\n 1) Player vs Player")
print("\n 2) Player vs Computer")
flag = True
while flag:
try:
mode = int(input("\n\nPick a number to select a game mode ----> "))
if mode == 1:
flag = False
BattleshipsPVP()
elif mode == 2:
flag = False
BattleshipsCOMP()
else:
continue
except ValueError:
print("You can only pick either option 1 or 2")
playbattleships()
</code></pre>
<p>A view of the game board in play. The radar is the upper grid, the ocean is the lower grid. </p>
<pre><code>. . . . . . . . . .
X . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
| |
S ~ ~ ~ ~ ~ ~ ~ ~ ~
S ~ ~ ~ ~ ~ ~ ~ ~ ~
S ~ ~ ~ ~ ~ ~ ~ ~ ~
S ~ ~ ~ ~ ~ ~ ~ ~ ~
S ~ ~ ~ ~ S S S S ~
~ ~ ~ ~ ~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ S S X ~ ~
~ ~ S ~ ~ ~ ~ ~ ~ ~
~ ~ S ~ ~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~ ~ ~ ~ ~
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T05:51:04.043",
"Id": "446731",
"Score": "1",
"body": "If you want to improve your `strike` function, I'd recommend [this nice article](http://www.datagenetics.com/blog/december32011/)"
}
] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>PEP484 type hints will help document and test your code. For example,</p>\n\n<pre><code>def can_use_col(self, row, col, size):\n</code></pre>\n\n<p>can be (I guess)</p>\n\n<pre><code>def can_use_col(self, row: int, col: int, size: int) -> bool:\n</code></pre>\n\n<h2>In-place addition</h2>\n\n<pre><code>col = col + 1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>col += 1\n</code></pre>\n\n<h2>Logic-by-exception</h2>\n\n<p>This:</p>\n\n<pre><code> try:\n self.ocean[row]\n return True\n except IndexError:\n return False\n</code></pre>\n\n<p>can simply be</p>\n\n<pre><code>return row in self.ocean\n</code></pre>\n\n<h2>can_use_col</h2>\n\n<p>This method shouldn't need to form a list. Let's see if we can improve it.</p>\n\n<p>First: replace <code>i</code> with <code>_</code> since you don't use it. Also, instead of <code>valid_coords</code> as a list, you can maintain it as a count starting at 0. Increment it instead of appending to a list.</p>\n\n<p>Also, don't repeat yourself - only do <code>col += 1</code> once, in the scope above where you have it now.</p>\n\n<p>Use a boolean directly by writing <code>return size == len(valid_coords)</code> instead of using an <code>if</code> statement. The same goes for this code:</p>\n\n<pre><code> if self.coords == []:\n return True\n else:\n return False\n</code></pre>\n\n<h2>Iteration</h2>\n\n<pre><code> for i in range(size):\n self.ocean[row][col] = \"S\"\n row = row + 1\n</code></pre>\n\n<p>Again, you don't use <code>i</code>, but you're also maintaining an index in <code>row</code>. Instead:</p>\n\n<pre><code> for i in range(size):\n self.ocean[row + i][col] = \"S\"\n</code></pre>\n\n<p>This also solves the issue that you're changing an argument to your function, which you generally shouldn't.</p>\n\n<h2>Docstrings</h2>\n\n<p>This comment:</p>\n\n<pre><code># Function uses player input to set up fleet positions on a player board.\n# For each ship, a ship object containing relevant coordinates is appended to self.fleet\n</code></pre>\n\n<p>belongs on the first line inside the function, in triple quotes.</p>\n\n<h2>Typo</h2>\n\n<pre><code>\"Boats are placed form right to left.\"\n</code></pre>\n\n<p>form = from.</p>\n\n<h2>Input prompts</h2>\n\n<pre><code> input(\"Boats are placed form right to left.\")\n</code></pre>\n\n<p>I'm not sure what this is asking the user to input, and they won't be either. Did you mean to write <code>print</code> here?</p>\n\n<h2>Character comparison</h2>\n\n<pre><code>if orientation in [\"v\", \"V\"]:\n</code></pre>\n\n<p>If you actually needed to compare against multiple things, you should use a set instead of a list:</p>\n\n<pre><code>if orientation in {\"v\", \"V\"}:\n</code></pre>\n\n<p>However, your case is easier than that:</p>\n\n<pre><code>if orientation.lower() == 'v':\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:55:57.937",
"Id": "446661",
"Score": "0",
"body": "Thanks man I really appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T07:53:54.993",
"Id": "446741",
"Score": "0",
"body": "`return row in self.ocean` will not work if the `ocean` is a list of lists. This can work if the ocean is a dict"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T17:14:03.897",
"Id": "229529",
"ParentId": "229526",
"Score": "2"
}
},
{
"body": "<h2>Use your own Interfaces</h2>\n\n<p>You've created both your <code>Ocean</code> class and <code>Radar</code> class to accept a <code>point</code> key in the <code>__getitem__</code> and <code>__setitem__</code> methods. Ie)</p>\n\n<pre><code>def __getitem__(self, point):\n row, col = point\n return self.ocean[row][col]\n\ndef __setitem__(self, point, value):\n row, col = point\n self.ocean[row][col] = value\n</code></pre>\n\n<p>But in your <code>Player</code> class, you avoid using those interfaces, and instead directly reach into the <code>Ocean</code> and <code>Radar</code> classes and manipulate the internals directly:</p>\n\n<pre><code> if self.ocean.valid_row(row) and self.ocean.valid_col(col):\n if target.ocean.ocean[row][col] == \"S\":\n print(\"DIRECT HIT!!!\")\n target.ocean.ocean[row][col] = \"X\"\n target.register_hit(row, col)\n self.radar.radar[row][col] = \"X\"\n</code></pre>\n\n<p>You should be using the interfaces you created:</p>\n\n<pre><code> if self.ocean.valid_row(row) and self.ocean.valid_col(col):\n if target.ocean[row, col] == \"S\":\n print(\"DIRECT HIT!!!\")\n target.ocean[row, col] = \"X\"\n target.register_hit(row, col)\n self.radar[row, col] = \"X\"\n</code></pre>\n\n<h2>Mark internals private</h2>\n\n<p>There is no \"private\" in Python, but by convention, if a member starts with a leading underscore, it should only be accessed by self. So using <code>self._ocean</code> is ok, but using <code>self._ocean._ocean</code> would not be, as the second <code>._ocean</code> is reaching into another objects privates.</p>\n\n<p>Ie:</p>\n\n<pre><code>class Ocean:\n def __init__(self, width=10, height=10):\n self._ocean = [[\"~\" for i in range(width)] for i in range(height)]\n</code></pre>\n\n<p>So when you create <code>Player</code>, and you type <code>self.ocean._ocean</code>, you can think to yourself, \"<em>wait ... I shouldn't be using that <code>._ocean</code> member of that <code>self.ocean</code> object; I should be calling a public method on <code>self.ocean</code> instead.</em>\"</p>\n\n<h2>Don't use Recursion for an Input Loop</h2>\n\n<p>Title says it all:</p>\n\n<pre><code>def strike(self, target):\n try:\n ...\n print(\"Area already hit....Check your radar!\")\n self.strike(target)\n ...\n except ValueError:\n print(\"You need to provide a number....\\n\")\n self.strike(target)\n ...\n</code></pre>\n\n<p>If you repeatedly enter an already hit location, your stack will eventually overflow. If you repeatedly enter an invalid row/col value, and get a <code>ValueError</code> exception, you'll get stack overflow while handling a <code>ValueError</code>, while handling a <code>ValueError</code>, while handling a <code>ValueError</code>, while handling a <code>ValueError</code>, while handling a <code>ValueError</code>, while ... a few thousand levels deep!</p>\n\n<p>You did things better in <code>set_fleet()</code> with a <code>while flag:</code> loop.</p>\n\n<h2>os.system('clear')</h2>\n\n<p>Don't use this. Don't even use:</p>\n\n<pre><code>os.system('cls' if sys.platform == 'nt' else 'clear')\n</code></pre>\n\n<p>That is forking a new process, loading a shell processor, interpreting a command, which may launch yet-another-process, which clears the screen. A little heavy weight. And it is risky, if an executable, like <code>cls.bat</code> or <code>clear</code> is on the path; you could end up executing arbitrary instructions.</p>\n\n<p>Use:</p>\n\n<pre><code>import colorama\n\ndef clear_screen():\n print(colorama.ansi.clear_screen())\n\ncolorama.init()\n\nclear_screen()\n</code></pre>\n\n<p>Look at colorama for other interesting things you can do. Like making your ocean blue, your ships green, and your hits red.</p>\n\n<h2>Fixed Formatting</h2>\n\n<pre><code> print(\"| |\")\n</code></pre>\n\n<p>What happens if your ocean is 8x8? Or 12x12? Will your vertical bars still properly line up?</p>\n\n<pre><code> print(\"|\" + \" \" * (2 * cols - 3) + \"|\")\n</code></pre>\n\n<p>would work better ... assuming <code>cols</code> is defined or replaced with something suitable.</p>\n\n<p>Ditto with:</p>\n\n<pre><code>input(\"Pick a coordinate between 0 and 9 for the columns and rows on your board\")\n</code></pre>\n\n<p>(Which as mentioned by Reinderien, should be a <code>print</code> statement.) What if you changed your board size?</p>\n\n<h2>Player-vs-Player or Player-vs-Computer</h2>\n\n<p>You've duplicated too much code. Player -vs- Player, Player -vs- Computer, and Computer -vs- Computer can all be handled by 1 \"game\" function.</p>\n\n<pre><code>def play_game(side1, side2):\n\n side1.set_fleet()\n side2.set_fleet()\n\n while True:\n side1.strike(side2)\n if self.fleet_sunk(side2):\n self.victory_message(side1, side2)\n break\n else:\n side1, side2 = side2, side1\n</code></pre>\n\n<p>You games would be launched like:</p>\n\n<pre><code>p1 = Player(p1name)\np2 = Player(p2name)\nplay_game(p1, p2)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>p1 = Player(p1name)\np2 = Computer()\nplay_game(p1, p2)\n</code></pre>\n\n<p>For this to work, <code>Computer</code> would need a <code>set_fleet()</code> method, instead of a <code>set_compu_fleet()</code> method, as well as a <code>strike()</code> method instead of a <code>compu_strike()</code> method.</p>\n\n<h2>f-strings</h2>\n\n<p>If using Python 3.6+, instead of:</p>\n\n<pre><code> print(\"%s's %s has been sunk!\" % (self.name, boat.ship_type))\n</code></pre>\n\n<p>use:</p>\n\n<pre><code> print(f\"{self.name}'s {boat.ship_type} has been sunk!\")\n</code></pre>\n\n<h2>Antipatterns</h2>\n\n<p>Avoid <code>is True</code>. For example, <code>while flag is True:</code>. Use <code>while flag:</code></p>\n\n<p>Avoid <code>if condition: return True else: return False</code>. Use, <code>return condition</code>. For example:</p>\n\n<pre><code> if ship_counters == 0:\n return True\n else:\n return False\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code> return ship_counters == 0\n</code></pre>\n\n<p>Avoid <code>for idx in range(len(item)): blah(item[idx])</code>. Use <code>for val in item: blah(val)</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>ship_counters = 0\nfor row in range(len(player.ocean.ocean)):\n for col in range(len(player.ocean.ocean)):\n if player.ocean.ocean[row][col] == \"S\":\n ship_counters += 1\n</code></pre>\n\n<p>Would be better written as:</p>\n\n<pre><code>ship_counters = 0\nfor ocean_row in player.ocean.ocean:\n for cell in ocean_row:\n if cell == \"S\":\n ship_counters += 1\nreturn ship_counters == 0\n</code></pre>\n\n<p>Or better:</p>\n\n<pre><code>ship_counters = sum(1 for row in player.ocean.ocean for cell in row if cell == \"S\")\nreturn ship_counters == 0\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>return all(cell != 'S' for row in player.ocean.ocean for cell in row)\n</code></pre>\n\n<h2>Docstrings</h2>\n\n<p>I disagree with @Reinderien's point:</p>\n\n<blockquote>\n <p>This comment:<br>\n <code># Function uses player input to set up fleet positions on a player board.</code>.<br>\n <code># For each ship, a ship object containing relevant coordinates is appended to self.fleet</code>.<br>\n belongs on the first line inside the function, in triple quotes.</p>\n</blockquote>\n\n<p>The above is a comment, not a docstring.</p>\n\n<ul>\n<li>A <code># comment</code> is used to document code for the <strong>reader</strong> of the code.</li>\n<li><p>A <code>\"\"\"docstring\"\"\"</code> is used to provide usage documentation for a <strong>caller</strong> who may not have access to the source code.</p>\n\n<p>class Player:</p>\n\n<pre><code># Function uses player input to set up fleet positions on a player board.\n# For each ship, a ship object containing relevant coordinates is appended to self.fleet\n\ndef set_fleet(self):\n \"\"\"\n Ask the user to assign locations to their fleet's ships.\n\n Parameters: None\n Returns: Nothing\n \"\"\"\n</code></pre></li>\n</ul>\n\n<p>Now, type <code>help(Player.set_fleet)</code>. You will see the <code>doc-string</code> help, which is designed to help the caller. From this description, the caller would know that they don't need to write <code>fleet = player.set_fleet()</code>, since nothing is returned.</p>\n\n<p>In contrast, someone reading the code (maybe to debug it, modify it, enhance it) will want to know what the code does. Appending a ship object to <code>self.fleet</code> is useful internal details the caller may not need to know.</p>\n\n<p>See also <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">sphinx-doc.org</a> for an automated docstring processing utility which can generate HTML doc pages, pdf help documents, etc., all by reading the docstrings directly from the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T03:32:09.753",
"Id": "229607",
"ParentId": "229526",
"Score": "4"
}
},
{
"body": "<h1>files</h1>\n\n<p>Python is not Java. Multiple classes can be in the same module (file)</p>\n\n<h1>grid</h1>\n\n<p>There is a lot of repetition between <code>Ocean</code> and <code>Radar</code>. You can use a lot of overlapping code</p>\n\n<h1>enum</h1>\n\n<p>instead of <code>\".\"</code> or <code>\"~\"</code> to denote what is in the grid, you could use Enums, and let the board representation method (<code>view_radar</code> for example) take care of how to represent this.</p>\n\n<h1>collection types</h1>\n\n<p>You only seem to use <code>list</code>s. Even when you only use the collection soo see whether something is in it, and order is not important. <code>set</code>s or <code>dict</code>s can be more suited on some moments. Get to know when to use which type of collection</p>\n\n<h1>orientation</h1>\n\n<p>You have a lot of methods that are the same, but one is for horizonatal, the other for vertical. This can be tackled by adding a parameter orientation (Which should be an Enum) to the method.</p>\n\n<pre><code>def plot_vertical(self, row, col):\n for i in range(self.size):\n self.coords.append((row, col))\n row = row + 1\n\n\ndef plot_horizontal(self, row, col):\n for i in range(self.size):\n self.coords.append((row, col))\n col = col + 1\n</code></pre>\n\n<p>can then be replaced by:</p>\n\n<pre><code>import enum\n\nclass Orientation(enum.Enum):\n Horizontal = (1, 0)\n Vertical = (0, 1)\n\n\ndef plot(self, row, col, orientation):\n d_col, d_row = orientation.value\n self.coords.extend(\n (row + i * d_row, col + i * d_col) for i in range(self.size)\n )\n</code></pre>\n\n<p>Even better would be to incorporate this in the ship's <code>__init__</code>, so the 2 steps in the placing of the fleet:</p>\n\n<pre><code>boat = Ship(ship, size)\nboat.plot_vertical(row, col)\n</code></pre>\n\n<p>can become :</p>\n\n<pre><code>class Ship:\n\n def __init__(self, ship_type, size, position, orientation):\n self.ship_type = ship_type\n self.size = size\n row, col = position\n d_col, d_row = orientation.value\n self.coords = [(row + i * d_row, col + i * d_col) for i in range(self.size)]\n</code></pre>\n\n<p>and be called:</p>\n\n<pre><code>boat = Ship(ship, size, (row, col), orientation)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:59:27.607",
"Id": "229626",
"ParentId": "229526",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:48:06.337",
"Id": "229526",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"game",
"battleship"
],
"Title": "Battleships OOP python"
}
|
229526
|
<p>I wrote a parser to extract data from a log file. The file format is a bit irregular, and so is also the parser code, as it turned out. It is a clutter of different loop types, different ways to iterate, and different ways of treating strings:</p>
<pre class="lang-py prettyprint-override"><code>import re
import pandas as pd
import os
import sys
logfilename = sys.argv[1]
csvfilename = os.path.splitext(logfilename)[0] + '.csv'
step = 0
data = []
logfile = open(logfilename,'r')
def match_step(line):
return re.match(r'\.step (.*)', line)
# find first .step definition
for line in logfile:
match = match_step(line)
if match:
break
# iterate through all steps with parameters
while match:
step += 1
row = { 'step': int(step) }
parameters = match.group(1).split()
for p in parameters:
[key, value] = p.split('=')
row[key] = float(value)
data.append(row)
match = match_step(next(logfile))
# iterate through measurement definitions
for line in logfile:
match = re.match(r'Measurement: (.*)', line)
if match:
name = match.group(1)
next(logfile) # skip row with column details
# iterate through measurement results for each step
while True:
measurement = next(logfile).split()
if not measurement:
break
row = { 'step': int(measurement[0]), name: float(measurement[1]) }
data.append(row)
logfile.close()
frame = pd.DataFrame(data).set_index('step').groupby('step').first()
frame.to_csv(csvfilename)
</code></pre>
<p>What could I do to improve code readability and consistency, especially in the parsing portion of the code?</p>
<p>I do not really care about performance since the process to generate the original log file already takes some minutes.</p>
<p>This is an example log file:</p>
<pre><code>Circuit: * D:\LTSpice\loss.asc
m1:1:v_sm: Missing value, assumed 0V @ DC
Per .tran options, skipping operating point for transient analysis.
.step iload=10 vdc=36 rg=1
.step iload=20 vdc=36 rg=1
.step iload=30 vdc=36 rg=1
.step iload=40 vdc=36 rg=1
.step iload=50 vdc=36 rg=1
.step iload=60 vdc=36 rg=1
.step iload=70 vdc=36 rg=1
.step iload=80 vdc=36 rg=1
.step iload=90 vdc=36 rg=1
.step iload=100 vdc=36 rg=1
.step iload=110 vdc=36 rg=1
.step iload=120 vdc=36 rg=1
.step iload=130 vdc=36 rg=1
.step iload=140 vdc=36 rg=1
.step iload=150 vdc=36 rg=1
.step iload=160 vdc=36 rg=1
.step iload=170 vdc=36 rg=1
.step iload=180 vdc=36 rg=1
.step iload=190 vdc=36 rg=1
.step iload=200 vdc=36 rg=1
.step iload=10 vdc=40 rg=1
.step iload=20 vdc=40 rg=1
.step iload=30 vdc=40 rg=1
.step iload=40 vdc=40 rg=1
.step iload=50 vdc=40 rg=1
.step iload=60 vdc=40 rg=1
.step iload=70 vdc=40 rg=1
.step iload=80 vdc=40 rg=1
.step iload=90 vdc=40 rg=1
.step iload=100 vdc=40 rg=1
.step iload=110 vdc=40 rg=1
.step iload=120 vdc=40 rg=1
.step iload=130 vdc=40 rg=1
.step iload=140 vdc=40 rg=1
.step iload=150 vdc=40 rg=1
.step iload=160 vdc=40 rg=1
.step iload=170 vdc=40 rg=1
.step iload=180 vdc=40 rg=1
.step iload=190 vdc=40 rg=1
.step iload=200 vdc=40 rg=1
.step iload=10 vdc=44 rg=1
.step iload=20 vdc=44 rg=1
.step iload=30 vdc=44 rg=1
.step iload=40 vdc=44 rg=1
.step iload=50 vdc=44 rg=1
.step iload=60 vdc=44 rg=1
.step iload=70 vdc=44 rg=1
.step iload=80 vdc=44 rg=1
.step iload=90 vdc=44 rg=1
.step iload=100 vdc=44 rg=1
.step iload=110 vdc=44 rg=1
.step iload=120 vdc=44 rg=1
.step iload=130 vdc=44 rg=1
.step iload=140 vdc=44 rg=1
.step iload=150 vdc=44 rg=1
.step iload=160 vdc=44 rg=1
.step iload=170 vdc=44 rg=1
.step iload=180 vdc=44 rg=1
.step iload=190 vdc=44 rg=1
.step iload=200 vdc=44 rg=1
.step iload=10 vdc=48 rg=1
.step iload=20 vdc=48 rg=1
.step iload=30 vdc=48 rg=1
.step iload=40 vdc=48 rg=1
.step iload=50 vdc=48 rg=1
.step iload=60 vdc=48 rg=1
.step iload=70 vdc=48 rg=1
.step iload=80 vdc=48 rg=1
.step iload=90 vdc=48 rg=1
.step iload=100 vdc=48 rg=1
.step iload=110 vdc=48 rg=1
.step iload=120 vdc=48 rg=1
.step iload=130 vdc=48 rg=1
.step iload=140 vdc=48 rg=1
.step iload=150 vdc=48 rg=1
.step iload=160 vdc=48 rg=1
.step iload=170 vdc=48 rg=1
.step iload=180 vdc=48 rg=1
.step iload=190 vdc=48 rg=1
.step iload=200 vdc=48 rg=1
.step iload=10 vdc=52 rg=1
.step iload=20 vdc=52 rg=1
.step iload=30 vdc=52 rg=1
.step iload=40 vdc=52 rg=1
.step iload=50 vdc=52 rg=1
.step iload=60 vdc=52 rg=1
.step iload=70 vdc=52 rg=1
.step iload=80 vdc=52 rg=1
.step iload=90 vdc=52 rg=1
.step iload=100 vdc=52 rg=1
.step iload=110 vdc=52 rg=1
.step iload=120 vdc=52 rg=1
.step iload=130 vdc=52 rg=1
.step iload=140 vdc=52 rg=1
.step iload=150 vdc=52 rg=1
.step iload=160 vdc=52 rg=1
.step iload=170 vdc=52 rg=1
.step iload=180 vdc=52 rg=1
.step iload=190 vdc=52 rg=1
.step iload=200 vdc=52 rg=1
.step iload=10 vdc=56 rg=1
.step iload=20 vdc=56 rg=1
.step iload=30 vdc=56 rg=1
.step iload=40 vdc=56 rg=1
.step iload=50 vdc=56 rg=1
.step iload=60 vdc=56 rg=1
.step iload=70 vdc=56 rg=1
.step iload=80 vdc=56 rg=1
.step iload=90 vdc=56 rg=1
.step iload=100 vdc=56 rg=1
.step iload=110 vdc=56 rg=1
.step iload=120 vdc=56 rg=1
.step iload=130 vdc=56 rg=1
.step iload=140 vdc=56 rg=1
.step iload=150 vdc=56 rg=1
.step iload=160 vdc=56 rg=1
.step iload=170 vdc=56 rg=1
.step iload=180 vdc=56 rg=1
.step iload=190 vdc=56 rg=1
.step iload=200 vdc=56 rg=1
.step iload=10 vdc=36 rg=2
.step iload=20 vdc=36 rg=2
.step iload=30 vdc=36 rg=2
.step iload=40 vdc=36 rg=2
.step iload=50 vdc=36 rg=2
.step iload=60 vdc=36 rg=2
.step iload=70 vdc=36 rg=2
.step iload=80 vdc=36 rg=2
.step iload=90 vdc=36 rg=2
.step iload=100 vdc=36 rg=2
.step iload=110 vdc=36 rg=2
.step iload=120 vdc=36 rg=2
.step iload=130 vdc=36 rg=2
.step iload=140 vdc=36 rg=2
.step iload=150 vdc=36 rg=2
.step iload=160 vdc=36 rg=2
.step iload=170 vdc=36 rg=2
.step iload=180 vdc=36 rg=2
.step iload=190 vdc=36 rg=2
.step iload=200 vdc=36 rg=2
.step iload=10 vdc=40 rg=2
.step iload=20 vdc=40 rg=2
.step iload=30 vdc=40 rg=2
.step iload=40 vdc=40 rg=2
.step iload=50 vdc=40 rg=2
.step iload=60 vdc=40 rg=2
.step iload=70 vdc=40 rg=2
.step iload=80 vdc=40 rg=2
.step iload=90 vdc=40 rg=2
.step iload=100 vdc=40 rg=2
.step iload=110 vdc=40 rg=2
.step iload=120 vdc=40 rg=2
.step iload=130 vdc=40 rg=2
.step iload=140 vdc=40 rg=2
.step iload=150 vdc=40 rg=2
.step iload=160 vdc=40 rg=2
.step iload=170 vdc=40 rg=2
.step iload=180 vdc=40 rg=2
.step iload=190 vdc=40 rg=2
.step iload=200 vdc=40 rg=2
.step iload=10 vdc=44 rg=2
.step iload=20 vdc=44 rg=2
.step iload=30 vdc=44 rg=2
.step iload=40 vdc=44 rg=2
.step iload=50 vdc=44 rg=2
.step iload=60 vdc=44 rg=2
.step iload=70 vdc=44 rg=2
.step iload=80 vdc=44 rg=2
.step iload=90 vdc=44 rg=2
.step iload=100 vdc=44 rg=2
.step iload=110 vdc=44 rg=2
.step iload=120 vdc=44 rg=2
.step iload=130 vdc=44 rg=2
.step iload=140 vdc=44 rg=2
.step iload=150 vdc=44 rg=2
.step iload=160 vdc=44 rg=2
.step iload=170 vdc=44 rg=2
.step iload=180 vdc=44 rg=2
.step iload=190 vdc=44 rg=2
.step iload=200 vdc=44 rg=2
.step iload=10 vdc=48 rg=2
.step iload=20 vdc=48 rg=2
.step iload=30 vdc=48 rg=2
.step iload=40 vdc=48 rg=2
.step iload=50 vdc=48 rg=2
.step iload=60 vdc=48 rg=2
.step iload=70 vdc=48 rg=2
.step iload=80 vdc=48 rg=2
.step iload=90 vdc=48 rg=2
.step iload=100 vdc=48 rg=2
.step iload=110 vdc=48 rg=2
.step iload=120 vdc=48 rg=2
.step iload=130 vdc=48 rg=2
.step iload=140 vdc=48 rg=2
.step iload=150 vdc=48 rg=2
.step iload=160 vdc=48 rg=2
.step iload=170 vdc=48 rg=2
.step iload=180 vdc=48 rg=2
.step iload=190 vdc=48 rg=2
.step iload=200 vdc=48 rg=2
.step iload=10 vdc=52 rg=2
.step iload=20 vdc=52 rg=2
.step iload=30 vdc=52 rg=2
.step iload=40 vdc=52 rg=2
.step iload=50 vdc=52 rg=2
.step iload=60 vdc=52 rg=2
.step iload=70 vdc=52 rg=2
.step iload=80 vdc=52 rg=2
.step iload=90 vdc=52 rg=2
.step iload=100 vdc=52 rg=2
.step iload=110 vdc=52 rg=2
.step iload=120 vdc=52 rg=2
.step iload=130 vdc=52 rg=2
.step iload=140 vdc=52 rg=2
.step iload=150 vdc=52 rg=2
.step iload=160 vdc=52 rg=2
.step iload=170 vdc=52 rg=2
.step iload=180 vdc=52 rg=2
.step iload=190 vdc=52 rg=2
.step iload=200 vdc=52 rg=2
.step iload=10 vdc=56 rg=2
.step iload=20 vdc=56 rg=2
.step iload=30 vdc=56 rg=2
.step iload=40 vdc=56 rg=2
.step iload=50 vdc=56 rg=2
.step iload=60 vdc=56 rg=2
.step iload=70 vdc=56 rg=2
.step iload=80 vdc=56 rg=2
.step iload=90 vdc=56 rg=2
.step iload=100 vdc=56 rg=2
.step iload=110 vdc=56 rg=2
.step iload=120 vdc=56 rg=2
.step iload=130 vdc=56 rg=2
.step iload=140 vdc=56 rg=2
.step iload=150 vdc=56 rg=2
.step iload=160 vdc=56 rg=2
.step iload=170 vdc=56 rg=2
.step iload=180 vdc=56 rg=2
.step iload=190 vdc=56 rg=2
.step iload=200 vdc=56 rg=2
Measurement: eon
step INTEG(v(drain)*ix(m1:d)) FROM TO
1 1.82588e-006 1e-005 1.02e-005
2 4.17134e-006 1e-005 1.02e-005
3 7.00321e-006 1e-005 1.02e-005
4 1.03301e-005 1e-005 1.02e-005
5 1.41369e-005 1e-005 1.02e-005
6 1.84238e-005 1e-005 1.02e-005
7 2.32117e-005 1e-005 1.02e-005
8 2.84883e-005 1e-005 1.02e-005
9 3.42491e-005 1e-005 1.02e-005
10 4.04575e-005 1e-005 1.02e-005
11 4.71822e-005 1e-005 1.02e-005
12 5.43457e-005 1e-005 1.02e-005
13 6.20163e-005 1e-005 1.02e-005
14 7.01661e-005 1e-005 1.02e-005
15 7.87419e-005 1e-005 1.02e-005
16 8.7822e-005 1e-005 1.02e-005
17 9.73496e-005 1e-005 1.02e-005
18 0.000107334 1e-005 1.02e-005
19 0.00011775 1e-005 1.02e-005
20 0.000128672 1e-005 1.02e-005
21 2.01474e-006 1e-005 1.02e-005
22 4.58268e-006 1e-005 1.02e-005
23 7.67373e-006 1e-005 1.02e-005
24 1.13006e-005 1e-005 1.02e-005
25 1.54471e-005 1e-005 1.02e-005
26 2.01132e-005 1e-005 1.02e-005
27 2.53309e-005 1e-005 1.02e-005
28 3.10536e-005 1e-005 1.02e-005
29 3.73023e-005 1e-005 1.02e-005
30 4.41231e-005 1e-005 1.02e-005
31 5.14188e-005 1e-005 1.02e-005
32 5.92874e-005 1e-005 1.02e-005
33 6.75954e-005 1e-005 1.02e-005
34 7.64433e-005 1e-005 1.02e-005
35 8.58157e-005 1e-005 1.02e-005
36 9.57088e-005 1e-005 1.02e-005
37 0.000106059 1e-005 1.02e-005
38 0.000116983 1e-005 1.02e-005
39 0.000128391 1e-005 1.02e-005
40 0.000140257 1e-005 1.02e-005
41 2.19203e-006 1e-005 1.02e-005
42 4.97675e-006 1e-005 1.02e-005
43 8.3144e-006 1e-005 1.02e-005
44 1.22347e-005 1e-005 1.02e-005
45 1.66951e-005 1e-005 1.02e-005
46 2.17464e-005 1e-005 1.02e-005
47 2.73532e-005 1e-005 1.02e-005
48 3.35368e-005 1e-005 1.02e-005
49 4.02896e-005 1e-005 1.02e-005
50 4.75927e-005 1e-005 1.02e-005
51 5.55096e-005 1e-005 1.02e-005
52 6.39629e-005 1e-005 1.02e-005
53 7.29618e-005 1e-005 1.02e-005
54 8.25448e-005 1e-005 1.02e-005
55 9.26558e-005 1e-005 1.02e-005
56 0.000103305 1e-005 1.02e-005
57 0.000114593 1e-005 1.02e-005
58 0.000126368 1e-005 1.02e-005
59 0.000138698 1e-005 1.02e-005
60 0.000151569 1e-005 1.02e-005
61 2.36219e-006 1e-005 1.02e-005
62 5.35277e-006 1e-005 1.02e-005
63 8.93444e-006 1e-005 1.02e-005
64 1.31182e-005 1e-005 1.02e-005
65 1.79136e-005 1e-005 1.02e-005
66 2.3314e-005 1e-005 1.02e-005
67 2.9333e-005 1e-005 1.02e-005
68 3.59266e-005 1e-005 1.02e-005
69 4.31761e-005 1e-005 1.02e-005
70 5.09889e-005 1e-005 1.02e-005
71 5.94634e-005 1e-005 1.02e-005
72 6.84967e-005 1e-005 1.02e-005
73 7.8198e-005 1e-005 1.02e-005
74 8.84392e-005 1e-005 1.02e-005
75 9.93694e-005 1e-005 1.02e-005
76 0.000110811 1e-005 1.02e-005
77 0.00012289 1e-005 1.02e-005
78 0.000135515 1e-005 1.02e-005
79 0.000148799 1e-005 1.02e-005
80 0.000162664 1e-005 1.02e-005
81 2.53127e-006 1e-005 1.02e-005
82 5.72998e-006 1e-005 1.02e-005
83 9.54195e-006 1e-005 1.02e-005
84 1.40013e-005 1e-005 1.02e-005
85 1.91076e-005 1e-005 1.02e-005
86 2.48313e-005 1e-005 1.02e-005
87 3.12246e-005 1e-005 1.02e-005
88 3.82451e-005 1e-005 1.02e-005
89 4.59383e-005 1e-005 1.02e-005
90 5.43192e-005 1e-005 1.02e-005
91 6.32779e-005 1e-005 1.02e-005
92 7.29517e-005 1e-005 1.02e-005
93 8.32275e-005 1e-005 1.02e-005
94 9.42133e-005 1e-005 1.02e-005
95 0.000105792 1e-005 1.02e-005
96 0.000118051 1e-005 1.02e-005
97 0.00013091 1e-005 1.02e-005
98 0.000144435 1e-005 1.02e-005
99 0.000158566 1e-005 1.02e-005
100 0.000173324 1e-005 1.02e-005
101 2.70084e-006 1e-005 1.02e-005
102 6.08804e-006 1e-005 1.02e-005
103 1.01309e-005 1e-005 1.02e-005
104 1.48588e-005 1e-005 1.02e-005
105 2.02551e-005 1e-005 1.02e-005
106 2.63259e-005 1e-005 1.02e-005
107 3.31072e-005 1e-005 1.02e-005
108 4.05473e-005 1e-005 1.02e-005
109 4.87006e-005 1e-005 1.02e-005
110 5.75245e-005 1e-005 1.02e-005
111 6.70787e-005 1e-005 1.02e-005
112 7.7313e-005 1e-005 1.02e-005
113 8.82438e-005 1e-005 1.02e-005
114 9.98267e-005 1e-005 1.02e-005
115 0.000112141 1e-005 1.02e-005
116 0.000125152 1e-005 1.02e-005
117 0.000138777 1e-005 1.02e-005
118 0.000153199 1e-005 1.02e-005
119 0.000168253 1e-005 1.02e-005
120 0.000183974 1e-005 1.02e-005
121 1.82588e-006 1e-005 1.02e-005
122 4.17134e-006 1e-005 1.02e-005
123 7.00321e-006 1e-005 1.02e-005
124 1.03301e-005 1e-005 1.02e-005
125 1.41369e-005 1e-005 1.02e-005
126 1.84238e-005 1e-005 1.02e-005
127 2.32117e-005 1e-005 1.02e-005
128 2.84883e-005 1e-005 1.02e-005
129 3.42491e-005 1e-005 1.02e-005
130 4.04575e-005 1e-005 1.02e-005
131 4.71822e-005 1e-005 1.02e-005
132 5.43457e-005 1e-005 1.02e-005
133 6.20163e-005 1e-005 1.02e-005
134 7.01661e-005 1e-005 1.02e-005
135 7.87419e-005 1e-005 1.02e-005
136 8.7822e-005 1e-005 1.02e-005
137 9.73496e-005 1e-005 1.02e-005
138 0.000107334 1e-005 1.02e-005
139 0.00011775 1e-005 1.02e-005
140 0.000128672 1e-005 1.02e-005
141 2.01474e-006 1e-005 1.02e-005
142 4.58268e-006 1e-005 1.02e-005
143 7.67373e-006 1e-005 1.02e-005
144 1.13006e-005 1e-005 1.02e-005
145 1.54471e-005 1e-005 1.02e-005
146 2.01132e-005 1e-005 1.02e-005
147 2.53309e-005 1e-005 1.02e-005
148 3.10536e-005 1e-005 1.02e-005
149 3.73023e-005 1e-005 1.02e-005
150 4.41231e-005 1e-005 1.02e-005
151 5.14188e-005 1e-005 1.02e-005
152 5.92874e-005 1e-005 1.02e-005
153 6.75954e-005 1e-005 1.02e-005
154 7.64433e-005 1e-005 1.02e-005
155 8.58157e-005 1e-005 1.02e-005
156 9.57088e-005 1e-005 1.02e-005
157 0.000106059 1e-005 1.02e-005
158 0.000116983 1e-005 1.02e-005
159 0.000128391 1e-005 1.02e-005
160 0.000140257 1e-005 1.02e-005
161 2.19203e-006 1e-005 1.02e-005
162 4.97675e-006 1e-005 1.02e-005
163 8.3144e-006 1e-005 1.02e-005
164 1.22347e-005 1e-005 1.02e-005
165 1.66951e-005 1e-005 1.02e-005
166 2.17464e-005 1e-005 1.02e-005
167 2.73532e-005 1e-005 1.02e-005
168 3.35368e-005 1e-005 1.02e-005
169 4.02896e-005 1e-005 1.02e-005
170 4.75927e-005 1e-005 1.02e-005
171 5.55096e-005 1e-005 1.02e-005
172 6.39629e-005 1e-005 1.02e-005
173 7.29618e-005 1e-005 1.02e-005
174 8.25448e-005 1e-005 1.02e-005
175 9.26558e-005 1e-005 1.02e-005
176 0.000103305 1e-005 1.02e-005
177 0.000114593 1e-005 1.02e-005
178 0.000126368 1e-005 1.02e-005
179 0.000138698 1e-005 1.02e-005
180 0.000151569 1e-005 1.02e-005
181 2.36219e-006 1e-005 1.02e-005
182 5.35277e-006 1e-005 1.02e-005
183 8.93444e-006 1e-005 1.02e-005
184 1.31182e-005 1e-005 1.02e-005
185 1.79136e-005 1e-005 1.02e-005
186 2.3314e-005 1e-005 1.02e-005
187 2.9333e-005 1e-005 1.02e-005
188 3.59266e-005 1e-005 1.02e-005
189 4.31761e-005 1e-005 1.02e-005
190 5.09889e-005 1e-005 1.02e-005
191 5.94634e-005 1e-005 1.02e-005
192 6.84967e-005 1e-005 1.02e-005
193 7.8198e-005 1e-005 1.02e-005
194 8.84392e-005 1e-005 1.02e-005
195 9.93694e-005 1e-005 1.02e-005
196 0.000110811 1e-005 1.02e-005
197 0.00012289 1e-005 1.02e-005
198 0.000135515 1e-005 1.02e-005
199 0.000148799 1e-005 1.02e-005
200 0.000162664 1e-005 1.02e-005
201 2.53127e-006 1e-005 1.02e-005
202 5.72998e-006 1e-005 1.02e-005
203 9.54195e-006 1e-005 1.02e-005
204 1.40013e-005 1e-005 1.02e-005
205 1.91076e-005 1e-005 1.02e-005
206 2.48313e-005 1e-005 1.02e-005
207 3.12246e-005 1e-005 1.02e-005
208 3.82451e-005 1e-005 1.02e-005
209 4.59383e-005 1e-005 1.02e-005
210 5.43192e-005 1e-005 1.02e-005
211 6.32779e-005 1e-005 1.02e-005
212 7.29517e-005 1e-005 1.02e-005
213 8.32275e-005 1e-005 1.02e-005
214 9.42133e-005 1e-005 1.02e-005
215 0.000105792 1e-005 1.02e-005
216 0.000118051 1e-005 1.02e-005
217 0.00013091 1e-005 1.02e-005
218 0.000144435 1e-005 1.02e-005
219 0.000158566 1e-005 1.02e-005
220 0.000173324 1e-005 1.02e-005
221 2.70084e-006 1e-005 1.02e-005
222 6.08804e-006 1e-005 1.02e-005
223 1.01309e-005 1e-005 1.02e-005
224 1.48588e-005 1e-005 1.02e-005
225 2.02551e-005 1e-005 1.02e-005
226 2.63259e-005 1e-005 1.02e-005
227 3.31072e-005 1e-005 1.02e-005
228 4.05473e-005 1e-005 1.02e-005
229 4.87006e-005 1e-005 1.02e-005
230 5.75245e-005 1e-005 1.02e-005
231 6.70787e-005 1e-005 1.02e-005
232 7.7313e-005 1e-005 1.02e-005
233 8.82438e-005 1e-005 1.02e-005
234 9.98267e-005 1e-005 1.02e-005
235 0.000112141 1e-005 1.02e-005
236 0.000125152 1e-005 1.02e-005
237 0.000138777 1e-005 1.02e-005
238 0.000153199 1e-005 1.02e-005
239 0.000168253 1e-005 1.02e-005
240 0.000183974 1e-005 1.02e-005
Measurement: eoff
step INTEG(v(drain)*ix(m1:d)) FROM TO
1 4.23893e-006 2e-005 2.02e-005
2 6.95585e-006 2e-005 2.02e-005
3 1.0193e-005 2e-005 2.02e-005
4 1.3824e-005 2e-005 2.02e-005
5 1.78051e-005 2e-005 2.02e-005
6 2.21101e-005 2e-005 2.02e-005
7 2.67549e-005 2e-005 2.02e-005
8 3.17371e-005 2e-005 2.02e-005
9 3.70578e-005 2e-005 2.02e-005
10 4.277e-005 2e-005 2.02e-005
11 4.87986e-005 2e-005 2.02e-005
12 5.51665e-005 2e-005 2.02e-005
13 6.19453e-005 2e-005 2.02e-005
14 6.915e-005 2e-005 2.02e-005
15 7.66868e-005 2e-005 2.02e-005
16 8.46352e-005 2e-005 2.02e-005
17 9.29818e-005 2e-005 2.02e-005
18 0.000101657 2e-005 2.02e-005
19 0.000110735 2e-005 2.02e-005
20 0.000120178 2e-005 2.02e-005
21 4.69635e-006 2e-005 2.02e-005
22 7.69407e-006 2e-005 2.02e-005
23 1.12591e-005 2e-005 2.02e-005
24 1.52438e-005 2e-005 2.02e-005
25 1.9606e-005 2e-005 2.02e-005
26 2.43249e-005 2e-005 2.02e-005
27 2.94065e-005 2e-005 2.02e-005
28 3.48604e-005 2e-005 2.02e-005
29 4.06825e-005 2e-005 2.02e-005
30 4.69548e-005 2e-005 2.02e-005
31 5.35431e-005 2e-005 2.02e-005
32 6.06112e-005 2e-005 2.02e-005
33 6.81013e-005 2e-005 2.02e-005
34 7.60042e-005 2e-005 2.02e-005
35 8.43295e-005 2e-005 2.02e-005
36 9.31359e-005 2e-005 2.02e-005
37 0.00010231 2e-005 2.02e-005
38 0.000111976 2e-005 2.02e-005
39 0.000121963 2e-005 2.02e-005
40 0.000132423 2e-005 2.02e-005
41 5.1599e-006 2e-005 2.02e-005
42 8.41701e-006 2e-005 2.02e-005
43 1.22973e-005 2e-005 2.02e-005
44 1.66192e-005 2e-005 2.02e-005
45 2.13463e-005 2e-005 2.02e-005
46 2.64597e-005 2e-005 2.02e-005
47 3.19739e-005 2e-005 2.02e-005
48 3.78825e-005 2e-005 2.02e-005
49 4.41972e-005 2e-005 2.02e-005
50 5.09872e-005 2e-005 2.02e-005
51 5.82033e-005 2e-005 2.02e-005
52 6.59461e-005 2e-005 2.02e-005
53 7.406e-005 2e-005 2.02e-005
54 8.27488e-005 2e-005 2.02e-005
55 9.18643e-005 2e-005 2.02e-005
56 0.000101476 2e-005 2.02e-005
57 0.000111573 2e-005 2.02e-005
58 0.000122229 2e-005 2.02e-005
59 0.000133124 2e-005 2.02e-005
60 0.000144596 2e-005 2.02e-005
61 5.63236e-006 2e-005 2.02e-005
62 9.13522e-006 2e-005 2.02e-005
63 1.33072e-005 2e-005 2.02e-005
64 1.79548e-005 2e-005 2.02e-005
65 2.30477e-005 2e-005 2.02e-005
66 2.85415e-005 2e-005 2.02e-005
67 3.44904e-005 2e-005 2.02e-005
68 4.0866e-005 2e-005 2.02e-005
69 4.7659e-005 2e-005 2.02e-005
70 5.50591e-005 2e-005 2.02e-005
71 6.27947e-005 2e-005 2.02e-005
72 7.11432e-005 2e-005 2.02e-005
73 8.00001e-005 2e-005 2.02e-005
74 8.94251e-005 2e-005 2.02e-005
75 9.93542e-005 2e-005 2.02e-005
76 0.000109774 2e-005 2.02e-005
77 0.00012074 2e-005 2.02e-005
78 0.000132208 2e-005 2.02e-005
79 0.000144181 2e-005 2.02e-005
80 0.00015664 2e-005 2.02e-005
81 6.10254e-006 2e-005 2.02e-005
82 9.83685e-006 2e-005 2.02e-005
83 1.42959e-005 2e-005 2.02e-005
84 1.92432e-005 2e-005 2.02e-005
85 2.4707e-005 2e-005 2.02e-005
86 3.05967e-005 2e-005 2.02e-005
87 3.69216e-005 2e-005 2.02e-005
88 4.37559e-005 2e-005 2.02e-005
89 5.11195e-005 2e-005 2.02e-005
90 5.89263e-005 2e-005 2.02e-005
91 6.734e-005 2e-005 2.02e-005
92 7.63461e-005 2e-005 2.02e-005
93 8.58748e-005 2e-005 2.02e-005
94 9.60459e-005 2e-005 2.02e-005
95 0.000106726 2e-005 2.02e-005
96 0.00011802 2e-005 2.02e-005
97 0.000129852 2e-005 2.02e-005
98 0.000142253 2e-005 2.02e-005
99 0.000155198 2e-005 2.02e-005
100 0.000168663 2e-005 2.02e-005
101 6.5849e-006 2e-005 2.02e-005
102 1.05374e-005 2e-005 2.02e-005
103 1.52673e-005 2e-005 2.02e-005
104 2.05492e-005 2e-005 2.02e-005
105 2.63589e-005 2e-005 2.02e-005
106 3.26249e-005 2e-005 2.02e-005
107 3.93226e-005 2e-005 2.02e-005
108 4.66382e-005 2e-005 2.02e-005
109 5.44663e-005 2e-005 2.02e-005
110 6.28883e-005 2e-005 2.02e-005
111 7.18675e-005 2e-005 2.02e-005
112 8.15138e-005 2e-005 2.02e-005
113 9.17877e-005 2e-005 2.02e-005
114 0.000102613 2e-005 2.02e-005
115 0.000114123 2e-005 2.02e-005
116 0.000126246 2e-005 2.02e-005
117 0.000138925 2e-005 2.02e-005
118 0.000152236 2e-005 2.02e-005
119 0.000166172 2e-005 2.02e-005
120 0.000180598 2e-005 2.02e-005
121 4.23893e-006 2e-005 2.02e-005
122 6.95585e-006 2e-005 2.02e-005
123 1.0193e-005 2e-005 2.02e-005
124 1.3824e-005 2e-005 2.02e-005
125 1.78051e-005 2e-005 2.02e-005
126 2.21101e-005 2e-005 2.02e-005
127 2.67549e-005 2e-005 2.02e-005
128 3.17371e-005 2e-005 2.02e-005
129 3.70578e-005 2e-005 2.02e-005
130 4.277e-005 2e-005 2.02e-005
131 4.87986e-005 2e-005 2.02e-005
132 5.51665e-005 2e-005 2.02e-005
133 6.19453e-005 2e-005 2.02e-005
134 6.915e-005 2e-005 2.02e-005
135 7.66868e-005 2e-005 2.02e-005
136 8.46352e-005 2e-005 2.02e-005
137 9.29818e-005 2e-005 2.02e-005
138 0.000101657 2e-005 2.02e-005
139 0.000110735 2e-005 2.02e-005
140 0.000120178 2e-005 2.02e-005
141 4.69635e-006 2e-005 2.02e-005
142 7.69407e-006 2e-005 2.02e-005
143 1.12591e-005 2e-005 2.02e-005
144 1.52438e-005 2e-005 2.02e-005
145 1.9606e-005 2e-005 2.02e-005
146 2.43249e-005 2e-005 2.02e-005
147 2.94065e-005 2e-005 2.02e-005
148 3.48604e-005 2e-005 2.02e-005
149 4.06825e-005 2e-005 2.02e-005
150 4.69548e-005 2e-005 2.02e-005
151 5.35431e-005 2e-005 2.02e-005
152 6.06112e-005 2e-005 2.02e-005
153 6.81013e-005 2e-005 2.02e-005
154 7.60042e-005 2e-005 2.02e-005
155 8.43295e-005 2e-005 2.02e-005
156 9.31359e-005 2e-005 2.02e-005
157 0.00010231 2e-005 2.02e-005
158 0.000111976 2e-005 2.02e-005
159 0.000121963 2e-005 2.02e-005
160 0.000132423 2e-005 2.02e-005
161 5.1599e-006 2e-005 2.02e-005
162 8.41701e-006 2e-005 2.02e-005
163 1.22973e-005 2e-005 2.02e-005
164 1.66192e-005 2e-005 2.02e-005
165 2.13463e-005 2e-005 2.02e-005
166 2.64597e-005 2e-005 2.02e-005
167 3.19739e-005 2e-005 2.02e-005
168 3.78825e-005 2e-005 2.02e-005
169 4.41972e-005 2e-005 2.02e-005
170 5.09872e-005 2e-005 2.02e-005
171 5.82033e-005 2e-005 2.02e-005
172 6.59461e-005 2e-005 2.02e-005
173 7.406e-005 2e-005 2.02e-005
174 8.27488e-005 2e-005 2.02e-005
175 9.18643e-005 2e-005 2.02e-005
176 0.000101476 2e-005 2.02e-005
177 0.000111573 2e-005 2.02e-005
178 0.000122229 2e-005 2.02e-005
179 0.000133124 2e-005 2.02e-005
180 0.000144596 2e-005 2.02e-005
181 5.63236e-006 2e-005 2.02e-005
182 9.13522e-006 2e-005 2.02e-005
183 1.33072e-005 2e-005 2.02e-005
184 1.79548e-005 2e-005 2.02e-005
185 2.30477e-005 2e-005 2.02e-005
186 2.85415e-005 2e-005 2.02e-005
187 3.44904e-005 2e-005 2.02e-005
188 4.0866e-005 2e-005 2.02e-005
189 4.7659e-005 2e-005 2.02e-005
190 5.50591e-005 2e-005 2.02e-005
191 6.27947e-005 2e-005 2.02e-005
192 7.11432e-005 2e-005 2.02e-005
193 8.00001e-005 2e-005 2.02e-005
194 8.94251e-005 2e-005 2.02e-005
195 9.93542e-005 2e-005 2.02e-005
196 0.000109774 2e-005 2.02e-005
197 0.00012074 2e-005 2.02e-005
198 0.000132208 2e-005 2.02e-005
199 0.000144181 2e-005 2.02e-005
200 0.00015664 2e-005 2.02e-005
201 6.10254e-006 2e-005 2.02e-005
202 9.83685e-006 2e-005 2.02e-005
203 1.42959e-005 2e-005 2.02e-005
204 1.92432e-005 2e-005 2.02e-005
205 2.4707e-005 2e-005 2.02e-005
206 3.05967e-005 2e-005 2.02e-005
207 3.69216e-005 2e-005 2.02e-005
208 4.37559e-005 2e-005 2.02e-005
209 5.11195e-005 2e-005 2.02e-005
210 5.89263e-005 2e-005 2.02e-005
211 6.734e-005 2e-005 2.02e-005
212 7.63461e-005 2e-005 2.02e-005
213 8.58748e-005 2e-005 2.02e-005
214 9.60459e-005 2e-005 2.02e-005
215 0.000106726 2e-005 2.02e-005
216 0.00011802 2e-005 2.02e-005
217 0.000129852 2e-005 2.02e-005
218 0.000142253 2e-005 2.02e-005
219 0.000155198 2e-005 2.02e-005
220 0.000168663 2e-005 2.02e-005
221 6.5849e-006 2e-005 2.02e-005
222 1.05374e-005 2e-005 2.02e-005
223 1.52673e-005 2e-005 2.02e-005
224 2.05492e-005 2e-005 2.02e-005
225 2.63589e-005 2e-005 2.02e-005
226 3.26249e-005 2e-005 2.02e-005
227 3.93226e-005 2e-005 2.02e-005
228 4.66382e-005 2e-005 2.02e-005
229 5.44663e-005 2e-005 2.02e-005
230 6.28883e-005 2e-005 2.02e-005
231 7.18675e-005 2e-005 2.02e-005
232 8.15138e-005 2e-005 2.02e-005
233 9.17877e-005 2e-005 2.02e-005
234 0.000102613 2e-005 2.02e-005
235 0.000114123 2e-005 2.02e-005
236 0.000126246 2e-005 2.02e-005
237 0.000138925 2e-005 2.02e-005
238 0.000152236 2e-005 2.02e-005
239 0.000166172 2e-005 2.02e-005
240 0.000180598 2e-005 2.02e-005
Date: Sun Sep 22 18:48:00 2019
Total elapsed time: 186.382 seconds.
tnom = 27
temp = 27
method = modified trap
totiter = 4603
traniter = 4603
tranpoints = 1964
accept = 1663
rejected = 301
matrix size = 43
fillins = 99
solver = Normal
Matrix Compiler1: 9.73 KB object code size 5.9/3.3/[0.7]
Matrix Compiler2: 5.38 KB object code size 1.4/3.0/[0.5]
</code></pre>
<p>The example log file can also be found <a href="https://github.com/realtime/python-tools/blob/master/testdata/loss.log" rel="nofollow noreferrer">here</a>, as well as the <a href="https://github.com/realtime/python-tools/blob/master/ltparse.py" rel="nofollow noreferrer">code</a> above, both on my GitHub.</p>
<p>Please note: <em>I am not a professional programmer</em>, I only write code to support my main activity which is electronics engineering.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T18:46:06.840",
"Id": "446479",
"Score": "6",
"body": "To whoever is voting to close this question: don't forget to leave a comment."
}
] |
[
{
"body": "<p>I wrote an example of what you can do to clean this up:</p>\n\n<pre><code>import re\nfrom collections import OrderedDict\nfrom csv import DictWriter\nfrom os.path import splitext\nfrom sys import argv\nfrom typing import Iterable\n\n\ndef get_measure_matches(log: str) -> tuple:\n return tuple(re.finditer(r'Measurement: (.*)$', log, re.M))\n\n\ndef parse_main(log: str, measure_matches: tuple) -> (list, OrderedDict):\n all_cols = OrderedDict((('step', None),))\n rows = []\n main_row_re = re.compile(r'(\\S+)=(\\S+)')\n main_lines = log[:measure_matches[0].start()].splitlines()\n step = 1\n for line in main_lines:\n row = {}\n for match in main_row_re.finditer(line):\n k, v = match.groups()\n all_cols[k] = None\n row[k] = v\n if row:\n row['step'] = step\n rows.append(row)\n step += 1\n\n for m in measure_matches:\n all_cols[m[1]] = None\n\n return rows, all_cols\n\n\ndef parse_measures(log: str, measure_matches: tuple, rows: Iterable[dict]):\n measure_ends = (*(m.start() for m in measure_matches[1:]), -1)\n\n measure_re = re.compile(r'^\\s*(\\S+)\\s+(\\S+)', re.M)\n for measure, measure_end in zip(measure_matches, measure_ends):\n measure_name = measure[1]\n blob = log[measure.end(): measure_end]\n\n for match in measure_re.finditer(blob):\n try:\n step, val = match.groups()\n rows[int(step) - 1][measure_name] = float(val)\n except ValueError:\n pass\n\n\ndef write_csv(rows: Iterable[dict], cols: Iterable[str], csv_filename: str):\n \"\"\"\n step,iload,vdc,rg,eon,eoff\n 1,10.0,36.0,1.0,1.82588e-06,4.23893e-06\n 2,20.0,36.0,1.0,4.17134e-06,6.95585e-06\n (etc)\n \"\"\"\n with open(csv_filename, 'w') as csv_file:\n writer = DictWriter(csv_file, cols)\n writer.writeheader()\n writer.writerows(rows)\n\n\ndef main():\n log_filename = argv[1]\n with open(log_filename) as log_file:\n log = log_file.read()\n\n measure_matches = get_measure_matches(log)\n rows, all_cols = parse_main(log, measure_matches)\n\n parse_measures(log, measure_matches, rows)\n\n csv_filename = splitext(log_filename)[0] + '.csv'\n write_csv(rows, all_cols.keys(), csv_filename)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>There are methods</li>\n<li>No need to use pandas - this runs on base Python 3</li>\n<li>Better use of <code>finditer</code></li>\n<li>Type hints</li>\n<li>No need to call <code>group(n)</code></li>\n<li>Implicitly close files in a context manager</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T03:11:48.043",
"Id": "229549",
"ParentId": "229532",
"Score": "4"
}
},
{
"body": "<p>I started reviewing this last night, and got way off track from what you need. You've been clear that this is hobbyist code that already works; the only reason you're hear asking how to improve it is (I guess) so it'll be easier for you to resume work on a year from now.</p>\n\n<h2>First, some responses to your actual code:</h2>\n\n<ul>\n<li>Breaking your code up into functions is often good, even if the function is only used once. This <em>can</em> make things more verbose, but it's worth it if it helps us understand the flow of the code, or helps us consider pieces of it in isolation. </li>\n<li>It's my opinion that strong <a href=\"https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5\">type signatures</a> are always a good idea. They clarify what you code does, and unlike a comment they can't be wrong.</li>\n<li>The example log file has less than a thousand lines. For a small enough file, it will make sense to read the whole thing into a list of strings before trying to work with it. It's more performant to work with streams than lists, but realizing that performance benefit here would be hard because we have to hold all the <em>data</em> from the first n-1 sections in memory until we get to the last section. <strong>Until you start having performance problems, load all your data right at the beginning.</strong></li>\n<li><a href=\"https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html\" rel=\"nofollow noreferrer\">List comprehensions</a> are wonderful and cover all the basic python data structures. That said, in order for them to work for this situation you'll need some <a href=\"https://docs.python.org/3/library/itertools.html#module-itertools\" rel=\"nofollow noreferrer\">helper functions</a>.</li>\n<li>You're writing this as a CLI tool. Using the <a href=\"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html\" rel=\"nofollow noreferrer\">main-function pattern</a> will make the code easier to play with in other contexts.</li>\n</ul>\n\n<h2>What I wrote last night:</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\nimport pandas as pd\nimport os\nimport sys\nfrom itertools import chain, dropwhile, groupby\nfrom typing import *\n\ndef read_lines(file_name:str) -> Iterable[str]:\n with open(file_name, 'r') as f: # This is generally preferable to closing the file manually.\n return [line.strip() for line in f]\n\ndef parse_lines(lines: Iterable[str]) -> Dict[int, Dict[str, float]]:\n runs = [\n run\n for run\n in map(lambda g: list(g[1]), groupby(lines, bool))\n # filter out the headers, footers, and empty lines:\n if any(l.startswith('.step') or l.startswith('Measurement:') for l in run)\n ]\n steps = {\n step_number: read_step(line)\n for (step_number, line)\n in enumerate(\n dropwhile(lambda l: not l.startswith('.step'),\n runs[0]),\n 1)\n }\n metrics = {\n read_measurment_key(measurment_batch[0]): {\n int(step_number): float(measurement)\n for [step_number, measurement]\n in map(lambda m: m.split()[0:2], measurment_batch[2:])\n }\n for measurment_batch in runs[1:]\n }\n return {\n step_number: dict(chain(\n step.items(),\n (\n (measurment_key, measurments[step_number])\n for (measurment_key, measurments)\n in metrics.items()\n )\n ))\n for (step_number, step) in steps.items()\n }\n\ndef read_step(line: str) -> Dict[str, float]:\n match = re.match(r'\\.step (.*)', line) # For performance we could compile the regex.\n return {\n key: float(value)\n for [key, value]\n in map(\n lambda parameter: parameter.split('='),\n match.group(1).split()\n )\n }\n\ndef read_measurment_key(line: str) -> str:\n match = re.match(r'Measurement: (.*)', line) # For performance we could compile the regex.\n return match.group(1)\n\ndef main():\n logfilename = 'loss.log' # Or read the argument as you did.\n csvfilename = os.path.splitext(logfilename)[0] + '.csv'\n\n log_file_lines = read_lines(logfilename)\n data = parse_lines(log_file_lines)\n frame = pd.DataFrame(\n dict(step = step_number, **values)\n for (step_number, values) in data.items()\n ).set_index('step')\n\n frame.to_csv(csvfilename)\n\nif __name__== \"__main__\":\n main()\n</code></pre>\n\n<h2>Is that better?</h2>\n\n<p>I don't know.</p>\n\n<ul>\n<li>Is it readable to you? It sounds like you probably don't already know most of the syntax used, and there's probably only so much new stuff you'll want to learn for this project.</li>\n<li>When you need to update it a year from now, will it be clear what the current <code>runs = [...]</code> section is doing? Will you be able to make the needed changes with minimal trial and error? </li>\n<li>Does it actually work? I know it <em>runs</em>, and the output <em>looks</em> the same, but how do we know I didn't introduce some small bug such that 5% of your data is now wrong?</li>\n<li>How will it handle bad data? I didn't put in any kind of error detection. </li>\n</ul>\n\n<h2>What's good about it?</h2>\n\n<ul>\n<li>The use of typed functions will help us be sure the code is doing what we intend it to do. I could actually have taken this further by moving <em>more</em> stuff out into individual functions.</li>\n<li>The use of list comprehensions and other \"functional programming\" styles means that we're never mutating the state of a variable. This also helps us be sure everything is working as intended.</li>\n<li>The use of <a href=\"https://www.geeksforgeeks.org/pure-functions/\" rel=\"nofollow noreferrer\">pure functions</a> also helps us be sure everything is working as intended.</li>\n<li>Basically every \"line\" can be read as \"build a value\", and the nature of those values is clearly (?) indicated by the names of the variables we assigning to or the functions we're returning from.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:36:07.443",
"Id": "446861",
"Score": "0",
"body": "Thank you very much for your contribution. I will see how I can benefit from it and then get back. Some remarks: You write it is \"hobbyist code\". This is almost certainly true regarding my skill level, but nevertheless this code was created for a professional purpose, just in a different domain. Also, looking at your code (and that of @Reinderien) I realize that there is one feature in my original code I like: It follows the sequence of the original log file. In 80% of usage I actually read the log file and do not use the parser. That makes it easy to retrace what the parser is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:46:01.130",
"Id": "446862",
"Score": "0",
"body": "Interesting. I guess the (structured, explicit) way to implement that way of thinking would be a \"Builder\" pattern: A class that sets up an empty data structure (possibly a data-frame, possibly something custom) on `__init__()`, and then exposes a (stateful) `ingest(self, line:str)` function and some kind of final-output function. But really it's not clear what would make one implementation better than another for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:46:16.557",
"Id": "229565",
"ParentId": "229532",
"Score": "3"
}
},
{
"body": "<p>The log file looks like it is made up of bunch of sections separated by blank lines. So, an approach is to code functions to parse each section. The main driver can scan the log file to find the sections and then pass the parsing off to the parsing functions. The parsing functions have a common interface, to make it easy to add new parsing functions.</p>\n\n<p>The code below is mostly comments and doc strings.</p>\n\n<p>This is the driver. It iterates over the lines in the log file, trying to identify what kind of section it's reading. For example, if a line starts with '.step' it is in the 'step' section, etc.</p>\n\n<pre><code>def parse_log(lines):\n \"\"\"\n Parses a log file in which sections are delimited by blank lines.\n\n Input 'lines' is an iterable over the lines of the log file.\n Output is a defaultdict of dictionaries. The defaultdict is keyed by\n step number. The dict for each step is a dict of the parameters and \n measurements associated with that step:\n\n defaultdict(dict,\n {1: {'step': 1, 'iload': '10', 'vdc': '36', 'rg': '1',\n 'eon': '1.82588e-006', 'eoff': '4.23893e-006'},\n 2: {'step': 2, 'iload': '20', 'vdc': '36', 'rg': '1',\n 'eon': '4.17134e-006', 'eoff': '6.95585e-006'},\n 3: {'step': 3, 'iload': '30', 'vdc': '36', 'rg': '1',\n 'eon': '7.00321e-006', 'eoff': '1.0193e-005'},\n ...\n })\n \"\"\"\n\n # Lines in the input are checked to see if the section can be identified. If a section is\n # identified a section specific parsing function is called. If a section cannot be identified\n # from a line, the line is appended to 'leadin'.\n #\n # Some sections are easier to identify after reading a few lines. For example, the\n # 'step' section contains lines that start with '.step'. \n #\n # m1:1:v_sm: Missing value, assumed 0V @ DC\n # Per .tran options, skipping operating point for transient analysis.\n # .step iload=10 vdc=36 rg=1\n # .step iload=20 vdc=36 rg=1\n # ...\n # \n # The list of the 'leadin' lines are passed to 'section()' so that the section specific \n # parsing function gets all of the lines in the section (e.g., the m1:1 ..., and Per ... lines\n # in the example above). \n #\n # Section specific parsing functions are expected to return a dictionary, keyed by step number,\n # of dictionaries containing parameter or measurement names and their values. The section\n # specific dictionaries are merged and returned.\n\n data = defaultdict(dict)\n\n leadin = []\n section_data = None\n\n for line in lines:\n\n line = line.lstrip()\n\n if not line:\n if leadin:\n leadin = []\n\n # If 'leadin' is is not empty, there was an unknown or unrecognized section.\n # For debuging, it might be useful to print (or log) the first few lines.\n #print(f\"unknown section: {leadin[:5]}\")\n\n continue\n\n leadin.append(line)\n\n if line.startswith('.step'):\n section_data = parse_step_section(section(lines, leadin))\n\n elif line.startswith('Measurement: '):\n section_data = parse_measurement_section(section(lines, leadin))\n\n if section_data:\n for step,fields in section_data.items():\n data[step].update(fields)\n\n leadin = []\n section_data = None\n\n return data\n</code></pre>\n\n<p>These are the section specific parsing routines:</p>\n\n<pre><code>def parse_step_section(lines):\n \"\"\"\n Section specific parse function for the 'step' section of a log file.\n\n Input 'lines' is an iterable (e.g., a file, list, etc.) over lines of the section. \n\n The section looks like:\n\n m1:1:v_sm: Missing value, assumed 0V @ DC\n Per .tran options, skipping operating point for transient analysis.\n .step iload=10 vdc=36 rg=1\n .step iload=20 vdc=36 rg=1\n .step iload=30 vdc=36 rg=1\n .step iload=40 vdc=36 rg=1\n ...\n\n The '.step' lines are implicitly numbered, starting at 1.\n\n Output is a dict of dicts. The outer dict is keyed by step. The inner dicts are \n keyed by parameter name. Like this:\n\n {1: {'step': 1, 'iload': '10', 'vdc': '36', 'rg': '1'},\n 2: {'step': 2, 'iload': '20', 'vdc': '36', 'rg': '1'},\n 3: {'step': 3, 'iload': '30', 'vdc': '36', 'rg': '1'},\n 4: {'step': 4, 'iload': '40', 'vdc': '36', 'rg': '1'},\n ...\n }\n\n \"\"\"\n\n # The first two lines are skipped, because they aren't being used.\n next(lines)\n next(lines)\n\n pattern = re.compile(r\"(\\S+)=(\\S+)\")\n\n data = {}\n\n for step,line in enumerate(lines, 1):\n d = dict([('step',step)] + pattern.findall(line))\n data[step] = d\n\n return data\n\n\ndef parse_measurement_section(lines):\n \"\"\"\n Section specific parse function for a measurement section.\n\n Input 'lines' is an iterable (e.g., a file, list, etc.) over lines of the section. \n\n The section looks like:\n\n Measurement: eon\n step INTEG(v(drain)*ix(m1:d)) FROM TO\n 1 1.82588e-006 1e-005 1.02e-005\n 2 4.17134e-006 1e-005 1.02e-005\n 3 7.00321e-006 1e-005 1.02e-005\n 4 1.03301e-005 1e-005 1.02e-005\n ...\n\n The first line contains the name of the measurement (e.g., 'eon').\n The second line contains the header for the following table.\n The table is terminated with a blank line.\n\n This function only parses the first two columns and returns a dictionary like:\n\n {1: {'eon': '1.82588e-006'},\n 2: {'eon': '4.17134e-006'},\n 3: {'eon': '7.00321e-006'},\n 4: {'eon': '1.03301e-005'},\n ....\n }\n \"\"\"\n\n _, name = next(lines).strip().split()\n\n # skip header line\n next(lines) \n\n step_meas_rest = (line.split(maxsplit=2) for line in lines)\n\n data = {int(step):{name:measurement} for step,measurement,_ in step_meas_rest}\n\n return data\n</code></pre>\n\n<p>This is a helper function.</p>\n\n<pre><code>def section(lines, leadin=None):\n \"\"\"\n Generator that yields lines from 'leadin' then from 'lines'. Leading blank lines are skipped.\n It terminates when a trailing blank line is read.\n \"\"\"\n if leadin:\n lines = it.chain(leadin, lines)\n\n line = next(lines).lstrip()\n\n while not line:\n line = next(lines).lstrip()\n\n while line:\n yield line\n line = next(lines).lstrip()\n</code></pre>\n\n<p>The main program:</p>\n\n<pre><code>def main(log, output):\n logdata = parse_log(log)\n\n fieldnames = logdata[1].keys()\n\n writer = csv.DictWriter(output, fieldnames)\n writer.writeheader()\n\n for step, stepdata in logdata.items():\n writer.writerow(stepdata)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T04:04:35.573",
"Id": "229675",
"ParentId": "229532",
"Score": "3"
}
},
{
"body": "<p>The contributed answers each had some valuable contributions, but they did not really achieve the clarity (as perceived by me) I was hoping for. I guess this was mainly due to the fact that the answers were focused very much on how to express code elegantly, but in contrast my thinking is focused on the data.</p>\n\n<p>So I picked some advice from those answers, i.e.</p>\n\n<ul>\n<li>follow the main function convention for CLI programs</li>\n<li>split everything into functions</li>\n<li>read the file to memory at the beginning</li>\n</ul>\n\n<p>But I also kept much of my code, which follows along very much the data as it is presented in the log file. For me, everything I take from the log file is a kind of \"observation\", so storing them as a list of dictionaries makes perfect sense to me and using pandas to transform all those observation in a usable shape also seems straightforward to me.</p>\n\n<p>So in summary, I implemented the advice above and cleaned up my existing code a bit to make it more uniform:</p>\n\n<pre><code>import re\nimport pandas as pd\nimport os\nimport sys\n\ndef read_log(filename):\n with open(filename,'r') as logfile:\n return logfile.readlines()\n\ndef parse_steps(log):\n steps_data = []\n\n step_number = 0\n\n for line in log:\n step_definition = re.match(r'\\.step (.*)', line)\n if step_definition:\n step_number += 1\n row = { 'step': step_number }\n for parameter_match in re.finditer(r'(\\S+)=(\\S+)', step_definition[1]):\n parameter, value = parameter_match.groups()\n row[parameter] = float(value)\n steps_data.append(row)\n\n return steps_data\n\ndef parse_measurements(log):\n measurements_data = []\n\n log_iterator = iter(log)\n\n while True:\n try:\n line = next(log_iterator)\n except StopIteration:\n break\n\n measurement_definition = re.match(r'Measurement: (\\S+)', line)\n if measurement_definition:\n measurement_name = measurement_definition[1]\n next(log_iterator) # skip one line\n\n while True:\n line = next(log_iterator)\n if re.match(r'^\\s*\\n', line): # empty line\n break\n\n measurement_observation = re.match(r'^\\s*(\\S+)\\s+(\\S+)', line)\n if measurement_observation:\n step, value = measurement_observation.groups()\n row = { 'step': int(step), measurement_name: float(value) }\n measurements_data.append(row)\n\n return measurements_data\n\n\ndef main():\n logfilename = sys.argv[1]\n log = read_log(logfilename)\n\n steps = parse_steps(log)\n measurements = parse_measurements(log)\n\n csvfilename = os.path.splitext(logfilename)[0] + '.csv'\n\n frame = pd.DataFrame(steps + measurements).set_index('step').groupby('step').first()\n frame.to_csv(csvfilename)\n\n\nif __name__== \"__main__\":\n main()\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:34:00.840",
"Id": "448446",
"Score": "0",
"body": "Are you happy with this revision or would you like a review of this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T02:39:34.200",
"Id": "448455",
"Score": "0",
"body": "Nice rewrite. Clear and readable. I would add two things: 1) in main, `if sys.argc != 1 or argv[1] in ('-h', '--help')`: print a basic help/usage message and 2) a docstring or comment for the two parsing routines to document the format of the lines they are parsing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T23:02:09.087",
"Id": "448598",
"Score": "0",
"body": "@dfhwze I am fine with it, but if you spot some major problem I might have introduced, let me know."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:31:13.123",
"Id": "230276",
"ParentId": "229532",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229565",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T18:41:30.187",
"Id": "229532",
"Score": "7",
"Tags": [
"python",
"parsing"
],
"Title": "Parser for a log file"
}
|
229532
|
<h3>Selection Sort</h3>
<p>The selection sort algorithm sorts a list (array) by finding the minimum element from the right (unsorted part) of the list and putting it at the left (sorted part) of the list. The algorithm maintains two sub-lists in a given input list.</p>
<ul>
<li><p>The already sorted sub-list</p></li>
<li><p>The remaining unsorted sub-list</p></li>
</ul>
<h3>Bubble Sort</h3>
<p>The Bubble Sort algorithm functions by repeatedly swapping the adjacent elements, if they aren't in order.</p>
<h3>Optimized Bubble Sort</h3>
<p>An optimized version of Bubble Sort algorithm is to break the loop, when there is no further swapping to be made, in one entire pass.</p>
<h3>Insertion Sort</h3>
<p>Insertion sort algorithm builds the final sorted array in a one item at a time manner. It is less efficient on large lists than more advanced algorithms, such as Quick Sort, Heap Sort or Merge Sort, yet it provides some advantages, such as implementation simplicity, efficiency for small datasets and sorting stability.</p>
<hr>
<p>I've been trying to implement the above algorithms in Python, practicing some object-oriented programming also, and I'd appreciate it if you'd review it for changes/improvements.</p>
<h3>Code</h3>
<pre><code>from typing import List, TypeVar
T = TypeVar('T')
class InPlaceSortingAlgorithm(object):
def __init__(self) -> None:
pass
def selection_sort(self, input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer list using Selection Sort method.
Sorting:
- In-Place (space complexity O(1))
- Efficiency (Time Complexity => O(N^2))
- Unstable Sort (Order of duplicate elements is not preserved)
Iterates through the list and swaps the min from the right side
to sorted elements from the left side of the list.
"""
# Is the length of the list.
length = len(input_list)
# Iterates through the list to do the swapping.
for element_index in range(length - 1):
min_index = element_index
# Iterates through the list to find the min index.
for finder_index in range(element_index+1, length):
if input_list[min_index] > input_list[finder_index]:
min_index = finder_index
# Swaps the min value with the pointer value.
if element_index is not min_index:
input_list[element_index], input_list[min_index] = input_list[min_index], input_list[element_index]
return input_list
def length_of_array(self, input_list: List[T]) -> int:
"""
Returns the length of the input array.
"""
return len(input_list)
def bubble_sort(self, input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer list using regular Bubble Sort algorithm.
Sorting:
- In-Place (Space Complexity => O(1))
- Efficiency (Time Complexity => O(N^2))
- Stable Sort (Order of equal elements does not change)
"""
length = self.length_of_array(input_list)
for i in range(length -1 ):
for j in range(length - i - 1):
if input_list[j] > input_list[j+1]:
self.__swap_elements(j, j+1)
return input_list
def optimized_bubble_sort(self, input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer list using an Optimized Bubble Sort algorithm.
For optimization, the Bubble Sort algorithm stops if in a pass there would be no further swaps
between an element of the array and the next element.
Sorting:
- In-Place (Space Complexity => O(1))
- Efficiency (Time Complexity => O(N^2))
- Stable Sort (Order of equal elements does not change)
"""
# Assigns the length of to be sorted array
length = self.length_of_array(input_list)
for i in range(length -1 ):
number_of_swaps = 0
for j in range(length - i - 1):
if input_list[j] > input_list[j+1]:
self.__swap_elements(j, j+1)
number_of_swaps += 1
# If there is no further swap in iteration i, the array is already sorted.
if number_of_swaps == 0:
break
return input_list
def __swap_elements(self, current_index: int, next_index: int) -> None:
"""
Swaps the adjacent elements.
"""
input_list[current_index], input_list[next_index] = input_list[next_index], input_list[current_index]
def insertion_sort(self, input_list: List[T]) -> List[T]:
"""
Iterates through the input array and sorts the array.
"""
# Assigns the length of to be sorted array
length = self.length_of_array(input_list)
# Picks the to-be-inserted element from the right side of the array, starting with index 1.
for i in range(1, length):
element_for_insertion = input_list[i]
# Iterates through the left sorted-side of the array to find the correct position for the element to be inserted.
j = i - 1
while j >= 0 and input_list[j] > element_for_insertion:
input_list[j+1] = input_list[j]
j -= 1
# Inserts the element.
input_list[j+1] = element_for_insertion
return input_list
if __name__ == "__main__":
OBJECT = InPlaceSortingAlgorithm()
TEST_LIST_1 = [10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1]
# Tests the Selection Sort method
print(OBJECT.selection_sort(TEST_LIST_1))
# Tests the Optimized Bubble Sort method
print(OBJECT.optimized_bubble_sort(TEST_LIST_1))
# Tests the Bubble Sort method
print(OBJECT.bubble_sort(TEST_LIST_1))
# Tests the Insertion Sort method
print(OBJECT.insertion_sort(TEST_LIST_1))
</code></pre>
<h3>Input for Testing</h3>
<pre><code>[10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1]
</code></pre>
<h3>Output</h3>
<pre><code>[-93, -45, -30, -1, 0, 4, 9, 10, 23, 23, 23, 23, 82]
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/229509/selection-sort-algorithm-python">Selection Sort Algorithm (Python) - Code Review</a></li>
<li><a href="https://www.geeksforgeeks.org/bubble-sort/" rel="nofollow noreferrer">Bubble Sort (Geeks for Geeks)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Bubble_sort" rel="nofollow noreferrer">Bubble Sort (Wiki)</a></li>
<li><a href="https://www.geeksforgeeks.org/selection-sort/" rel="nofollow noreferrer">Selection Sort (Geeks for Geeks)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Selection_sort" rel="nofollow noreferrer">Selection Sort (Wiki)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow noreferrer">Insertion Sort (Wiki)</a></li>
</ul>
|
[] |
[
{
"body": "<h1>Use of classes / methods</h1>\n\n<ul>\n<li><p>The <code>InPlaceSortingAlgorithm</code> class does not have any data / attributes associated to specific objects. Unlike some OO languages like Java, Python supports top-level function definitions. Therefore there is no real need for a class. If the intention is to group a bunch of reusable methods having similar functionality, create a module and <code>import</code> it from other files.</p></li>\n<li><p>I do not see a need for the wrapper method <code>length_of_array</code>. If you do not intend to modify the behaviour of the built-in <code>len</code> function, just use <code>len</code>. Also, the <code>selection_sort</code> method directly calls <code>len</code>, which is inconsistent with other methods, which call <code>length_of_array</code> instead.</p></li>\n<li><p>The <code>input_list</code> variable is not defined in the <code>__swap_elements</code> method. The method is not functional.</p></li>\n</ul>\n\n<h1>Issues of testing code</h1>\n\n<ul>\n<li><p>In the test code, <code>TEST_LIST_1</code> is sorted in-place by <code>OBJECT.selection_sort</code>. Afterwards, all the remaining methods receive inputs that are already sorted. That is why <code>__swap_elements</code> is never called and the program still runs. To fix this, a copy should be created for each function call using either <code>TEST_LIST_1.copy()</code> or <code>TEST_LIST_1[:]</code>.</p></li>\n<li><p>For more extensive testing, input lists can be randomly generated and the results can be compared with the outcomes of the built-in <code>sorted</code> function.</p></li>\n</ul>\n\n<h2>Coding Style</h2>\n\n<ul>\n<li><p>The style of using whitespaces in expressions are not consistent. Some expressions have whitespaces besides operators (e.g., <code>range(length - 1)</code>) while others do not (e.g., <code>range(element_index+1, length)</code>). The style should be consistent throughout the program.</p></li>\n<li><p>See <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> for more Python style convensions. You can also choose an IDE that has built-in PEP8 inspection or use <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">this website</a> to check the style violations yourself.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T00:48:09.980",
"Id": "229543",
"ParentId": "229535",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T21:07:24.377",
"Id": "229535",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"sorting"
],
"Title": "Sorting Algorithms (Python)"
}
|
229535
|
<p>I'm trying to implement the Wu-Manber algorithm (<a href="http://webglimpse.net/pubs/TR94-17.pdf" rel="noreferrer">http://webglimpse.net/pubs/TR94-17.pdf</a>). From my understanding, the algorithm basically does string matching using a hash table-based approach with chaining to resolve collision.</p>
<p>I have not used C++ for quite a while. I'm looking for help with coding convention for better readability and performance tweaks if possible.</p>
<p>The original algorithm does not work with short patterns (shorter than the value B) so I added the 2 lookups <code>lengthOnePatternLookup_</code> and <code>lengthTwoPatternLookup_</code> to help with it.</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef WU_MANBER_HPP
#define WU_MANBER_HPP
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <math.h>
namespace wu_manber {
namespace { // anonymous namespace, things in here are "private" to wu_manber namespace
// fast mod (ref: https://www.youtube.com/watch?v=nXaxk27zwlk&feature=youtu.be&t=56m34s)
unsigned int fastmod(const int input, const int ceil) {
// apply the modulo operator only when needed
return input >= ceil ? input % ceil : input;
}
}
template<typename CharType>
class WuManber {
public:
using StringType = std::basic_string<CharType>;
WuManber(unsigned short HBITS = 4, size_t tableSize = 32768) :
isInitialized_(false), m_(0), k_(0),
HBITS_(HBITS), tableSize_(tableSize)
{
shiftTable_ = new size_t[tableSize_];
hashPrefixTable_ = new std::vector<PatternHash>[tableSize_];
alphabetSize_ = pow(2, 8 * sizeof(CharType));
isShortPatternExist_ = false;
}
~WuManber() {
delete []shiftTable_;
delete []hashPrefixTable_;
if (isShortPatternExist_) {
delete []lengthOnePatternLookup_;
for (int i = 0; i < alphabetSize_; ++i) {
delete []lengthTwoPatternLookup_[i];
}
delete []lengthTwoPatternLookup_;
}
}
WuManber(const WuManber&) = delete;
WuManber& operator =(const WuManber&) = delete;
const std::vector<StringType>& patternList() const {
return patternList_;
}
void preProcess(const std::vector<StringType> &patterns) {
m_ = 0;
for (const auto &pattern : patterns) {
size_t patternLength = pattern.size();
if (patternLength < B_) {
if (patternLength == 1) {
lengthOnePatterns_.push_back(pattern);
} else if (patternLength == 2) {
lengthTwoPatterns_.push_back(pattern);
}
continue;
}
m_ = (!m_) ? patternLength : std::min(patternLength, m_);
patternList_.push_back(pattern);
}
k_ = patternList_.size();
// fill default value for SHIFT table
for (int i = 0; i < tableSize_; ++i) {
shiftTable_[i] = m_ - B_ + 1;
}
// fill HASH/PREFIX and SHIFT tables
for (size_t i = 0; i < k_; ++i) {
for (size_t j = m_; j >= B_; --j) {
unsigned int hashValue;
hashValue = patternList_[i][j - 1];
hashValue <<= HBITS_;
hashValue += patternList_[i][j - 1 - 1];
hashValue <<= HBITS_;
hashValue += patternList_[i][j - 2 - 1];
hashValue = fastmod(hashValue, tableSize_);
size_t shiftLength = m_ - j;
shiftTable_[hashValue] = std::min(shiftTable_[hashValue], shiftLength);
if (!shiftLength) {
PatternHash patternHashToAdd;
patternHashToAdd.idx = i;
// calculate this prefixHash to help us skip some patterns if there are collisions in hashPrefixTable_
patternHashToAdd.prefixHash = patternList_[i][0];
patternHashToAdd.prefixHash <<= HBITS_;
patternHashToAdd.prefixHash += patternList_[i][1];
hashPrefixTable_[hashValue].push_back(patternHashToAdd);
}
}
}
isShortPatternExist_ = (lengthOnePatterns_.size() > 0) || (lengthTwoPatterns_.size() > 0);
if (isShortPatternExist_) {
lengthOnePatternLookup_ = new int[alphabetSize_];
lengthTwoPatternLookup_ = new int*[alphabetSize_];
for (int i = 0; i < alphabetSize_; ++i) {
lengthOnePatternLookup_[i] = -1;
lengthTwoPatternLookup_[i] = new int[alphabetSize_];
for (int j = 0; j < alphabetSize_; ++j) {
lengthTwoPatternLookup_[i][j] = -1;
}
}
for (int i = 0; i < lengthOnePatterns_.size(); ++i) {
lengthOnePatternLookup_[(size_t)lengthOnePatterns_[i][0]] = i;
}
for (int i = 0; i < lengthTwoPatterns_.size(); ++i) {
lengthTwoPatternLookup_[(size_t)lengthTwoPatterns_[i][0]][(size_t)lengthTwoPatterns_[i][1]] = i;
}
}
isInitialized_ = true;
}
// onMatch takes 3 arguments: the matched pattern, the pattern's index in the pattern list, the start index of the match in text
void scan(const StringType &text, std::function<void(const StringType&, size_t, size_t)> onMatch) {
size_t textLength = text.size();
if (!isInitialized_ || textLength == 0) {
return;
}
if (isShortPatternExist_) {
int firstCharacterMatchIndex = lengthOnePatternLookup_[(size_t)text[0]];
if (firstCharacterMatchIndex > -1) {
onMatch(lengthOnePatterns_[firstCharacterMatchIndex], firstCharacterMatchIndex, 0);
}
const int PRE_WU_MANBER_LIMIT = std::min(m_ - 1, textLength);
for (int idx = 1; idx < PRE_WU_MANBER_LIMIT; ++idx) {
CharType preChar = text[idx - 1];
CharType curChar = text[idx];
checkShortPattern_(text, idx, onMatch);
}
}
size_t idx = m_ - 1;
while (idx < textLength) {
if (isShortPatternExist_) {
checkShortPattern_(text, idx, onMatch);
}
// hash value for HASH table
unsigned int hashValue;
hashValue = text[idx];
hashValue <<= HBITS_;
hashValue += text[idx - 1];
hashValue <<= HBITS_;
hashValue += text[idx - 2];
hashValue = fastmod(hashValue, tableSize_);
size_t shiftLength = shiftTable_[hashValue];
if (shiftLength == 0) {
// found a potential match, check values in HASH/PREDIX and will shift by 1 character
shiftLength = 1;
// hash value to match pattern
unsigned int prefixHash;
prefixHash = text[idx - m_ + 1];
prefixHash <<= HBITS_;
prefixHash += text[idx - m_ + 2];
for (const auto &potentialMatch : hashPrefixTable_[hashValue]) {
if (prefixHash == potentialMatch.prefixHash) {
bool isMatched = false;
const StringType &pattern = patternList_[potentialMatch.idx];
size_t idxInPattern = 0;
size_t idxInText = idx - m_ + 1;
size_t patternLength = pattern.size();
// prefix hash matched so we try to match character by character
while(idxInPattern < patternLength && idxInText < textLength && pattern[idxInPattern++] == text[idxInText++]);
// end of pattern reached => match found
if (idxInPattern == patternLength) {
onMatch(pattern, potentialMatch.idx, idx - m_ + 1);
}
}
}
}
if (isShortPatternExist_) {
++idx;
} else {
idx += shiftLength;
}
}
}
private:
// block size
// the paper says in practice, we use either B = 2 or B = 3
// we'll use 3
const size_t B_ = 3;
// min pattern size
size_t m_;
// number of patterns to be processed by Wu - Manber
size_t k_;
// number of bits to shift when hashing
// the paper says it use 5
unsigned short HBITS_;
// size of HASH and SHIFT tables
size_t tableSize_;
// SHIFT table
size_t* shiftTable_;
// store index in pattern list + prefix hash value for each pattern
struct PatternHash
{
unsigned int prefixHash;
size_t idx;
};
// HASH + PREFIX table
std::vector<PatternHash>* hashPrefixTable_;
// pattern list
std::vector<StringType> patternList_;
// handle length 1 and 2 patterns
bool isShortPatternExist_;
size_t alphabetSize_;
int* lengthOnePatternLookup_;
int** lengthTwoPatternLookup_;
std::vector<StringType> lengthOnePatterns_;
std::vector<StringType> lengthTwoPatterns_;
bool isInitialized_;
void checkShortPattern_(const StringType &text, size_t cur_idx, std::function<void(const StringType&, size_t, size_t)> onMatch) const {
int l1MatchIndex = lengthOnePatternLookup_[(size_t)text[cur_idx]];
if (l1MatchIndex > -1) {
onMatch(lengthOnePatterns_[l1MatchIndex], l1MatchIndex, cur_idx);
}
int l2MatchIndex = lengthTwoPatternLookup_[(size_t)text[cur_idx - 1]][(size_t)text[cur_idx]];
if (l2MatchIndex > -1) {
onMatch(lengthTwoPatterns_[l2MatchIndex], l2MatchIndex, cur_idx - 1);
}
}
};
} // namespace wu_manber
#endif // WU_MANBER_HPP
</code></pre>
<p>If the code is too long, I have pushed it to github if you find reading from there easier (<a href="https://github.com/bubiche/wu_manber/blob/master/wu_manber.hpp" rel="noreferrer">https://github.com/bubiche/wu_manber/blob/master/wu_manber.hpp</a>)</p>
<p>Thank you for your help!</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review and welcome back to C++! Here's my two cents:</p>\n\n<ul>\n<li><p>Use <code><cmath></code> instead of the deprecated <code><math.h></code>.</p></li>\n<li><p>Sort the <code>#include</code> directives according to alphabetical order.</p></li>\n<li><p>This is not true:</p>\n\n<blockquote>\n<pre><code>namespace { // anonymous namespace, things in here are \"private\" to wu_manber namespace\n</code></pre>\n</blockquote>\n\n<p>Everything inside this anonymous namespace is effectively placed in the enclosing namespace (with internal linkage), so <code>wu_manber::fastmod</code> becomes an ODR time bomb.</p></li>\n<li><p>Instead of trying to defeat the compiler with the <code>fastmod</code> function, just turn on the optimizations and let the compiler decide. The compiler can usually do better.</p></li>\n<li><p>Since you use <code>std::basic_string<CharType></code>, you should also have a <code>CharTraits</code> template parameter for user-defined character types to work.</p></li>\n<li><p><code>unsigned short</code> is not semantic.</p></li>\n<li><p>Instead of trying to manually handle memory management inside an otherwise irrelevant class and ending up with exception unsafe code (the first <code>new</code> is leaked if the second <code>new</code> throws), use standard facilities like <code>std::unique_ptr</code> or <code>std::vector</code> instead.</p></li>\n<li><p>Consistently use member initializer clauses in the constructor, rather than mixing them with assignments.</p></li>\n<li><p>Do not use <code>pow</code> for integer exponentiation. Use <code><<</code> instead. If you need readability, write a function: (with proper SFINAE treatment)</p>\n\n<pre><code>template <class T>\nconstexpr T power2(T n)\n{\n assert(n < static_cast<T>(std::numeric_limits<T>::digits));\n return 1 << n;\n}\n</code></pre></li>\n<li><p>In C++, a byte is not guaranteed to be 8 bits. The number of bits in a byte is <code>CHAR_BIT</code>.</p></li>\n<li><p>Use <code>std::size_t</code> indexes to traverse an array, not <code>int</code>.</p></li>\n<li><p>Use <code>static_cast</code> instead of C style casts.</p></li>\n<li><p>Do not use <code>std::function</code> if you do not want type erasure (which is expensive). Use a template parameter, call with <code>std::invoke</code>, and SFINAE with <code>std::is_invocable</code> instead.</p></li>\n<li><p>The functions are way too long. They should be separated into different functions. I am not familiar with the algorithm, but at least this should be in a separate function:</p>\n\n<pre><code>// hash value for HASH table\nunsigned int hashValue;\nhashValue = text[idx];\nhashValue <<= HBITS_;\nhashValue += text[idx - 1];\nhashValue <<= HBITS_;\nhashValue += text[idx - 2];\nhashValue = fastmod(hashValue, tableSize_);\n</code></pre></li>\n<li><p>It's <code>std::size_t</code>, not <code>size_t</code>, and you forgot to <code>#include <cstddef></code>.</p></li>\n<li><p><code>B_</code> can (and should) be <code>static constexpr</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T23:51:38.580",
"Id": "446697",
"Score": "0",
"body": "Thank you! I have much to learn to be able to write production level C++."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T12:47:55.600",
"Id": "229561",
"ParentId": "229541",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229561",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T22:56:07.427",
"Id": "229541",
"Score": "5",
"Tags": [
"c++",
"strings",
"c++11"
],
"Title": "Wu-Manber algorithm for multiple pattern matching in C++"
}
|
229541
|
<p>I had an application where I really wanted a double-ended queue that supports random access. Java's <code>ArrayDeque</code> would have been perfect, except that it doesn't expose random access into its backing array. So I went and implemented my own, which I named <code>RingBuffer</code>.</p>
<p>I'm looking for any constructive criticism about either the data structure implementation itself, or the test suite.</p>
<p>Implementation:</p>
<pre><code>import java.util.NoSuchElementException;
public class RingBuffer<T> {
private Object[] backingArray;
private int firstIdx = 0; // Index of the first elements
private int nextIdx = 0; // Index of the slot into which we would insert an element on addLast
// If nextIdx == (firstIdx - 1) % array_size, then insertion requires resizing the array.
// If nextIdx == firstIdx, then the buffer is empty.
public RingBuffer() {
backingArray = new Object[2];
}
synchronized private void doubleBackingArraySize() {
int newSize = backingArray.length * 2;
Object[] newArray = new Object[newSize];
int oldSize;
if (nextIdx < firstIdx) {
int numElementsToEndOfArray = backingArray.length - firstIdx;
System.arraycopy(backingArray, firstIdx, newArray, 0, numElementsToEndOfArray);
System.arraycopy(backingArray, 0, newArray, numElementsToEndOfArray, nextIdx);
oldSize = numElementsToEndOfArray + nextIdx;
} else {
// This will happen if firstIdx == 0
System.arraycopy(backingArray, firstIdx, newArray, 0, nextIdx - firstIdx);
oldSize = nextIdx - firstIdx;
}
backingArray = newArray;
// Update our indices into that array.
firstIdx = 0;
nextIdx = oldSize;
}
/**
* Returns the number of elements that the array backing this can hold.
* This is NOT necessarily the number of elements presently in the buffer.
* Useful for testing that the implementation works correctly, and for figuring out if an add{First, Last} will
* cause a re-allocation.
*/
public int capacity() {
return backingArray.length - 1;
}
/**
* The number of elements currently held in the buffer.
*/
public int size() {
if (firstIdx <= nextIdx) {
return nextIdx - firstIdx;
} else {
return (backingArray.length - firstIdx + nextIdx);
}
}
public void addLast(T x) {
if ((nextIdx + 1) % backingArray.length == firstIdx) {
doubleBackingArraySize();
}
backingArray[nextIdx] = x;
nextIdx +=1;
nextIdx %= backingArray.length;
}
public void addFirst(T x) {
if ((nextIdx + 1) % backingArray.length == firstIdx) {
doubleBackingArraySize();
}
firstIdx -= 1;
// Note: in Java -1 % n == -1
if (firstIdx < 0) {
firstIdx += backingArray.length;
}
backingArray[firstIdx] = x;
}
public void removeFirst() {
if (size() == 0) {
throw new NoSuchElementException();
} else {
firstIdx += 1;
firstIdx %= backingArray.length;
}
}
public void removeLast() {
if (size() == 0) {
throw new NoSuchElementException();
} else {
nextIdx -= 1;
if (nextIdx < 0) {
nextIdx += backingArray.length;
}
}
}
public T getFromFirst(int i) {
if (i < 0 || i >= size()) {
throw new NoSuchElementException();
} else {
//noinspection unchecked
return (T)backingArray[(firstIdx + i) % backingArray.length];
}
}
public T getFromLast(int i) {
if (i < 0 || i >= size()) {
throw new NoSuchElementException();
} else {
int idx = nextIdx - 1 - i;
if (idx < 0) {
idx += backingArray.length;
}
//noinspection unchecked
return (T)backingArray[idx];
}
}
}
</code></pre>
<p>Tests:</p>
<pre><code>import org.junit.Assert;
import org.junit.Test;
import java.util.NoSuchElementException;
public class RingBufferTests {
@Test
public void populateAndRandomAccess() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addLast(5); // [5]
buffer.addLast(6); // [5, 6]
buffer.addLast(7); // [5, 6, 7]
Assert.assertEquals(5, (int)buffer.getFromFirst(0));
Assert.assertEquals(6, (int)buffer.getFromFirst(1));
Assert.assertEquals(7, (int)buffer.getFromFirst(2));
}
@Test
public void populateAndRandomAccessFromLast() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addLast(5); // [5];
buffer.addLast(6); // [5, 6]
buffer.addLast(7); // [5, 6, 7]
Assert.assertEquals(7, (int)buffer.getFromLast(0));
Assert.assertEquals(6, (int)buffer.getFromLast(1));
Assert.assertEquals(5, (int)buffer.getFromLast(2));
}
@Test
public void populateFromFirst() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addFirst(5); // [5]
buffer.addFirst(6); // [6, 5]
buffer.addFirst(7); // [7, 6, 5]
Assert.assertEquals(5, (int)buffer.getFromLast(0));
Assert.assertEquals(6, (int)buffer.getFromLast(1));
Assert.assertEquals(7, (int)buffer.getFromLast(2));
Assert.assertEquals(7, (int)buffer.getFromFirst(0));
Assert.assertEquals(6, (int)buffer.getFromFirst(1));
Assert.assertEquals(5, (int)buffer.getFromFirst(2));
}
@Test
public void populateFromBothEnds() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addFirst(6); // [6]
buffer.addFirst(5); // [5, 6]
buffer.addLast(7); // [5, 6, 7]
buffer.addLast(8); // [5, 6, 7, 8]
Assert.assertEquals(8, (int)buffer.getFromLast(0));
Assert.assertEquals(7, (int)buffer.getFromLast(1));
Assert.assertEquals(6, (int)buffer.getFromLast(2));
Assert.assertEquals(5, (int)buffer.getFromLast(3));
Assert.assertEquals(5, (int)buffer.getFromFirst(0));
Assert.assertEquals(6, (int)buffer.getFromFirst(1));
Assert.assertEquals(7, (int)buffer.getFromFirst(2));
Assert.assertEquals(8, (int)buffer.getFromFirst(3));
}
@Test
public void outOfBoundsAccessThrows() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addLast(5); // [5]
buffer.addLast(6); // [5, 6]
buffer.addLast(7); // [5, 6, 7]
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromFirst(3));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromFirst(4));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromFirst(5));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromLast(3));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromLast(4));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromLast(5));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromFirst(-1));
Assert.assertThrows(NoSuchElementException.class, () -> buffer.getFromLast(-1));
}
@Test
public void removingWhenEmptyThrows() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addLast(5); // [5]
buffer.addLast(6); // [5, 6]
buffer.addLast(7); // [5, 6, 7]
buffer.removeFirst();
buffer.removeFirst();
buffer.removeFirst();
Assert.assertThrows(NoSuchElementException.class, buffer::removeFirst);
Assert.assertThrows(NoSuchElementException.class, buffer::removeLast);
}
@Test
public void populateAndRemove() {
RingBuffer<Integer> buffer = new RingBuffer<>();
buffer.addLast(5); // [5]
buffer.addLast(6); // [5, 6]
buffer.addLast(7); // [5, 6, 7]
buffer.removeFirst(); // Should remove the 5
Assert.assertEquals(6, (int)buffer.getFromFirst(0));
Assert.assertEquals(7, (int)buffer.getFromFirst(1));
Assert.assertEquals(6, (int)buffer.getFromLast(1));
Assert.assertEquals(7, (int)buffer.getFromLast(0));
}
@Test
public void populateAndRemoveManyTimes() {
RingBuffer<Integer> buffer = new RingBuffer<>();
// This should result in the buffer always containing between 3 and 5 elements.
buffer.addLast(-1);
buffer.addLast(-1);
buffer.addLast(-1);
for (int i=0; i < 100; i+=2) {
buffer.addLast(i);
buffer.addLast(i+1);
buffer.removeFirst();
buffer.removeFirst();
}
// Check that the buffer has only 3 elements
Assert.assertEquals(3, buffer.size());
// Check that these elements are [97, 98, 99]
Assert.assertEquals(97, (int)buffer.getFromFirst(0));
Assert.assertEquals(98, (int)buffer.getFromFirst(1));
Assert.assertEquals(99, (int)buffer.getFromFirst(2));
// Check that the buffer has not grown in capacity to some absurd size
// Will use 8 since my implementation will probably grow by doubling the backing array size.
Assert.assertTrue(buffer.capacity() <= 8);
}
}
</code></pre>
<p>By the way, I <em>know</em> this never shrinks the backing array, even if the number of elements in the <code>RingBuffer</code> drops well below the capacity. I don't consider this to be an issue for my application.</p>
|
[] |
[
{
"body": "<h3>Observations</h3>\n\n<ul>\n<li>The class is not thread-safe, so why is method <code>doubleBackingArraySize</code> synchronized?</li>\n<li>All methods perform some sort of redundancy in circular incrementation and decrementation. This kind of arithmetic could be placed in 2 separate methods, which you would then call in the other methods to have more DRY code.</li>\n<li>Deciding when to allocate more space is a repeating code block that could be placed into a helper method.</li>\n<li>You present a great set of unit tests.</li>\n</ul>\n\n<hr>\n\n<h3>Circular arithmetic</h3>\n\n<p>These could be the reusable helpers methods. Naming conventions conform Java's implementation of <a href=\"http://fuseyism.com/classpath/doc/java/util/concurrent/ArrayBlockingQueue-source.html\" rel=\"nofollow noreferrer\">ArrayBlockingQueue</a>.</p>\n\n<pre><code>final int inc(int i) {\n return ++i % items.length;\n}\n\nfinal int dec(int i) {\n return (--i + items.length) % items.length;\n}\n</code></pre>\n\n<hr>\n\n<h3>DRY</h3>\n\n<p>Put the following recurring code into a helper:</p>\n\n<blockquote>\n<pre><code>if ((nextIdx + 1) % backingArray.length == firstIdx) {\n doubleBackingArraySize();\n}\n</code></pre>\n</blockquote>\n\n<pre><code>final void CheckArrayCapacity() {\n if ((nextIdx + 1) % backingArray.length == firstIdx) {\n doubleBackingArraySize();\n }\n}\n</code></pre>\n\n<hr>\n\n<h3>Refactoring Code</h3>\n\n<p>For instance, <code>addFirst</code> could be written as:</p>\n\n<pre><code>public void addFirst(T x) {\n CheckArrayCapacity();\n firstIdx = dec(firstIdx);\n backingArray[firstIdx] = x;\n}\n</code></pre>\n\n<p>instead of:</p>\n\n<blockquote>\n<pre><code>public void addFirst(T x) {\n if ((nextIdx + 1) % backingArray.length == firstIdx) {\n doubleBackingArraySize();\n }\n\n firstIdx -= 1;\n // Note: in Java -1 % n == -1\n if (firstIdx < 0) {\n firstIdx += backingArray.length;\n }\n backingArray[firstIdx] = x;\n}\n</code></pre>\n</blockquote>\n\n<p>All other methods could be written in a succinct way as above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:32:57.357",
"Id": "446572",
"Score": "1",
"body": "Great, those refactorings are much cleaner.\n\nAdding `synchronized` was just a bad habit - I thought \"Oh, I'm modifying the backing array, better not have two threads trying to do this at once!\". But there's so many other places that this isn't thread-safe that it was just misleading. I've removed it now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T04:40:55.900",
"Id": "229551",
"ParentId": "229542",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T23:22:01.253",
"Id": "229542",
"Score": "3",
"Tags": [
"java",
"array",
"reinventing-the-wheel",
"library",
"circular-list"
],
"Title": "Ring buffer with random access"
}
|
229542
|
<p>I'm taking an online course in website development and we're going over JavaScript ES6, but my professors lecture and notes I've taken we're not very helpful more resourceful with the assignment I was given.
Using proper ES6 methods, I was asked to create a class for Vehicles and two Subclasses for a bus that inclues the number of seats and Ambulance thatinclues a ttoggle for siren (on & off). Then to create an HTML file of those subclasses that allow me to drive them around using methods. Here what I have so far:</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>//properties
class Vehicle {
constructor(color, direction, currentSpeed, topSpeed) {
this._color = color; //string
this._direction = direction; //integer 0-359 (representing a compass)
this._currentSpeed = currentSpeed; //integer
this._topSpeed = topSpeed; // integer
this._engineStarted = true; //boolean
}
//Methods:
turnOn() {
this._engineStarted = true;
}
statusOn(){
if(this._engineStarted){
const statusOn = `${this._color}, ${this._direction}, ${this._currentSpeed}, ${this.topSpeed}`;
return statusOn;
} else {
const status = "Engine has not been started! Vehicle is idle and inactive. Please activate";
return status;
}
}
///////////////////////////////
turnOff() {
this._engineStarted = false;
const status = "The Engine is now disengaged and vehicle is inactive."
}
///////////////////////////////
accelerate(){
if(this._engineStarted = true){
} else {
const status = "Engine has not been started! Vehicle is idle and inactive. Please activate";
return status;
}
}
///////////////////////////////
brake(){
if(this._engineStarted = true){
} else {
const status = "Engine has not been started! Vehicle is idle and inactive. Please activate";
return status;
}
}
///////////////////////////////
turnLeft(){
if (this._engineStarted = true) {
} else {
const status = "Engine has not been started! Vehicle is idle and inactive. Please activate";
return status;
}
}
///////////////////////////////
turnRight(){
if (this._engineStarted = true) {
} else {
const status = "Engine has not been started! Vehicle is idle and inactive. Please activate";
return status;
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><DOCTYPE html/>
<html>
<head>
<title>Vehicles</title>
</head>
<body>
<script src="Johnson_ES6_Classes.js"></script>
<script>
let vehicle = new Vehicle()
let bus = new Bus()
let ambulance = new Abulance()
alert(vehicle.status());
alert(bus.status());
alert(ambulance.status());
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T08:31:25.360",
"Id": "446534",
"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 the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:38:29.813",
"Id": "446584",
"Score": "0",
"body": "Also, your code doesn't work. The function `status()` doesn't exist."
}
] |
[
{
"body": "<p>This is okay for as a start. However you are missing the two classes Bus and Ambulance.</p>\n\n<p>Few comments:</p>\n\n<p>(1) You are using this._variableName pattern - although not wrong this is a bit redundant way to express yourself. Historically <code>_variableName</code> or m_variableName comes from C++ to indicate member variables. However, <code>this.variableName</code> already means that this is a member variable hence the \"_\" is redundant.</p>\n\n<p>(2) The key to good design is consistency. Therefore it would make sense if all of your methods return status string or none but the status() method. Choose and stay consistent. Your current methods are all over the place.</p>\n\n<p>(3) You are missing implementation on few of the methods like accelerate(), turnLeft() and turnRight(); </p>\n\n<p>Implement those changes and let's resume the code review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T03:46:40.127",
"Id": "446520",
"Score": "2",
"body": "Please do not answer off-topic questions, such as this one where the code is not yet working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:37:11.570",
"Id": "446560",
"Score": "0",
"body": "@200_success Wade is obviously making his first steps and one should have proper expectation - if this is a code review the feedback can be given at any time. I see no harm in that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:21:19.113",
"Id": "446579",
"Score": "1",
"body": "The same can be said of thousands of other people who have posted unfinished homework assignments on this site. [It hurts the community in the long run.](https://codereview.meta.stackexchange.com/a/6389/9357)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:29:06.877",
"Id": "446604",
"Score": "0",
"body": "@Deian - Thank you for your help and understanding. I greatly appreciate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:09:34.350",
"Id": "446664",
"Score": "0",
"body": "@200_success I might agree with https://codereview.meta.stackexchange.com/a/6389/9357 however this is simply uncompleted work by someone who need a push in the right direction."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T02:20:43.430",
"Id": "229546",
"ParentId": "229545",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229546",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T01:35:03.793",
"Id": "229545",
"Score": "-2",
"Tags": [
"javascript",
"html",
"ecmascript-6"
],
"Title": "I was given an assignment on writing a javascript ES6 program for vehicles. Am I writing this correctly? Any advice or tip?"
}
|
229545
|
<p>Stumbled upon this interview question:</p>
<blockquote>
<p>Given a morse encoded sentence with no spaces or separation between letters or words and a list of words contained in the message, decode it. </p>
</blockquote>
<p>This was my solution (and a test case with the jack and jill sentence):</p>
<pre><code> static String[] alpha = {"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"};
static String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."};
private static HashMap<Character, String> letters = new HashMap<>();
public static void main(String[] args) {
for (int i = 0; i < alpha.length; i++) {
letters.put(alpha[i].charAt(0), morse[i]);
}
String[] words = {"hill","jack","went","and","jill","the","up"};
System.out.println(
decode(".---.--.-.-.-.--.-...---...-...-...--.-.-..-.--.-............-...-..",
words)
);
}
private static String decode(String code, String[] words){
String[] encodedWords = new String[words.length];
for (int i = 0; i < words.length; i++) {
encodedWords[i] = encodeWord(words[i]);
}
return decodePossibility(code, words, encodedWords, new StringBuilder());
}
private static String decodePossibility(String code, String[] words, String[] encodedWords, StringBuilder current){
if(code.length() == 0) return current.toString();
for (int i = 0; i < encodedWords.length; i++) {
if(code.length() >= encodedWords[i].length()){
if(code.substring(0, encodedWords[i].length()).equals(encodedWords[i])){
String result = decodePossibility(code.substring(encodedWords[i].length()), words, encodedWords, current.append(words[i]).append(' '));
if(result != null){
return result;
}
}
}
}
return null;
}
private static String encodeWord(String word){
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
stringBuilder.append(letters.get(word.charAt(i)));
}
return stringBuilder.toString();
}
</code></pre>
<p>Any tips on how to improve the code? Any alternative solution?
To back track to a correct solution I would prefer throwing an exception, but sadly I'am not allowed to do so. </p>
|
[] |
[
{
"body": "<h2>White Space</h2>\n\n<p>This is hard on my aging eyes:</p>\n\n<pre><code>static String[] morse = {\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\n \".--\",\"-..-\",\"-.--\",\"--..\"};\n</code></pre>\n\n<p>This is much easier to read:</p>\n\n<pre><code>static String[] morse = {\n \".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\",\n \"-.-\", \".-..\", \"--\", \"-.\", \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\",\n \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"\n};\n</code></pre>\n\n<h2><code>alpha[i].charAt(0)</code></h2>\n\n<p>In the following, you use create 26 strings, and call <code>.charAt(0)</code> on each:</p>\n\n<pre><code>static String[] alpha = {\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\n \"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\n \"w\",\"x\",\"y\",\"z\"};\nstatic String[] morse = {\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\n \".--\",\"-..-\",\"-.--\",\"--..\"};\n\nprivate static HashMap<Character, String> letters = new HashMap<>();\n\npublic static void main(String[] args) {\n for (int i = 0; i < alpha.length; i++) {\n letters.put(alpha[i].charAt(0), morse[i]);\n }\n</code></pre>\n\n<p>You could simply use one 26-character string:</p>\n\n<pre><code>final static String alpha = \"abcdefghijklmnopqrstuvwxyz\";\n\n...\n\nfor (int i = 0; i < alpha.length(); i++) {\n letters.put(alpha.charAt(i), morse[i]);\n}\n</code></pre>\n\n<p>Or you could statically initialize the structure directly:</p>\n\n<pre><code>Map<Character, String> letters = Map.of(\n 'a', \".-\", 'b', \"-...\", 'c', \"-.-.\", 'd', \"-..\", 'e', \".\",\n 'f', \"..-.\", 'g', \"--.\", 'h', \"....\", 'i', \"..\", 'j', \".---\",\n ... etc ...);\n</code></pre>\n\n<h2><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html\" rel=\"nofollow noreferrer\">Stream API</a></h2>\n\n<p>The following code:</p>\n\n<pre><code>private static String encodeWord(String word){\n StringBuilder stringBuilder = new StringBuilder();\n for (int i = 0; i < word.length(); i++) {\n stringBuilder.append(letters.get(word.charAt(i)));\n }\n return stringBuilder.toString();\n}\n</code></pre>\n\n<p>is pretty straight forward. It could be reduced to 1 line of code with the Stream API, if you are familiar with it:</p>\n\n<pre><code>private static String encodeWord(String word){\n return word.chars().mapToObj(i -> letters.get((char) i).collect(Collectors.joining());\n}\n</code></pre>\n\n<h2>Words & Encoded Words</h2>\n\n<p>Right now, you are allocating a parallel array for <code>encodedWords</code>, and matching words and encoded words by index. You could merge these two structures into one object, a <code>Map<String, String></code> where encoded words map to their decoded values. Passing this object to <code>decodePossibility</code> would be more cohesive than two arrays, which could be of different length.</p>\n\n<h2>Efficiency</h2>\n\n<p>Continuing with the <code>Map<String, String></code> of decodings...</p>\n\n<p>In <code>decodePossibility</code>, you are looping over all <code>encodedWords</code> trying each one to see if it is the next possibility in the message. With 7 words, this isn't too inefficient, but if the list of words was larger, it could be.</p>\n\n<p>Instead, you could find the length of the shortest encoded word, and develop a <code>Map</code> of lists of words starting with a prefixes of that length:</p>\n\n<pre><code>Map<String, Map<String, String>> partitioned_decoding;\n</code></pre>\n\n<p>For instance, the encoding of \"the\" produces the shortest sequence <code>-.....</code> of 6 characters, so in <code>partition_decoding</code> each key would be the first 6 characters of <code>encodedWords</code>, and each value would contain a mapping of <code>encodedWords</code> to <code>words</code> for only the <code>encodedWords</code> starting with that key.</p>\n\n<pre><code>\"-.....\" -> Map.of(\"-.....\", \"the\")\n\".---.-\" -> Map.of(\".---.--.-.-.-\", \"jack\")\n\".---..\" -> Map.of(\".---...-...-..\", \"jill\")\n\".--.-.\" -> Map.of(\".--.-.-\", \"went\", \".--.-..\", \"and\")\n\"..-.--\" -> Map.of(\"..-.--.\", \"up\")\n\"......\" -> Map.of(\".......-...-..\", \"hill\")\n</code></pre>\n\n<p>During <code>decodePossibility</code>, if <code>code</code> was at least 6 characters long, you would fetch the first 6 characters of <code>code</code>, look up that entry in <code>partitioned_decoding</code>, and if present, loop over that (ideally only 1) entry in that submap. In the case of <code>\".--.-.\"</code>, you'd have to try both <code>\"went\"</code> and <code>\"and\"</code>, but that is only 2 words, which is still much smaller than examining all 7.</p>\n\n<p>Neither <code>\"e\"</code> or <code>\"t\"</code> are valid single letter words, so the worst case would be if <code>words</code> contained the word <code>\"a\"</code>, which would cause the key length to reduce to 2 characters, and <code>words</code> would be partitioned into 4 different bins: <code>\"--\"</code>, <code>\".-\"</code>, <code>\"-.\"</code>, and <code>\"..\"</code>, which should still provide a 4 times speed-up, since only one quarter of entries would be checked at each stage.</p>\n\n<h2>Alternative to Recursion</h2>\n\n<p>Instead of recursion, you could use a loop, and allocate your own stacks for current position and word iteration for each level. When a solution is found, the <code>return</code> statement would directly return the solution - no need to check for a sub-step returning non-null and returning that value, eventually unwinding the call-stack to the top. When a dead-end is found, you pop the previous state from your own stacks, and continue looping until a solution is found or no solution is possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:55:16.180",
"Id": "229589",
"ParentId": "229547",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229589",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T02:37:54.200",
"Id": "229547",
"Score": "5",
"Tags": [
"java",
"interview-questions",
"morse-code"
],
"Title": "Decode ambiguous Morse code"
}
|
229547
|
<p>This is my first game and I'm really proud of it, but I think it's horribly messy. Is there any way to improve it?</p>
<pre><code>#HANGMAN
# Valid Word Checker
def valid_word(word):
ill_chars = ["!","@","#","$","%","^","&","*","(",")",",",".", " ","1","2","3","4","5","6","7","8","9","0"]
for i in word:
if i in ill_chars:
print(f"\nError: It must be a letter. No symbols, numbers or spaces allowed. \n\n '{i}' is not allowed\n")
return False
if len(word) > 12:
print("\n\nError: Word is too long. Use a word with eight characters or less.")
return False
return True
word_list = []
spaces = []
guessed_letters = []
ill_chars = ["!","@","#","$","%","^","&","*","(",")",",",".", " ","1","2","3","4","5","6","7","8","9","0"]
head =" O"
armL = " /"
torso = "|"
armR = "\\"
legL = "/"
legR = " \\"
hangman_parts = [head, armL, torso, armR, legL, legR]
hangman_progress = ["",
"|",
"\n|",
"\n|"]
hangman_final = ["|~~~~|\n"]
# Check if word is valid
wordisValid = False
while True:
word = input("\n\n\nChoose any word\n\n\n").lower()
if valid_word(word) == True:
wordisValid = True
break
else:
continue
# Add to list
for i in word:
word_list.append(i)
spaces.append("_ ")
# Main Game Loop
bad_letter = 0
while wordisValid == True:
print("".join(hangman_final))
print("\n\n\n\n")
print("".join(spaces))
print("\n\nThe word has: " + str(len(word)) + " letters.")
print("\nYou've tried the following letters: " + "\n\n" + "".join(guessed_letters) + "\n\n")
# Winning Loop
if "".join(spaces) == word:
print(f"YOU WIN! The word was: {word}")
break
# Choose Letters
player_guess = input("\n\nPlease choose a letter: \n\n\n\n").lower()
guessed_letters.append(" " + player_guess)
if player_guess in ill_chars:
print(f"\nError: It must be a letter. No symbols, numbers or spaces allowed. \n\n '{player_guess}' is not allowed\n")
elif len(player_guess) > 1:
print("\nError: You must use one letter.\n")
elif player_guess == "":
print("\nError: No input provided.\n")
# Wrong Letter
elif player_guess not in word_list:
bad_letter += 1
if bad_letter == 1:
hangman_final.append(hangman_progress[1] + head)
elif bad_letter == 2:
hangman_final.append(hangman_progress[2] + " " + torso)
elif bad_letter == 3:
hangman_final.pop(2)
hangman_final.append(hangman_progress[2] + armL + torso)
elif bad_letter == 4:
hangman_final.pop(2)
hangman_final.append(hangman_progress[2] + armL + torso + armR)
elif bad_letter == 5:
hangman_final.append(hangman_progress[3] + " " + legL)
elif bad_letter == 6:
hangman_final.pop(3)
hangman_final.append(hangman_progress[3] + " " + legL + legR)
print("\n\nThe word was: " + word)
print("\n\n\n\n\n\n\n" + "".join(hangman_final))
print(" YOU GOT HUNG ")
break
print("".join(hangman_final))
print("\n\n\n\n")
print("".join(spaces))
print("\n\nThe word has: " + str(len(word)) + " letters.")
print("\nYou've tried the following letters: " + "\n\n" + "".join(guessed_letters) + "\n\n")
print(f"\n\n\n{player_guess} is not in the word. Try again.\n\n")
# END GAME
if bad_letter == 6:
break
# Add letters guessed to a list
counter = 0
for i in word:
if player_guess == i:
spaces[counter] = player_guess
counter += 1
</code></pre>
<p>Even though it's working, I'm not sure that I have the right idea when it comes to making this type of project.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T10:03:45.153",
"Id": "446542",
"Score": "2",
"body": "Welcome to Code Review! You can take the [tour] for a quick overview of the site."
}
] |
[
{
"body": "<p>While it's clear that you're new to python, it's still pretty good that you got it to run first time. Good job!</p>\n\n<h3>Input Validation</h3>\n\n<p>Currently, you have a list of forbidden characters. While that can work, by default python allows unicode input. That means there's literally thousands of letters someone can input. I suggest instead using a whitelist of valid inputs. Like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>VALID_LETTERS = \"abcdefghijklmnopqrstuvwxyz\" # This won't ever change, and typically this sort\n# of things is a module-level variable. \n\ndef valid_word(word):\n for letter in word:\n if letter not in VALID_LETTERS:\n print(f\"Letter {letter} is not a valid letter. Please use just a-z.\")\n return\n if len(word) > 8: # This was 12 in your script. Little mistake? And you might want a \n # module-level constant for this as well.\n print(\"\\n\\nError: Word is too long. Use a word with eight characters or less.\")\n return False\n return True\n</code></pre>\n\n<h3>main() and game()</h3>\n\n<p>Generally, in python we never execute code at the moment the module is loaded. <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Read here for details</a>, and how we guard against it. I'll come back to this later. For now, it means we should put as much as possible into functions - lets call them main() and game().</p>\n\n<p>main() will be the main menu function. Since we don't have a true menu, this will basically start a game, and perhaps ask if the player wants to play again. </p>\n\n<p>game() will be a function that lets us play a single game. Most of this will be a loop that gets player input and calculates the game state. Basically everything in your script that isn't another function should be in the game() function. </p>\n\n<p>I'll cut some variables we don't need later on. I'll explain them when we get to where we use them.</p>\n\n<p>Like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def game():\n # Variable naming is important. This is an example of a good name.\n guessed_letters = []\n\n # ill_chars = [...] We already have this variable before here!\n\n # Lets assign the parts directly. We can index them as in \"3rd part\".\n # And for ourselves, we comment the meaning to make sure we still know what it means a year \n # from now.\n hangman_parts = [\n \" O\", # Head\n \" /\", # Left Arm\n \"|\" , # Torse\n \"\\\\\", # Right Arm\n \"/\", # Left Leg\n \" \\\\\" # Right Leg\n ]\n hangman_progress = [\"\", \n \"|\", \n \"\\n|\", \n \"\\n|\"]\n\n hangman_final = [\"|~~~~|\\n\"]\n\n # Check if word is valid\n\n # Naming: should be word_is_valid, to be consistent with your other variables.\n word_is_valid = False\n while not word_is_valid:\n word = input(\"\\n\\n\\nChoose any word\\n\\n\\n\").lower()\n word_is_valid = valid_word(word)\n # With this loop condition, it'll keep asking until valid_word returns True. So we can just \n # assign that value to word_is_valid directly.\n\n # Since this is the word we're trying to guess, lets just push it upwards in\n # the console a lot, so we won't see it all the time:\n print(\"\\n\" * 100) # Prints 100 newlines.\n\n # We don't need word_list, just word will do. We don't need spaces either.\n while True: # Main game loop. We don't need to check for anything, we'll just use break or\n # return to get out.\n</code></pre>\n\n<p>Now we're going to use a list comprehension. It's almost the same as a generator expression, but it gives us a true list, so we can ask python how long it is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> # Calculate how many bad letters we have with a list comprehension:\n bad_letter = len([letter for letter in guessed_letters if letter not in word])\n draw_hangman(bad_letter)\n if bad_letter > 5:\n print(\"\\n\\n\\n\\nYOU GOT HUNG\")\n return\n print(\"\\n\\n\\n\\n\")\n</code></pre>\n\n<p>You used to draw your hangman at two different places, while it's more practical to do it in one place. It also ensures that if you want to change something, you'll only have to change it once.</p>\n\n<p>I've also changed how to draw it. It's much more useful to have a function for this drawing operation, and have it calculate how to draw from the number of bad letters so far. This makes the drawing independent of the current game state. Here's the version I came up with, based on your modifications of <code>hangman_final</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def draw_hangman(bad_letter):\n print(hangman_final, end=\"\")\n if bad_letter > 0: # Head\n print(hangman_progress[1] + hangman_parts[0], end=\"\")\n if bad_letter == 2: # Torso and arms\n print(hangman_progress[2] + \" \" + hangman_parts[2], end=\"\")\n elif bad_letter == 3:\n print(hangman_progress[2] + \"\".join(hangman_parts[1:3]), end=\"\")\n elif bad_letter > 3:\n print(hangman_progress[2] + \"\".join(hangman_parts[1:4]), end=\"\")\n if bad_letter > 4: # Legs\n print(hangman_progress[3] + \" \" + hangman_parts[4], end=\"\")\n if bad_letter > 5:\n print(hangman_parts[5], end=\"\")\n</code></pre>\n\n<p>Here we need to print the letters we guessed, and underscores otherwise. We can calculate and print it in one line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> print(\" \".join(letter for letter in word if letter in guessed_letters else \"_\"))\n</code></pre>\n\n<p>For every letter, this will print it if it's contained in guessed_letters, and otherwise print an underscore. This is a <a href=\"https://docs.python.org/3/reference/expressions.html?highlight=generator#generator-expressions\" rel=\"noreferrer\">generator expression</a>. This one is almost equal to the function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def make_word(word, guessed_letters):\n result = []\n for letter in word:\n if letter in guessed_letters:\n result.append(letter)\n else:\n result.append(\"_\")\n return result\n</code></pre>\n\n<p>I say almost, because it's not exactly a list that comes out of it, even if it acts the same if you use it in a for loop or feed it to a function that does, like \"\".join(). It also acts more like a loop than a function, but that's not really important right now.</p>\n\n<p>We feed the result to the join. And note that we feed it to \" \".join(), with a space in between, which will put a space between every letter like you did before.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> print(f\"\\n\\nThe word has: {len(word)} letters.\") # f-strings are shorter, and easy to use. \n print(f\"\\nYou've tried the following letters:\\n\\n{''.join(guessed_letters) }\\n\\n\")\n # For a string literal inside an f-string, use the other type of quotes\n\n # This is another generator expression - this one returns a not-quite-list of booleans, and\n # the all() builtin function returns True if and only if all results of the generator\n # expression are True.\n if all(letter in guessed_letters for letter in word):\n print(f\"You WIN!\\nThe word was: {word}\")\n return\n\n input_valid = False\n while not input_valid:\n new_letter = input(\"\\n\\nPlease choose a letter: \\n\\n\\n\\n\").lower()\n # VERY GOOD that you lowercase it! Prevents tons of weird behaviour.\n if len(new_letter) > 1:\n print(\"Please enter a single letter only.\")\n elif new_letter not in VALID_LETTERS:\n print(f\"{new_letter} is not a valid letter. Please enter a letter a-z\")\n elif not new_letter: # Empty strings evaluate to False\n print(\"Please enter a letter before pressing enter.\")\n elif new_letter in guessed_letters:\n print(\"You already guessed {new_letter} before!\")\n else:\n guessed_letters.append(new_letter):\n input_valid = True\n\n</code></pre>\n\n<p>This is pretty close to your input. But I put it in a loop, so if we have an invalid input, we don't have to traverse the entire game loop again. I use a pretty simple signalling boolean to keep it going, but perhaps there's more elegant ways to do this. Never <em>wrong</em> to keep it simple, though.</p>\n\n<p>Right now, to play the game, all you have to do is call the <code>game()</code> function. But perhaps we want to play multiple games in series? Lets make our <code>main()</code> function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n game()\n while \"y\" in input(\"Play again? [Y/n]\").lower():\n game()\n</code></pre>\n\n<p>Why is this in a separate function? Again, for the sake of extensiblility. Perhaps, we want to import our game from another module. If so, we don't want it to run when we import, but when we call a function. So we end the script with this <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">guard</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>If we execute this file directly, this will run our main() function and let us play the game. But if we import it, it won't, so we can call the function when we want it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T11:30:15.743",
"Id": "446548",
"Score": "4",
"body": "Instead of defining `VALID_LETTERS` manually: `from string import ascii_lowercase as VALID_LETTERS`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T11:33:05.547",
"Id": "446549",
"Score": "0",
"body": "Would work just as well, but personally I wouldn't import for something like this. Unless you need localization for countries with different alphabets, but in that case you'd need to go a lot more complicated than that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T12:58:47.473",
"Id": "446558",
"Score": "0",
"body": "If the whitelist is just lower case letters, one can also check the entire input string using `word.islower() and word.isascii()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:14:30.933",
"Id": "446559",
"Score": "1",
"body": "Using both, you mean? Yeah, it could work, but I don't think the current is a bad solution. I wanted to keep it someone similar to the question, and I also reused it to check the letters again. And if it was performance limited, I'd use `ord()` and check it's value instead. However, This is both readable and generalizable while not being slow or an antipattern. So that's why I think this is the better way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:59:47.783",
"Id": "446643",
"Score": "0",
"body": "Thank you so much for your amazing detailed explanation!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T06:36:40.330",
"Id": "446735",
"Score": "0",
"body": "Happy to help. I still easily remember when I started out, and I wish I'd have gone here back then."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T07:59:34.743",
"Id": "229556",
"ParentId": "229552",
"Score": "16"
}
}
] |
{
"AcceptedAnswerId": "229556",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T06:08:29.177",
"Id": "229552",
"Score": "10",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"hangman"
],
"Title": "My first Hangman game in Python"
}
|
229552
|
<p>I'm working on a program that creates a file for a specific embosser machine (machine that creates plastic bank card for example). I have 3 embosser machines and all of them create different files. Every file contains a card number, last and first name, address, etc. The difference between the files is that they contain specific characters for the delimiter.</p>
<p>I want to implement this project with a factory pattern.</p>
<p>For simplicity sake, let's say that I have these embossers: <code>DataCard</code>, <code>CIM</code> and <code>DataCard2</code>.</p>
<p>This is how I created the files in my project, and I'd like to know if this is a good way of doing it.</p>
<pre><code>public enum eEmbosserType
{
Datacard,
Cim,
Datacard2
}
public interface IEmbosser
{
eEmbosserType EmbosserType { get; }
List<EmbosserData> Data { get; set; }
void CreateFileForEmbosser(string path);
void PrepareDataForEmboser();
}
public class DataCardEmbosser : Emboser.IEmbosser
{
public eEmbosserType EmbosserType => eEmbosserType.Datacard;
public List<EmbosserData> Data { get ; set; }
public void CreateFileForEmbosser(string path)
{
using (StreamWriter sw = new StreamWriter(path))
{
foreach (DataCard item in Data)
{
sw.Write(item.cardNumber + "_!");
sw.Write(item.city + "_?");
sw.Write(item.name + "_^");
sw.Write(item.expDate + "_:");
}
}
}
public void PrepareDataForEmboser()
{
Data = new List<EmbosserData>();
List<CardData> cards = GetCardData();
foreach (CardData card in cards)
{
DataCard dc = new DataCard();
dc.cardNumber = card.PAN;
dc.city = card.City;
dc.expDate = card.Expire;
dc.name = card.Owner;
Data.Add(dc);
}
}
}
public class CimEmbosser : Emboser.IEmbosser
{
public eEmbosserType EmbosserType => eEmbosserType.Datacard2;
public List<EmbosserData> Data { get; set; }
public void CreateFileForEmbosser(string path)
{
using (StreamWriter sw = new StreamWriter(path))
{
foreach (Cim item in Data)
{
sw.Write(item.cardNumber + ";");
sw.Write(item.city + ";");
sw.Write(item.name + ";");
sw.Write(item.expDate + ";");
sw.Write(item.version + ";");
}
}
}
public void PrepareDataForEmboser()
{
Data = new List<EmbosserData>();
List<CardData> cards = GetCardData();
foreach (CardData card in cards)
{
Cim dc = new Cim();
dc.cardNumber = card.PAN;
dc.city = card.City;
dc.expDate = card.Expire;
dc.name = card.Owner;
dc.version = DateTime.Now.ToString() + GetNewVersionNumber();
Data.Add(dc);
}
}
}
public class DataCard2Embosser : Emboser.IEmbosser
{
public eEmbosserType EmbosserType => eEmbosserType.Datacard2;
public List<EmbosserData> Data { get; set; }
public void CreateFileForEmbosser(string path)
{
using (StreamWriter sw = new StreamWriter(path))
{
foreach (DataCard2 item in Data)
{
sw.Write(item.cardNumber + ";_");
sw.Write(item.city + "?");
sw.Write(item.name + ";");
sw.Write(item.expDate + "#");
sw.Write(item.f1 + " ");
sw.Write(item.f2 + " ");
sw.Write(item.f3 + " ");
}
}
}
public void PrepareDataForEmboser()
{
Data = new List<EmboserData>();
List<CardData> cards = GetCardData();
foreach (CardData card in cards)
{
DataCard2 dc = new DataCard2();
dc.cardNumber = card.PAN;
dc.city = card.City;
dc.expDate = card.Expire;
dc.name = card.Owner;
dc.f1 = card.PAN + " " + card.Expire;
dc.f2 = card.Owner + " " + card.Address;
dc.f3 = cards.Count().ToString().Trim();
Data.Add(dc);
}
}
}
</code></pre>
<p>And factory creator </p>
<pre><code>public class EmbosserCreator
{
public static IEmbosser GetEmboser(eEmbosserType type)
{
switch (type)
{
case eEmbosserType.Datacard:
return new DataCardEmbosser();
case eEmbosserType.Cim:
return new CimEmbosser();
case eEmbosserType.Datacard2:
return new DataCard2Embosser();
default:
throw new Exception("");
}
}
}
</code></pre>
<p>For data I thought I should create an abstract class, <code>EmbosserData</code>, which inherits classes <code>DataCard</code>, <code>CIM</code>, and <code>DataCard2</code>.</p>
<p>For example:</p>
<pre><code>public abstract class EmbosserData
{
public string cardNumber { get; set; }
public string name { get; set; }
public string city { get; set; }
public string expDate { get; set; }
}
public class DataCard : EmbosserData
{
}
public class Cim : EmbosserData
{
public string version { get; set; }
}
public class DataCard2 : EmbosserData
{
public string f1 { get; set; }
public string f2 { get; set; }
public string f3 { get; set; }
}
</code></pre>
<p>Is this a good approach for my project? If you have any advice for other implementations, I'd love to know more.</p>
<p>PS. I hope that code is now ok to understand my idea.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T07:59:25.230",
"Id": "446529",
"Score": "2",
"body": "Please visit our help center to see how to ask a question that is on-topic for this site: https://codereview.stackexchange.com/help/how-to-ask. Hypothetical identifiers _A, B, C_ are discouraged. Could you post your real working code instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T08:06:02.457",
"Id": "446531",
"Score": "0",
"body": "Real working code contains my mother language, so you would confuse if you read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T08:28:00.093",
"Id": "446533",
"Score": "2",
"body": "See [this meta question](https://codereview.meta.stackexchange.com/questions/3795/should-code-be-forcibly-translated-into-english) for some comments concerning translations. We require working (and not stub) code because otherwise the OP ends up with many completely useless reviews, and miss out on the context-sensitive useful stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:16:18.030",
"Id": "446680",
"Score": "0",
"body": "This is looking much better, but can you include the definitions of `DataCard` and `DataCard2`? Again, stub code simple isn't worth posting, because it can't be usefully reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:40:32.147",
"Id": "446684",
"Score": "0",
"body": "DataCard is machine with old standard and DataCard2 is machine with newer standard, difference between them is that newer standard has F1, F2 and F3 fields, and bit different delimiters in file according to DataCard old standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:31:45.180",
"Id": "446799",
"Score": "1",
"body": "Where is `GetCardData` defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T17:00:08.883",
"Id": "446852",
"Score": "1",
"body": "GetCardData is method that reads data from database with SqlDataReader and returns list of objects CardData."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:28:50.903",
"Id": "446860",
"Score": "0",
"body": "Could you show us how this will be used? It would help to see if it's a good approach."
}
] |
[
{
"body": "<h3><code>eEmbosserType</code></h3>\n\n<ul>\n<li>Don't use Hungarian Notation in C#. A better name would be <code>EmbosserType</code> or <code>EmbosserKind</code>.</li>\n</ul>\n\n<h3><code>IEmbosser</code></h3>\n\n<ul>\n<li>This is a public interface, so I would expect that consumers could make their own implementations. If this is allowed, consumers are hampered by <code>EmbosserType</code> because this enum is under your control. Consider using an external key like <code>string</code> if more types are allowed.</li>\n<li>Next up are methods <code>CreateFileForEmbosser</code>, <code>PrepareDataForEmboser</code> and a mutable property <code>Data</code>. These are 3 separate concerns: IO, data lookup and in-memory data storage. This might be a bit too much for a single interface to handle. I feel these concerns are sufficiently independant to warrant separate interfaces to allow better <em>reusability</em>, <em>granularity</em> and <em>modularity</em>. Consider splitting into interfaces <code>IDataRepository</code> (db or any other data source access), <code>IDataProvider</code> (store the data in-memory with a read-only getter) and <code>IDataWriter</code> (write data to a stream).</li>\n<li>I have a few problems with method <code>PrepareDataForEmboser</code> since it's void and takes no parameters. Implementations only have the name of the method to decide what to do, and what is expected of them to do. From your implementatons I reverse engineered (should have documentation instead) that this method expects <code>Data</code> to be set. An additional problem here is that this property is mutable, allowing consumers to bypass the method and store <code>Data</code> directly, rendering your method unguarded and the design insufficiently encapsulated. Furthermore, implementations have to fetch the data <code>GetCardData</code> and store it internally, which is also mixing two different concerns.</li>\n<li>Method <code>CreateFileForEmbosser</code> is very specific that it needs to write to the system. I would change the specification to allow to write to a <code>Stream</code> instead. This way, consumers are free to provide the type of stream to write to, a file, a string builder, or any other stream.</li>\n</ul>\n\n<h3><code>class *Embosser</code></h3>\n\n<ul>\n<li>I have questions about this design where each concrete instance fetches base class <code>EmbosserData</code> data using <code>GetCardData</code>, while iterating over concrete (for instance <code>DataCard</code>) data. I would have expected a base class to provide method <code>GetCardData</code> and perhaps also a generic type parameter for the return type.</li>\n</ul>\n\n<h3><code>EmbosserCreator</code></h3>\n\n<ul>\n<li>In the initial revision of your question, you called this an <em>Abstract Factory Pattern</em>. Note, this is just a <em>Factory Pattern</em>. The former pattern is a factory for factories.</li>\n<li>Exception information might be a bit too cryptic for consumers and end-users: <code>throw new Exception(\"\");</code>.</li>\n</ul>\n\n<hr>\n\n<h3>Conclusion</h3>\n\n<p>In general, I'm not sure why you need a factory for these different embossers, since each of them work with different data classes (probably also different data sources) and different data serialisation. Your question does not show us how you would use this pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T07:39:13.647",
"Id": "446947",
"Score": "1",
"body": "Thank you for your review, after your comments I think I messed with design, maybe it is better to use just abstract class `Embosser` instead interface.\nAnd all classes that inherits `Embosser` class override methods `CreateFileForEmbosser`, `PrepareDataForEmboser`\n\nMethod GetCardData fetch data from only one table, and from that data I create object of class `DataCard2`, `CIM` and `DataCard`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:05:08.927",
"Id": "229654",
"ParentId": "229554",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T06:33:26.733",
"Id": "229554",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"interface"
],
"Title": "Factory pattern for creating embossing machines"
}
|
229554
|
<p>I have a function which returns an error. I would like to handle this error on the caller function, so I need to know the reason of the error in the caller function.</p>
<p>Below there is my solution, but I am not sure, that it is ideomatic Go code and would be thankfull for any comments.</p>
<p>Here is the function:</p>
<pre><code>func (e *Engine) returnOrCreateArtist(musicService musicservices.IMusicService, serviceArtistId string) (*core.Artist, error) {
artist, err := e.DataRepository.ArtistRepository.GetByArtistId(serviceArtistId)
if err != nil {
artist, err = musicService.DownloadArtist(serviceArtistId)
if err != nil {
return nil, NewDownloadArtistError(err)
}
artist, err = e.DataRepository.ArtistRepository.Store(artist)
if err != nil {
return nil, NewStoreArtistError(err)
}
}
return artist, nil
}
</code></pre>
<p>It can returns errors of two types, so I have created two structs to distinct two types of my error:</p>
<pre><code>type DownloadArtistError struct {
InnerError error
}
func (e *DownloadArtistError) Error() string {
return e.InnerError.Error()
}
func NewDownloadArtistError(e error) *DownloadArtistError {
return &DownloadArtistError{InnerError: e}
}
type StoreArtistError struct {
InnerError error
}
func (e *StoreArtistError) Error() string {
return e.InnerError.Error()
}
func NewStoreArtistError(e error) *StoreArtistError {
return &StoreArtistError{InnerError: e}
}
</code></pre>
<p>And here is a part of caller function:</p>
<pre><code>artist, err := e.returnOrCreateArtist(musicService, track.ServiceArtistId)
if err != nil {
switch e := err.(type) {
case *DownloadArtistError:
logger.With(zap.Error(e)).Errorw("не удалось получить исполнителя на музыкальном сервисе",
"Track.ServiceId", track.TrackId,
"Track.PlaylistId", track.PlaylistId,
"Track.ArtistId", track.ServiceArtistId)
case *StoreArtistError:
logger.With(zap.Error(err)).Errorw("не удалось сохранить исполнителя",
"Track.ServiceId", track.TrackId,
"Track.PlaylistId", track.PlaylistId,
"Track.ArtistId", track.ServiceArtistId)
}
continue
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T07:39:50.340",
"Id": "446526",
"Score": "1",
"body": "Basically fine. Minor things: There is no real need to have Error operate on pointer receivers, values would lead to less typing. `InnerError` is an uncommon name, `Err` or `Cause` might be alternatives to consider."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T07:41:59.970",
"Id": "446527",
"Score": "0",
"body": "Instead of different type and type-switching you could do a `type ArtistError struct {Err error; Kind int}` where the different kinds of errors are distinguished by the Kind field (some enum, or a string, you choose)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T07:48:10.013",
"Id": "446528",
"Score": "1",
"body": "I'm not a big fan of the `New... functions` as they do nothing you could not do with a literal. I would get rid of them and write `return nil, StoreArtisError{err}` or (see previous comment) `return nil, ArtistError{Err: err, Kind: DownloadError}`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T07:29:45.823",
"Id": "229555",
"Score": "0",
"Tags": [
"error-handling",
"go",
"exception"
],
"Title": "Error handling in Go"
}
|
229555
|
<p>I have a Tree structure represented by a <code>List</code>, which I want to get it flattened.</p>
<p>I wrote the function below:</p>
<pre><code>List<Entry> flatTree(List<Entry> toFlat, List<Entry> destination) {
for (Entry entry : toFlat) {
if (CollectionUtils.isNotEmpty(entry.getEntries())) {
this.flatTree(entry.getEntries(), destination);
} else {
destination.add(entry);
}
}
return destination;
}
</code></pre>
<p>used in this way:</p>
<pre><code>List<Entry> flattenedEntries = this.flatTree(entries, new ArrayList<>());
</code></pre>
<p>with this kind of input (<code>entries</code>):</p>
<pre><code>[
{
key: "level1.1",
entries: []
},
{
key: "level1.2",
entries: [
{
key: "level2.1",
entries: []
}
]
},
{
key: "level1.3",
entries: [
{
key: "level2.2",
entries: []
},
{
key: "level2.3",
entries: [
{
key: "level3.1",
entries: []
}
]
}
]
}
]
</code></pre>
<p>What I'm going to achieve is to have a list containing only objects with keys: <code>level1.1, level2.1, level2.2, level3.1</code> or rather, all the elements that has no sub elements <code>entries</code>.</p>
<p>Each object has just 2 properties inside: <code>key</code> and <code>entries</code>.</p>
<p>It works, but I would like to avoid the side effect on the <code>List<Entry> destination</code>. Is there a better way to write it? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:49:29.597",
"Id": "446563",
"Score": "0",
"body": "You’ll need to add more context. What is an `Entry`? Does it have more info than is shown in your JSON? Why are you adding the entry that contains no subentry, but you don’t add an entry that contains other entries? Do you have two types of entries: containers & leafs? Are you losing the `key` data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T05:11:45.700",
"Id": "446726",
"Score": "0",
"body": "Hi, I just added more information. Should be enough to understand what I mean."
}
] |
[
{
"body": "<p><del>First off, I'm assuming the call of the method <code>flatEntriesMap</code> is wrong and it should be a recursive call to <code>flatTree</code>.</del> (EDIT: Source code has been corrected.)</p>\n\n<p>Then you should reconsider the name, especially considering the confusion before your edit: You are not flatting the tree, but retrieving its leaves.</p>\n\n<p>To get rid of the side effect, you simply make the original method <code>private</code> and wrap a new method around it that creates the destination list:</p>\n\n<pre><code>public List<Entry> flatTree(List<Entry> toFlat) {\n return this.flatTree(toFlat, new ArrayList<>());\n}\n</code></pre>\n\n<p>In case you need to be able to determine the type of list returned from the outside, then instead of passing a new instance pass a supplier that creates the instance:</p>\n\n<pre><code>public List<Entry> flatTree(List<Entry> toFlat, Supplier<List<Entry>> listSupplier) {\n return this.flatTree(toFlat, listSupplier.get());\n}\n</code></pre>\n\n<p>which can then be called either with</p>\n\n<pre><code>flatTree(entries, () -> new ArrayList<>());\n</code></pre>\n\n<p>or</p>\n\n<pre><code>flatTree(entries, ArrayList::new);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:09:46.810",
"Id": "446796",
"Score": "0",
"body": "Thanks! I wonder if there is any way to do this by using, for example, just the Java 8 Stream API or something similar, to have it in just one line of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:47:14.860",
"Id": "446809",
"Score": "0",
"body": "@grimi I was thinking about suggesting streams, but I couldn't figure out a nice way to do it, that is actually better than without. I'll do more thinking about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T10:23:33.727",
"Id": "446970",
"Score": "0",
"body": "Sure! Super thanks! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:08:06.473",
"Id": "229627",
"ParentId": "229557",
"Score": "2"
}
},
{
"body": "<p>To answer the question from the <a href=\"https://codereview.stackexchange.com/questions/229557/build-a-flat-list-from-a-tree-structure-in-java/229627#comment446796_229627\">comment</a> on RoToRa's answer:</p>\n\n<blockquote>\n <p>Thanks! I wonder if there is any way to do this by using, for example, just the Java 8 Stream API or something similar, to have it in just one line of code.</p>\n</blockquote>\n\n<h2>Using the Java Stream API</h2>\n\n<p>Assuming the following <code>Entry</code> class:</p>\n\n<pre><code>public class Entry {\n final String key;\n final List<Entry> entries = new ArrayList<>();\n\n Entry(String _key, Entry ...children) {\n key = _key;\n entries.addAll(Arrays.asList(children));\n }\n\n public List<Entry> getEntries() {\n return Collections.unmodifiableList(entries);\n }\n\n public String toString() {\n return key;\n }\n}\n</code></pre>\n\n<p>We can build up the example input with:</p>\n\n<pre><code>List<Entry> top = new ArrayList<>();\ntop.add(new Entry(\"level1.1\"));\ntop.add(new Entry(\"level1.2\", new Entry(\"level2.1\")));\ntop.add(new Entry(\"level1.3\", new Entry(\"level2.2\"), new Entry(\"level2.3\", new Entry(\"level3.1\"))));\n</code></pre>\n\n<p>From @RoToRa's answer, we'll borrow these method signatures:</p>\n\n<pre><code>public static List<Entry> flatTree(List<Entry> toFlat) {\n return flatTree(toFlat, ArrayList::new);\n}\n\npublic static List<Entry> flatTree(List<Entry> toFlat, Supplier<List<Entry>> listSupplier) {\n</code></pre>\n\n<p>Now, to flatten with the Stream API, (the <strong>requested \"one line of code\"</strong>), we'd want to write something like:</p>\n\n<pre><code> return toFlat.stream().flatMap(Entry::leaves)\n .collect(Collectors.toCollection(listSupplier));\n}\n</code></pre>\n\n<p>So, we'll need to define <code>Entry::leaves</code> to extract only the leaves from our tree:</p>\n\n<pre><code>public static Stream<Entry> leaves(Entry entry) {\n if (entry.getEntries().size() > 0)\n return entry.getEntries().stream().flatMap(Entry::leaves);\n else\n return Stream.of(entry);\n}\n</code></pre>\n\n<p>And on the sample data:</p>\n\n<pre><code>jshell> System.out.println(Entry.flatTree(top));\n[level1.1, level2.1, level2.2, level3.1]\n\njshell>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:09:02.613",
"Id": "446877",
"Score": "0",
"body": "Nice ideas, but I'm not a big fan of having `.stream().flatMap(Entry::leaves)` twice in there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:25:52.907",
"Id": "446879",
"Score": "0",
"body": "@RoToRa `Entry::leaves` is recursive. You need to call it at least once somewhere, and then it must call itself to descend into the tree branches. Ego, it must appear twice. Hard to do recursion any other way. I dislike the top-level `toFlat.stream().flatMap(...)`, but the problem description has a list of trees at the top level instead of one root tree node, which causes some of the repetition of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T13:39:58.483",
"Id": "447003",
"Score": "1",
"body": "You've got a good point there. There was something bothering me, and you are right, it's because the input is a list of (root) nodes, instead of a single root. That's a continuation of confusion due to the misnaming of the original method `flatTree`: Not only is the \"flat\" part wrong, because it's not a flattening but retrieving of leaves, but the \"tree\" part is also wrong, because is not a about a single tree, but multiple trees."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T17:12:26.253",
"Id": "229651",
"ParentId": "229557",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T09:00:32.583",
"Id": "229557",
"Score": "5",
"Tags": [
"java",
"recursion",
"tree"
],
"Title": "Build a flat List from a Tree structure in Java"
}
|
229557
|
<p>I wanted to implement a thread pool to test my knowledge of various modern C++ features. The end result could be better, but I need a review as I'm not sure about delicate things especially regarding synchronization and variable argument passing and of course recommendations on improvements of the code as well as my reasoning below! The code compiles and runs on MSVS 2017 15.9.15.</p>
<p>First of, this is the design I've set up, by mainly reading the wikipedia <a href="https://en.wikipedia.org/wiki/Thread_pool" rel="noreferrer">article</a> and briefly skimming-through a couple of similar questions here. I say briefly because I wanted to implement this on my own.</p>
<ul>
<li>there is an array of threads</li>
<li>there is a FIFO queue of tasks (a Task should be a wrapper for a Callable object).</li>
<li>when a client creates a task he <code>enqueu()</code>s it into the task queue</li>
<li>all threads are started up front in the pool and they never quit running; if there's no task in the queue they <code>wait</code></li>
<li>each incoming task <code>notifies()</code> a single thread to handle it</li>
<li>if a Task returns a result the client can send a query for its value later</li>
<li>the thread pool has a switch On/Off flag</li>
<li>Thread synchronization: a <code>condition_variable</code> (m_cond) along with a <code>mutex</code> variable (m_mu) perform thread synchronization
<ul>
<li>m_mu is used to synchronize access to shared data (the containers mostly)</li>
<li>m_cond notifies threads upon task arrival and puts them to sleep when there are no tasks</li>
</ul></li>
</ul>
<p>The <strong>key</strong> implementation question I asked myself is "how can one create a container of callable objects"? In general a container of generic objects, in order to accomodate functions of any signature. <code>std::any</code> came up to my mind, but I thought it would possibly too much, making the entire class a template. So i questioned whether I can circumvent this somehow.</p>
<p>And I thought of a bare wrapper <code>std::function<void()></code> could possibly work, as the type of the task queue, as almost all c++ callables can be converted to an <code>std::function<T></code>. But this would be only an indirection, inside this <code>std::function</code> I would need to pass up the arguments up front (however many the client supplies).</p>
<p>Then I thought that I also want to provide return values to the client. The only way to do this in C++ in an generic way I know of is a <code>future</code>. And then I realized I need another level of indirection, a <code>std::packaged_task</code> which will wrap the <code>std::function</code> which will wrap the call to our target (member) <code>function</code>. And I must also make sure the packaged_task lives long enough for it to return the value, ie dynamic allocation through a <code>unique_ptr</code> or <code>shared_ptr</code> would be suitable. I decided on a <code>shared_ptr</code> as <code>unique_ptr</code> was unfortunately not enough.</p>
<p>And now to the code. This is the thread pool code:</p>
<pre><code>#include <iostream>
#include <functional>
#include <vector>
#include <thread>
#include <queue>
#include <condition_variable>
#include <future>
#include <memory>
#include <sstream>
#include <string>
class ThreadPool final
{
using Task = std::function<void()>;
public:
explicit ThreadPool(std::size_t nthreads = std::thread::hardware_concurrency(),
bool enabled = true) noexcept
: m_nthreads{ nthreads },
m_enabled{ enabled }
{
m_pool.reserve(nthreads);
run();
}
~ThreadPool() noexcept
{
stop();
}
ThreadPool(ThreadPool const&) = delete;
ThreadPool& operator=(const ThreadPool& rhs) = delete;
void start() noexcept
{
m_enabled.store(true);
run();
}
void stop() noexcept
{
m_enabled.store(false);
//std::unique_lock<std::mutex> lg{ m_mu }; // comment out and the program never ends
m_cond.notify_all();
for (auto& t : m_pool)
{
if (t.joinable())
{
t.join();
}
}
}
template<typename Callback, typename... TArgs>
decltype(auto) enqueue(Callback&& f, TArgs&&... args)
//auto enqueue(Callback&& f, TArgs&&... args) -> std::future<std::invoke_result_t<Callback, TArgs...>>
{
using ReturnType = std::invoke_result_t<Callback, TArgs...>;
using FuncType = ReturnType(TArgs...);
using Wrapped = std::packaged_task<FuncType>;
std::shared_ptr<Wrapped> smartFunctionPointer = std::make_shared<Wrapped>(f);
{
std::unique_lock<std::mutex> lg{ m_mu };
m_tasks.emplace(
[smartFunctionPointer, &args...]() -> void
{
(*smartFunctionPointer)(std::forward<TArgs>(args)...);
return;
}
);
m_cond.notify_one();
}
return smartFunctionPointer->get_future();
}
private:
std::atomic<bool> m_enabled = false;
size_t m_nthreads;
std::vector<std::thread> m_pool;
std::queue<Task> m_tasks;
std::condition_variable m_cond;
std::mutex m_mu;
void run()
{
for (int ti = 0; ti < m_nthreads; ++ti)
{
m_pool.emplace_back(
std::thread{
[this] () mutable
{
//using namespace std::chrono_literals;
Task task;
while (m_enabled)
{
{
std::unique_lock<std::mutex> lg{ m_mu };
while (m_tasks.empty() && m_enabled)
m_cond.wait(lg);
}
if (!m_tasks.empty())
{// there is a task available
std::unique_lock<std::mutex> lg{ m_mu };
task = std::move(m_tasks.front());
m_tasks.pop();
task();
}
}// while threadPool is enabled
//return;
}// thread function
}// launch thread
);// place thread in the pool
}// for all threads
}
};
/////////////////////////////////////////////////////////////////////////
</code></pre>
<p>This is the test code sample:</p>
<pre><code>// Create some work to test the Thread Pool
void spitId()
{
std::cout << "thread #" << std::this_thread::get_id() << '\n';
}
void sayAndNoReturn()
{
auto tid = std::this_thread::get_id();
std::cout << "thread #" << tid << "says " << " and returns... ";
std::cout << typeid(tid).name() << '\n'; // std::thread::id
}
char sayWhat(int arg)
{
auto tid = std::this_thread::get_id();
std::stringstream sid;
sid << tid;
int id = std::stoi(sid.str());
std::cout << "\nthread #" << id << " says " << arg << " and returns... ";
if (id > 7000)
return 'X';
return 'a';
}
struct Member
{
int i_ = 4;
void sayCheese(int i)
{
std::cout << "CHEESEE!" << '\n';
std::cout << i + i_ << '\n';
}
};
int vv() { puts("nothing"); return 0; }
int vs(const std::string& str) { puts(str.c_str()); return 0; }
int main()
{
ThreadPool threadPool{ std::thread::hardware_concurrency() };
threadPool.enqueue(spitId);
threadPool.enqueue(&spitId);
threadPool.enqueue(sayAndNoReturn);
auto f1 = threadPool.enqueue([]() -> int
{
std::cout << "lambda 1\n";
return 1;
});
auto sayWhatRet = threadPool.enqueue(sayWhat, 100);
std::cout << sayWhatRet.get() << '\n';
Member member{ 1 };
threadPool.enqueue(std::bind(&Member::sayCheese, member, 100));
std::cout << f1.get() << '\n';
auto f2 = threadPool.enqueue([]()
{
std::cout << "lambda 2\n";
return 2;
});
auto f3 = threadPool.enqueue([]()
{
return sayWhat(100);
});
//threadPool.enqueue(std::function<void(int)>{Member{}.sayCheese(100)});
std::cout << "f1 type = " << typeid(f2).name() << '\n';
std::cout << f2.get() << '\n';
std::cout << f3.get() << '\n';
return EXIT_SUCCESS;
}
</code></pre>
<p>Also note that I use an custom-made class in Windows which gets initialized during program start and at the end says whether there are any memory leaks. Thankfully no memory leaks were observed.</p>
<p>The parts of the code I am mostly interested in feedback (because those are the parts I'm mostly unsure of) are:</p>
<ol>
<li><p>thread synchronization. Is it done properly? Do I cover any possible scenarios? You will notice a commented <code>std::unique_lock</code> in the <code>stop</code> function. If I comment this out the threadPool never ends. I debugged and the threads never return. I believe this is a deadlock. The main thread grabs the mutex there, in the meantime other threads are waiting when they get notified in the next statement by the main thread they don't seem to wake up.. I'm not sure about this.</p></li>
<li><p>The way I capture the arguments and the <code>smartFunctionPointer</code> in the lambda. I tried out different combinations, by ref etc. and I picked the one which works best (capturing by value). This is however not proper design, as I'm not sure I understand for example, why capturing by reference there causes an exception.</p></li>
</ol>
|
[] |
[
{
"body": "<p>Welcome to Code Review! Here's some suggestions:</p>\n\n<ul>\n<li><p>Sort the <code>#include</code> directives in alphabetical order. <code><sstream></code> and <code><string></code> shouldn't be in the implementation.</p></li>\n<li><p>The constructor should not be <code>noexcept</code> — it allocates resources. Same for <code>start</code>.</p></li>\n<li><p>The destructor is implicitly <code>noexcept</code>, so you can omit it.</p></li>\n<li><p>In <code>enqueue</code>, the lambda captures <code>&args...</code>. This potentially creates dangling references. Also, the <code>() -> void</code> and <code>return;</code> in the lambda can be omitted.</p></li>\n<li><p>In the declaration of <code>m_nthreads</code>, the type specifier should be <code>std::size_t</code>, not <code>size_t</code>. You also didn't <code>#include <cstddef></code>.</p></li>\n<li><p>In <code>run</code>, the type of <code>ti</code> should be <code>std::size_t</code>, not <code>int</code>. The lambda does not have to be <code>mutable</code> because the only thing you capture is the <code>this</code> pointer which you don't want to modify, do you?</p></li>\n<li><p>The textual representation of a thread identifier is not guaranteed to be suitable for extracting as <code>int</code>.</p></li>\n<li><p>Don't mix C I/O with streams. Especially don't do <code>puts(str.c_str())</code> (which should have been <code>std::puts</code> anyway). You can turn off sync between C I/O and streams to (potentially) improve performance.</p></li>\n<li><p>You can omit the final <code>return</code> statement in <code>main</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:23:17.460",
"Id": "446665",
"Score": "0",
"body": "\"The lambda shouldn't be mutable\". Indeed, I thought that popping from the queue would require mutability.. I was wrong.. Can you tell me why capturing `&args...` by reference I create dangling references? `args...` is intended to be used only to call the function. They aren't used elsewhere so why would they dangle? Am I missing something? Thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:08:34.560",
"Id": "446748",
"Score": "1",
"body": "@Nikos You are welcome. `args` are the parameters of the enclosing function, but the lambda is placed in the queue and will be executed later. At that time, the parameters referred to by `args` may have ceased to exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:39:47.770",
"Id": "446871",
"Score": "0",
"body": "You are right. I resulted in `move`ing them in the lambda instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:05:34.423",
"Id": "229562",
"ParentId": "229560",
"Score": "9"
}
},
{
"body": "<pre><code>Task task;\nwhile (m_enabled)\n{\n {\n std::unique_lock<std::mutex> lg{ m_mu };\n while (m_tasks.empty() && m_enabled)\n m_cond.wait(lg);\n }\n if (!m_tasks.empty())\n {// there is a task available\n std::unique_lock<std::mutex> lg{ m_mu };\n task = std::move(m_tasks.front());\n m_tasks.pop();\n task();\n }\n}// while threadPool is enabled\n</code></pre>\n\n<p>This all seems a bit dodgy.</p>\n\n<ul>\n<li>We acquire a lock for waiting, and checking if tasks is empty (ok).</li>\n<li>Then when a task appears in the queue we dispose of the lock (?).</li>\n<li>We then check for emptiness without a lock (!!), and acquire a new lock. The queue could well become empty between checking for emptiness, and acquiring the new lock (and more importantly the subsequent unchecked call to <code>front()</code>).</li>\n<li>Then we take the task off the queue, and execute it while still holding the lock (!). So we are effectively executing tasks in a single-threaded fashion.</li>\n</ul>\n\n<p>I'd expect it to look something like:</p>\n\n<pre><code>while (true)\n{\n std::unique_lock<std::mutex> lg{ m_mu };\n m_cond.wait(lg, [&] () { return !m_enabled || !m_tasks.empty(); });\n\n if (!m_enabled)\n break;\n\n //assert(!m_tasks.empty());\n\n auto task = std::move(m_tasks.front());\n m_tasks.pop();\n\n lg.unlock();\n\n task();\n}\n</code></pre>\n\n<hr>\n\n<pre><code>std::atomic<bool> m_enabled = false;\n</code></pre>\n\n<p>This directly contradicts the default argument in the constructor.</p>\n\n<hr>\n\n<pre><code> : m_nthreads{ nthreads },\n m_enabled{ enabled }\n</code></pre>\n\n<p>Make sure to specify the members in the same order as they are declared in the body of the class (since that is the order they will actually be initialized in). Your compiler should warn you about this.</p>\n\n<hr>\n\n<p>The current logic for when to <code>run()</code> or <code>stop()</code> seems to be faulty. It looks like we call <code>run()</code> in the constructor, whether or not the thread pool is <code>enabled</code>.</p>\n\n<p><code>run()</code> may then be called a second time in <code>start()</code>, which will add another <code>nthreads</code> to the thread pool.</p>\n\n<p>Similarly, after <code>stop()</code> is called, we still have threads in the pool (and in the vector), even if they have been joined.</p>\n\n<hr>\n\n<p>Besides the lifetime issues pointed out by L.F., taking the arguments to the packaged task and forwarding them is quite complicated. The user can already manage arguments themselves with <code>std::bind</code> or lambda capture, so there's probably no need for another method. We can just take a single callable object.</p>\n\n<p>Perhaps <code>std::promise</code> might be a better choice than <code>std::packaged_task</code>. We don't need the capabilities of launching a new thread with a <code>packaged_task</code>, and we are effectively handling the packaging of the task ourselves.</p>\n\n<hr>\n\n<p>There's not really any need for <code>m_enabled</code> to be atomic. The only place where we would need a lock for it is in the stop function.</p>\n\n<hr>\n\n<p>Suggested modifications:</p>\n\n<pre><code>#include <cassert>\n#include <condition_variable>\n#include <cstddef>\n#include <functional>\n#include <future>\n#include <queue>\n#include <thread>\n#include <vector>\n\nclass ThreadPool final\n{\npublic:\n\n explicit ThreadPool(std::size_t nthreads = std::thread::hardware_concurrency()):\n m_enabled(true),\n m_pool(nthreads)\n {\n run();\n }\n\n ~ThreadPool()\n {\n stop();\n }\n\n ThreadPool(ThreadPool const&) = delete;\n ThreadPool& operator=(const ThreadPool&) = delete;\n\n template<class TaskT>\n auto enqueue(TaskT task) -> std::future<decltype(task())>\n {\n using ReturnT = decltype(task());\n auto promise = std::make_shared<std::promise<ReturnT>>();\n auto result = promise->get_future();\n\n auto t = [p = std::move(promise), t = std::move(task)] () mutable { execute(*p, t); };\n\n {\n std::lock_guard<std::mutex> lock(m_mu);\n m_tasks.push(std::move(t));\n }\n\n m_cv.notify_one();\n\n return result;\n }\n\nprivate:\n\n std::mutex m_mu;\n std::condition_variable m_cv;\n\n bool m_enabled;\n std::vector<std::thread> m_pool;\n std::queue<std::function<void()>> m_tasks;\n\n template<class ResultT, class TaskT>\n static void execute(std::promise<ResultT>& p, TaskT& task)\n {\n p.set_value(task()); // syntax doesn't work with void ResultT :(\n }\n\n template<class TaskT>\n static void execute(std::promise<void>& p, TaskT& task)\n {\n task();\n p.set_value();\n }\n\n void stop()\n {\n {\n std::lock_guard<std::mutex> lock(m_mu);\n m_enabled = false;\n }\n\n m_cv.notify_all();\n\n for (auto& t : m_pool)\n t.join();\n }\n\n void run()\n {\n auto f = [this] ()\n {\n while (true)\n {\n std::unique_lock<std::mutex> lock{ m_mu };\n m_cv.wait(lock, [&] () { return !m_enabled || !m_tasks.empty(); });\n\n if (!m_enabled)\n break;\n\n assert(!m_tasks.empty());\n\n auto task = std::move(m_tasks.front());\n m_tasks.pop();\n\n lock.unlock();\n task();\n }\n };\n\n for (auto& t : m_pool)\n t = std::thread(f);\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:36:33.360",
"Id": "229569",
"ParentId": "229560",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "229569",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T11:12:11.240",
"Id": "229560",
"Score": "13",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"callback"
],
"Title": "Implementation of a Thread Pool in C++"
}
|
229560
|
<p>I could barely get this to work... It seems there is redundancy as the dates are repeated twice, for example. Is there a way to simplify it?</p>
<pre><code>WITH total AS
(
SELECT COUNT(type) AS total FROM loan_loan
WHERE
loan_loan.created_at > '2019-08-15' and
loan_loan.created_at < '2019-09-05'
)
SELECT
type,
COUNT(*),
(0.00 + COUNT(*)) / total.total as share
FROM loan_loan, total
WHERE
loan_loan.created_at > '2019-08-15' and
loan_loan.created_at < '2019-09-05'
GROUP BY
type,
total.total
</code></pre>
<p>It (correctly) returns a table like this:</p>
<pre><code>|---------------------|------------------|------------------|
| type | count | share |
|---------------------|------------------|------------------|
| type1 | 26 | 0.52 |
|---------------------|------------------|------------------|
| type2 | 24 | 0.48 |
|---------------------|------------------|------------------|
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:47:19.117",
"Id": "446562",
"Score": "2",
"body": "Could you tell us what this is supposed to do? Also, you have DDL statements?"
}
] |
[
{
"body": "<h2>CTEs</h2>\n\n<p>A CTE is an optimization fence. You'll want to try to avoid it and at the least convert it into a subquery.</p>\n\n<h2>Casting</h2>\n\n<p>Do an explicit cast instead of an implicit cast:</p>\n\n<pre><code>0.00 + COUNT(*)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>count(*)::real\n</code></pre>\n\n<h2>Between</h2>\n\n<p>Rather than writing</p>\n\n<pre><code> loan_loan.created_at > '2019-08-15' and \n loan_loan.created_at < '2019-09-05'\n</code></pre>\n\n<p>write</p>\n\n<pre><code> loan_loan.created_at between '2019-08-15' and '2019-09-05'\n</code></pre>\n\n<h2>Joining</h2>\n\n<p>More broadly: are you sure this is doing the right thing? You aren't selecting <code>type</code> from your CTE to join to your upper query's <code>loan_loan.type</code>. Given the lack of this join, I fail to see how your <code>total</code> column will be reliably matched to your upper rows.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:13:19.797",
"Id": "446597",
"Score": "0",
"body": "Regarding joining, this is all from one table: `loan_loan`, so should be OK, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:13:49.783",
"Id": "446598",
"Score": "0",
"body": "Nope :) the moment that you do two different select statements, they create two different \"virtual\" tables that you need to join together."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:40:51.343",
"Id": "229570",
"ParentId": "229563",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:42:12.323",
"Id": "229563",
"Score": "3",
"Tags": [
"sql",
"postgresql"
],
"Title": "SQL query on percentage share of different groups in total"
}
|
229563
|
<p>I'm trying to resolve <a href="https://www.codewars.com/kata/path-finder-number-1-can-you-reach-the-exit/train/javascript" rel="nofollow noreferrer">this kata</a> from CodeWars.</p>
<h1>Kata exercise</h1>
<blockquote>
<p>You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return <code>true</code> if you can reach position [N-1, N-1] or <code>false</code> otherwise.</p>
<p>Empty positions are marked <code>.</code>. Walls are marked <code>W</code>. Start and exit positions are empty in all test cases.</p>
</blockquote>
<p>I made a simple depth first search algorithm to solve the maze and check if there exists an exit.</p>
<p>But I noticed that my code is too slow and so it produces Execution Timed Out error.</p>
<p>I'm quite sure that changing this algorithm to an heuristic one could fix this, but I don't want to do that. I want to solve this using a Deep Search Algorithm. Is possible to improve the performance of this code?</p>
<p>I think the problem may be in the <code>set</code>, which don't have a <code>pop</code> method, so removing an item from them is quite difficult. But using an array would even require more time to check if the item already exists there.</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 pathFinder(maze) {
// Turn maze from string to nested array
let chart = [];
for (let c of maze.split("\n")) {
chart.push([...c]);
}
let size = chart.length;
// Make toVisit frontier
let toVisit = new Set();
toVisit.add([0, 0]);
// Check if we already are in the exit
let end = size - 1;
// Size 1 maze
if (end == 0)
return true;
while (toVisit.size > 0) {
// Pop value from set
let pos = toVisit.values().next().value;
toVisit.delete(pos);
let [x, y] = pos;
chart[x][y] = "*"; // Mark as visited
// Iterate over adjancets
for ([x, y] of [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]) {
// Check exit
if (end == x && end == y)
return true;
// Check array out of boundary
if (x < 0 || y < 0 || x >= size || y >= size)
continue;
// Check if wall or already visited
let value = chart[x][y];
if (value != "W" && value != "*")
toVisit.add([x, y]);
}
}
return false;
}</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h2><code>Set</code> makes for a slow stack</h2>\n<p>Your use of a <code>Set</code> rather than a stack (array) is slowing everything down. The hashing function needed for <code>Set</code> to add delete and check items is expensive compared to pushing and popping from a stack.</p>\n<p>JS does not like managing memory, allocations are expensive. If you use a stack you don't need to shrink it, rather just keep a pointer to the current stack position. That way if it shrinks below half its size it does not need relocation. You only get reallocation of the array each time it grows over double its size and never repeated.</p>\n<p>Creating complex object, like arrays is far slower than creating primitive types. The <code>for</code> loop you use needs to create a new array for each position moved to. Every time you add to the <code>toVisit</code> set you create a new array. This all adds up.</p>\n<p>Even creating the array <code>chart</code> populating it with characters from from the maze string is overly complex and can be avoided.</p>\n<h2>Example</h2>\n<p>The example avoids creating anything by basic types in the while loop. Avoids repeated calculations. Uses <code>stackPos</code> to track the size of the stack rather than push and pop from the stack. For quicker indexing the map is a flat array and coordinates are handled as triplets {x, y, idx}</p>\n<p>I would guess its about 10 times faster (depending on the maze complexity) I did not have a maze to test it on so I hope it works :)</p>\n<pre><code>function pathFinder(maze) {\n const stack = [], rows = maze.split("\\n");\n const size = rows.length, size2 = size * 2, exit = size - 1;\n const map = new Array(size * size);\n const checkMove = (x, y, idx) => {\n if (x === exit && y === exit) { return foundExit = true } \n if (x < 0 || x > exit || y < 0 || y > exit || rows[y][x] === "W") { return false }\n if (map[idx] === undefined) {\n map[idx] = 1;\n stack[stackPos++] = x;\n stack[stackPos++] = y; \n }\n return false;\n }\n var x, y, idx, stackPos = 0, foundExit = false;\n\n checkMove(0, 0, 0)\n while (stackPos) {\n y = stack[--stackPos];\n x = stack[--stackPos] + 1; // add one to check next position\n idx = x + y * size;\n if (checkMove(x, y, idx)) { break }\n x -= 2;\n idx -= 2;\n if (checkMove(x++, y, idx++)) { break }\n y += 1;\n idx += size;\n if (checkMove(x, y, idx)) { break }\n if (checkMove(x, y - 2, idx - size2)) { break }\n }\n return foundExit;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:52:44.137",
"Id": "229576",
"ParentId": "229564",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229576",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:43:56.540",
"Id": "229564",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"depth-first-search"
],
"Title": "Maze path finder using Depth-First Search algorithm"
}
|
229564
|
<p>I'm new to C#, I programmed a little in Java in the past. I had the two previous exercises reviewed here (<a href="https://codereview.stackexchange.com/questions/229525/codilitys-permutation-check-in-c">permCheck</a>, <a href="https://codereview.stackexchange.com/questions/229371/codility-cyclic-rotation-in-c">cyclicRotation</a>, with a 100% score, just like this one), and I'm applying what the accepted answers contributed to me.</p>
<p>Even though the site expects names like <code>public int solution(int X, int[] A)</code>, I refactored the code after it was accepted, and applied those contributions I mentioned.</p>
<p>Is this how professional code should look like in terms of quality, or are there still things to improve in solutions of easy exercises like this written by me?</p>
<blockquote>
<p><em><strong>Task description</strong></em></p>
<hr />
<p>A small frog wants to get to the other side of a river. The frog is
initially located on one bank of the river (position 0) and wants to
get to the opposite bank (position X+1). Leaves fall from a tree onto
the surface of the river.</p>
<p>You are given an array A consisting of N integers representing the
falling leaves. A[K] represents the position where one leaf falls at
time K, measured in seconds.</p>
<p>The goal is to find the earliest time when the frog can jump to the
other side of the river. The frog can cross only when leaves appear at
every position across the river from 1 to X (that is, we want to find
the earliest moment when all the positions from 1 to X are covered by
leaves). You may assume that the speed of the current in the river is
negligibly small, i.e. the leaves do not change their positions once
they fall in the river.</p>
<p>For example, you are given integer X = 5 and array A such that:</p>
<p>A[0] = 1<br>
A[1] = 3<br>
A[2] = 1<br>
A[3] = 4<br>
A[4] = 2<br>
A[5] = 3 <br>
A[6] = 5<br>
A[7] = 4 <br>
In second 6, a leaf falls into position 5. This is
the earliest time when leaves appear in every position across the
river.</p>
<p>Write a function:</p>
<p>class Solution { public int solution(int X, int[] A); }</p>
<p>that, given a non-empty array A consisting of N integers and integer
X, returns the earliest time when the frog can jump to the other side
of the river.</p>
<p>If the frog is never able to jump to the other side of the river, the
function should return −1.</p>
<p>For example, given X = 5 and array A such that:</p>
<p>A[0] = 1<br>
A[1] = 3 <br>
A[2] = 1<br />
A[3] = 4<br />
A[4] = 2<br />
A[5] = 3<br />
A[6] = 5<br />
A[7] = 4 <br>
the function should return 6, as explained above.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N and X are integers within the range [1..100,000]; each element of
array A is an integer within the range [1..X].</p>
</blockquote>
<pre><code>/// <summary>
/// Check if a given array contains the integers 1..N
/// </summary>
/// <returns>
/// -1 if <paramref name="fallenLeaves"/> does not contain all integers
/// 1..N, where N = <paramref name="requiredAmountOfLeaves"/>
/// a possitive int i, if the required amount of ints were present at
/// <paramref name="fallenLeaves"/>
/// </returns>
const int FROG_CANT_JUMP_TO_THE_OTHER_SIDE = -1;
public static int GetSecondsRequired
(int requiredAmountOfLeaves, int[] fallenLeaves)
{
bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
int espectedSum = 0, correctSum = 0;
for (int i = 1; i <= fallenLeaves.Length; i++)
{
if (i <= requiredAmountOfLeaves)
//get summatory of 1..N
correctSum += i;
if (fallenLeaves[i - 1] <= requiredAmountOfLeaves &&
!leavesAsSteps[fallenLeaves[i - 1]])
{
//accumulate where the expected leaf fell and set its location to true
espectedSum += fallenLeaves[i - 1];
leavesAsSteps[fallenLeaves[i - 1]] = true;
}
if (espectedSum == correctSum && i >= requiredAmountOfLeaves)
//if all the espected leaves fell, then return the array's
//index where the last expected leaf was found
return i - 1;
}
return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}
</code></pre>
|
[] |
[
{
"body": "<h2>Readability</h2>\n<ul>\n<li><p>The code needs more spacing. Considering the comments, the indentation and the ifs, it's hard to read without some good old empty lines.</p>\n</li>\n<li><p>Use brackets when using conditions, especially if you have comments above your single line, it gets really confusing. Also, the readability is increased <strong>and</strong>, the biggest factor, you'll avoid <a href=\"https://embeddedgurus.com/barr-code/2014/03/apples-gotofail-ssl-security-bug-was-easily-preventable/\" rel=\"noreferrer\">weird bugs</a>.</p>\n</li>\n<li><p>If you really don't want to use brackets, at least indent your comments so it's clear the line under it is still into the <code>if</code>.</p>\n</li>\n<li><p>Considering that we have your explanation of the problem, we can understand pretty clearly what your variable names mean. But still... it could be improved or at least well documented. <code>fallenLeaves</code> doesn't represent fallen leaves, it represent when leaves are falling at which position. <code>expectedSum</code> and <code>correctSum</code> don't mean much, to a point I'm wondering if they are well initialized.</p>\n</li>\n</ul>\n<p><strong>Result for now :</strong></p>\n<h1></h1>\n<pre><code>public static int GetSecondsRequired(int requiredAmountOfLeaves, int[] fallenLeaves)\n{\n bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];\n int espectedSum = 0, correctSum = 0;\n\n for (int i = 1; i <= fallenLeaves.Length; i++)\n {\n if (i <= requiredAmountOfLeaves)\n {\n //get summatory of 1..N\n correctSum += i;\n }\n\n if (fallenLeaves[i - 1] <= requiredAmountOfLeaves &&\n !leavesAsSteps[fallenLeaves[i - 1]])\n {\n //accumulate where the expected leaf fell and set its location to true\n espectedSum += fallenLeaves[i - 1];\n leavesAsSteps[fallenLeaves[i - 1]] = true;\n }\n \n if (espectedSum == correctSum && i >= requiredAmountOfLeaves)\n {\n //if all the espected leaves fell, then return the array's \n //index where the last expected leaf was found\n return i - 1;\n }\n }\n\n return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;\n}\n</code></pre>\n<h2>Algorithm</h2>\n<ul>\n<li>You use <code>i - 1</code> everywhere but one place, it would be smarter to reverse this. Use <code>i</code> everywhere and <code>i + 1</code> at one place.</li>\n<li>You use the accessor <code>fallenLeaves[i]</code> often, you should consider storing it in a variable. It will make the code more readable. So : <code>int currentFallenLeaf = fallenLeaves[i];</code></li>\n<li>The usage of <code>expectedSum</code> and <code>correctSum</code> is too complicated for the problem at hand. You don't need to check the sum, only that the number of <code>true</code> elements in <code>leavesAsSteps</code> (minus one because of the zero index) equals <code>requiredAmountOfLeaves</code>.</li>\n<li>You could check right at the beginning of the loop if you already marked the "leaf step" as <code>true</code> and that the leaf is valid, so that you don't do useless work.</li>\n</ul>\n<h1></h1>\n<pre><code>public static int GetSecondsRequired(int requiredAmountOfLeaves, int[] fallenLeaves)\n{\n // You should comment why there's a + 1 here.\n bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];\n int numberOfFallenLeaves = 0;\n\n for (int i = 0; i < fallenLeaves.Length; i++)\n {\n int currentFallenLeaf = fallenLeaves[i];\n\n // Have we already checked this number?\n // Is the leaf number out of range?\n // If so, let's just stop right there for this leaf.\n if (currentFallenLeaf > requiredAmountOfLeaves \n || leavesAsSteps[currentFallenLeaf])\n {\n continue;\n }\n\n numberOfFallenLeaves++;\n leavesAsSteps[currentFallenLeaf] = true; \n\n // Have we marked all our leaves? We're done.\n if (numberOfFallenLeaves == requiredAmountOfLeaves)\n {\n return i;\n }\n }\n\n return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:21:53.167",
"Id": "229574",
"ParentId": "229566",
"Score": "12"
}
},
{
"body": "<p>Another way of using Set uniqueness feature is described below:</p>\n<p>using System;</p>\n<p>using System.Collections.Generic;</p>\n<p>class Solution {\npublic int solution(int X, int[] A) {</p>\n<pre><code> var uniques = new HashSet<int>();\n for (int i = 0; i < A.Length; i++)\n {\n if (!uniques.Contains(A[i]))\n {\n uniques.Add(A[i]);\n }\n if (uniques.Count == X)\n { \n return i;\n }\n }\n return -1;\n}\n</code></pre>\n<p>}</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T18:46:05.417",
"Id": "496600",
"Score": "3",
"body": "[Just presenting an alternative solution is no *code review*](https://codereview.stackexchange.com/help/how-to-answer) - *why/how* is the alternative better? (Why not unconditionally add `A[i]` to `uniques`?)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:37:56.890",
"Id": "252114",
"ParentId": "229566",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "229574",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T13:55:57.047",
"Id": "229566",
"Score": "10",
"Tags": [
"c#",
"beginner",
"programming-challenge",
"array",
"combinatorics"
],
"Title": "Earliest time frog can jump to the other side of a river in C#"
}
|
229566
|
<p>Given a start and end of a range as string, for example:</p>
<pre><code>String start = "1230000";
String end = "1285999";
</code></pre>
<p>Generate the shortest list possible with prefixes that include the whole range,
so that for any number from the given range there is a list elemnet which can be used as a prefix. For above example the list would contain:</p>
<pre><code> 123,124,125,126,127,1280,1281,1282,1283,1284,1285
</code></pre>
<p>Explanation </p>
<p>The length of the strings may vary (6 - 12) but <code>start.length()</code> and <code>end.length()</code> are always equal.
The above range can be manually divided into the sub ranges:</p>
<pre><code> //1230000 - 1239999
//1240000 - 1249999
//1250000 - 1259999
//1260000 - 1269999
//1270000 - 1279999
//1280000 - 1289999 this range is not completly included so make the ranges smaller with a factor 10
//1280000 - 1280999
//1281000 - 1281999
//1282000 - 1282999
//1283000 - 1283999
//1284000 - 1284999
//1285000 - 1285999
</code></pre>
<p>By storing the common substring of each start and end number of the subranges one can easliy validiate that any given number from the range starts with 123,124,125,126,127,1280,1281,1282,1283,1284 or 1285.</p>
<p>Here is a very naive but working solution to print the prefixes:</p>
<pre><code>public static void main(String[] args) {
String start = "1230000";
String end = "1285999";
while(start.charAt(start.length()-1) == '0' && end.charAt(start.length()-1) == '9'){
start = start.substring(0,start.length()-1);
end = end.substring(0,end.length()-1);
}
long st = Long.parseLong(start);
long en = Long.parseLong(end);
for(long i = st; i <= en; ){
if(i % 1000 == 0 && i + 999 <= en){
System.out.println(i/1000);
i = i + 1000;
}
else if(i % 100 == 0 && i + 99 <= en){
System.out.println(i/100);
i = i + 100;
}
else if(i % 10 == 0 && i + 9 <= en){
System.out.println(i/10);
i = i + 10;
}
else {
System.out.println(i);
i = i + 1;
}
}
}
</code></pre>
<p>For some not so nice ranges like the above I have to extend my for loop:</p>
<pre><code>public static void main(String[] args) {
String start = "1279995";
String end = "1285999";
while(start.charAt(start.length()-1) == '0' && end.charAt(start.length()-1) == '9'){
start = start.substring(0,start.length()-1);
end = end.substring(0,end.length()-1);
}
long st = Long.parseLong(start);
long en = Long.parseLong(end);
for(long i = st; i <= en; ){
if(i % 1000000 == 0 && i + 999999 <= en){
System.out.println(i/1000000);
i = i + 1000000;
}
else if(i % 100000 == 0 && i + 99999 <= en){
System.out.println(i/100000);
i = i + 100000;
}
else if(i % 10000 == 0 && i + 9999 <= en){
System.out.println(i/10000);
i = i + 10000;
}
else if(i % 1000 == 0 && i + 999 <= en){
System.out.println(i/1000);
i = i + 1000;
}
else if(i % 100 == 0 && i + 99 <= en){
System.out.println(i/100);
i = i + 100;
}
else if(i % 10 == 0 && i + 9 <= en){
System.out.println(i/10);
i = i + 10;
}
else {
System.out.println(i);
i = i + 1;
}
}
}
</code></pre>
<p>Which I found not very nice. Any ideas how to optimise my approach or do some one have another approach (I am open to everything, Regex, streams, recursion .. )?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:22:35.243",
"Id": "446600",
"Score": "0",
"body": "Do they need to be strings? Can they be converted to `long`? What's the maximum value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:23:45.587",
"Id": "446601",
"Score": "1",
"body": "Seems that your code assumes that they'll fit into an integer, which is even smaller than a `long`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:36:04.313",
"Id": "446609",
"Score": "0",
"body": "@Reinderien Sorry. Integer.parseInt was a typo. Should be Long.parseLong. I'll edit my post. I need the result as List<String> but it is absolutly fine to use other types somewhere in between for the values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:39:29.710",
"Id": "446611",
"Score": "1",
"body": "I don't understand the problem statement. For the first example, wouldn't a single prefix of `1` cover all of the numbers in the range?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:04:04.570",
"Id": "446623",
"Score": "1",
"body": "My guess is that, rather than `Generate the shortest list possible with prefixes that include the whole range,` based on the example, the problem should state `Generate the shortest list possible with prefixes that include ONLY the whole range and nothing outside of it`."
}
] |
[
{
"body": "<p>Even the “extended version” does not handle the cases where <code>start</code> and <code>end</code> have more than 6 trailing zeros in common. Instead of hard-coding those ranges and a long <code>if/else if/...</code> statement you can determine the largest fitting range dynamically in a loop:</p>\n\n<pre><code>for (long i = st; i <= en; ) {\n // Determine `range` as largest power of 10 with `i % range == 0`\n // and `i + range - 1 <= en`:\n int range = 1;\n while (range <= i && i % range == 0 && i + range - 1 <= en) {\n range *= 10;\n }\n range /= 10;\n\n System.out.println(i / range); \n i += range;\n}\n</code></pre>\n\n<p>Removing common zeros/nines is more efficiently done in integer arithmetic instead of string manipulation:</p>\n\n<pre><code>while (st % 10 == 0 && en % 10 == 9) {\n st /= 10;\n en /= 10;\n}\n</code></pre>\n\n<p>I would move the computation from <code>main()</code> into a separate function and separate it from the I/O. That increases the clarity of the program and allows to add test cases more easily. In a comment you said that you need the result as <code>List<String></code>:</p>\n\n<pre><code>public static List<String> computePrefixes(long start, long end) {\n List<String> prefixes = new ArrayList<String>();\n\n while (start % 10 == 0 && end % 10 == 9) {\n start /= 10;\n end /= 10;\n }\n\n for (long i = start; i <= end; ) {\n // Determine `range` as largest power of 10 with `i % range == 0`\n // and `i + range - 1 <= en`:\n int range = 1;\n while (range <= i && i % range == 0 && i + range - 1 <= end) {\n range *= 10;\n }\n range /= 10;\n\n prefixes.add(String.valueOf(i / range));\n i += range;\n }\n\n return prefixes;\n}\n\npublic static void main(String[] args) {\n String start = \"1230000\";\n String end = \"1285999\";\n\n long st = Long.parseLong(start);\n long en = Long.parseLong(end);\n List<String> prefixes = computePrefixes(st, en);\n System.out.println(prefixes);\n}\n</code></pre>\n\n<p>You may also want to check the validity of the parameters (<code>1 <= start <= end</code>).</p>\n\n<p>Finally note that there is still a problem with numbers close to <code>Long.MAX_VALUE</code> because the calculations can overflow. If that is an issue then the range calculations and comparisons have to be done more carefully:</p>\n\n<pre><code>public static List<String> computePrefixes(long start, long end) {\n List<String> prefixes = new ArrayList<String>();\n\n while (start % 10 == 0 && end % 10 == 9) {\n start /= 10;\n end /= 10;\n }\n\n for (long i = start; ; ) {\n // Determine `range` as largest power of 10 with `i % range == 0`\n // and `i + range - 1 <= end`:\n int range = 1;\n while (range <= Long.MAX_VALUE / 10 && range <= i && i % range == 0 && range - 1 <= end - i) {\n range *= 10;\n }\n range /= 10;\n\n prefixes.add(String.valueOf(i / range));\n if (i == end) {\n break;\n }\n i += range;\n }\n\n return prefixes;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T07:46:01.513",
"Id": "446739",
"Score": "0",
"body": "Thank you so much for taking the time to thoroughly identify all flaws in my code. Thanks also for the hints and clear explanations. I have learned a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:15:23.330",
"Id": "229591",
"ParentId": "229567",
"Score": "1"
}
},
{
"body": "<p>@MartinR's answer is good, but I disagree on the choice of returning a list of strings. They should be maintained as <code>long</code> until the output stage. The return type can be made</p>\n\n<pre><code>public static List<Long>\n</code></pre>\n\n<p>which, if you set <code>prefixes</code> to be a <code>List<Long></code>, requires that the call to <code>String.valueOf</code> be removed.</p>\n\n<p>In your <code>main</code> method, the rest of the code does not need to change. The advantage of leaving this as <code>Long</code> is that if you ever need to do further processing, it's much easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T21:12:56.617",
"Id": "446689",
"Score": "0",
"body": "I agree ..... :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T07:47:19.243",
"Id": "446740",
"Score": "0",
"body": "Thanks for mentioning that. I'll keep it in mind."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:37:22.577",
"Id": "229595",
"ParentId": "229567",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229591",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:04:21.877",
"Id": "229567",
"Score": "3",
"Tags": [
"java"
],
"Title": "divide a range of numbers into groups of 10, 100, 1000, 10000 and so on"
}
|
229567
|
<p>I have an implementation of the <code>sqrt</code> function that uses a combination of IEEE 754, packed bitfields, and the Newton-Raphson algorithm:</p>
<p><code>decompose.h</code>:</p>
<pre><code>#ifndef DECOMPOSE_H
#define DECOMPOSE_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include <float.h>
#define MANTISSA_SIZE 52
#define EXPONENT_SIZE 11
#define EXPONENT_BIAS 0x3ff
#define TYPE double
#define TYPE_MIN DBL_MIN
#define TYPE_MAX DBL_MAX
#define NAME_SFX(name) name
typedef unsigned long long mantissa;
typedef unsigned short exponent;
typedef unsigned char sign;
#include "decompose_generic.h"
#ifdef __cplusplus
}
#endif
#endif
</code></pre>
<p><code>decompose_generic.h</code>:</p>
<pre><code>#ifndef DECOMPOSE_GENERIC_H
#define DECOMPOSE_GENERIC_H 1
#ifdef __cplusplus
extern "C" {
#endif
#define SIGN_SIZE 1
union decompose {
TYPE f;
struct decompose_s {
mantissa m:MANTISSA_SIZE;
exponent e:EXPONENT_SIZE;
sign s:SIGN_SIZE;
} __attribute__((packed)) o;
};
static inline union decompose decompose(TYPE f)
{
union decompose result;
result.f = f;
return result;
}
#define is_nan(x) NAME_SFX(isnan)(x)
#ifdef __cplusplus
}
#endif
#endif
</code></pre>
<p><code>sqrt.c</code>:</p>
<pre><code>#include <math.h>
#include <errno.h>
#include "decompose.h"
TYPE NAME_SFX(sqrt)(TYPE a)
{
TYPE result_old2 = 0;
unsigned short c = 0;
union decompose r = decompose(a);
if(a < -(TYPE)0)
{
errno = EDOM;
return NAME_SFX(nan)("");
}
if(a == (TYPE)0 || is_nan(a) || a > TYPE_MAX)
{
return a;
}
/* Divide the exponent by 2 */
r.o.e -= EXPONENT_BIAS;
r.o.e = (r.o.e & 1) | (r.o.e >> 1);
r.o.e += EXPONENT_BIAS;
/* Newton-Raphson */
while(result_old2 != r.f)
{
if(c % 2 == 0) result_old2 = r.f;
r.f -= (r.f*r.f-a)/(2*r.f);
c++;
}
return r.f;
}
</code></pre>
<p>What I'm looking for:</p>
<ul>
<li><p>Are there any efficiency problems?</p></li>
<li><p>Are there any accuracy problems?</p></li>
<li><p>Are there any other miscellaneous things that I can improve?</p></li>
</ul>
<p>As far as I've tested, this is as accurate as possible. It even matches the results from the GNU C library.</p>
<p>One note: This is part of a modular system. There will be a <code>decompose.h</code> for each floating point type (<code>float</code>, <code>double</code>, <code>long double</code>), and they all include <code>decompose_generic.h</code>.</p>
<p>I'm slightly new to this area of C (math, IEEE 754), but not so new that I'd add the <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged 'beginner'" rel="tag">beginner</a> tag.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:39:24.060",
"Id": "446610",
"Score": "9",
"body": "It's a shame this isn't C++, where you could check that the floating-point representation matches your expectation using `std::numeric_limits<T>::is_iec559`. I don't know of an equivalent test for C, other than separately checking all the macros in `<float.h>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-19T17:32:14.120",
"Id": "472446",
"Score": "2",
"body": "@TobySpeight `__STDC_IEC_559__`"
}
] |
[
{
"body": "<h2>Modular odd check</h2>\n\n<p>The compiler is likely to do this anyway, but can't</p>\n\n<pre><code>if(c % 2 == 0)\n</code></pre>\n\n<p>be</p>\n\n<pre><code>if (!(c & 1))\n</code></pre>\n\n<p>?</p>\n\n<h2>Factoring</h2>\n\n<p>Isn't</p>\n\n<pre><code>r.f -= (r.f*r.f-a)/(2*r.f);\n</code></pre>\n\n<p>equivalent to:</p>\n\n<pre><code>r.f = (r.f + a/r.f)/2?\n</code></pre>\n\n<h2>Optimization</h2>\n\n<p>Depending on which compiler you're using and what flags you pass it, some of your attempted math risks modification by the optimizer, and in an implementation so closely coupled to the hardware, this might matter. Have you checked your produced assembly? Can you show us your build flags?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:39:48.017",
"Id": "446587",
"Score": "1",
"body": "Under **Factoring**: That's Newton-Raphson, it detects the amount of error and decreases it. It's not the same as `(1-a)/2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:47:12.927",
"Id": "446590",
"Score": "0",
"body": "Do you mind if I make an edit to the question showing how the code was before I preprocessed it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:47:37.203",
"Id": "446591",
"Score": "3",
"body": "Soooo. The problem isn't with my answer (and I don't think it should receive your edit, yet); it's with the code you posted. A strict interpretation of the CR policies would suggest that since there's already an answer, you can't edit your code. However, I think instead that you should edit your question to show your actual (non-preprocessed) code, and I'll then amend this answer myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:50:35.207",
"Id": "446593",
"Score": "2",
"body": "@Reinderien Thanks. I've added a clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:04:26.880",
"Id": "446596",
"Score": "1",
"body": "Re. factoring: So my first stab at the math was wrong, and I modified it to reflect reality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:25:05.350",
"Id": "446602",
"Score": "1",
"body": "The second has two divisions while the first has one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:26:24.610",
"Id": "446603",
"Score": "1",
"body": "Produced assembly seems fine, GCC with optimization levels three and size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:29:44.237",
"Id": "446605",
"Score": "0",
"body": "The division increase would usually be a concern, but in this case the `/2` should be converted to a `>>1`, which is cheap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:33:27.233",
"Id": "446606",
"Score": "0",
"body": "You can't do bitshifts on floating-point numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:34:45.160",
"Id": "446607",
"Score": "1",
"body": "Ah, but you can! You're already assuming that you're coupled to the IEEE754 implementation, so while a blind `>>1` won't work, you can decrement the exponent directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:46:50.277",
"Id": "446614",
"Score": "0",
"body": "The compiler does automatically do the modular odd check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:20:30.540",
"Id": "446705",
"Score": "0",
"body": "`r.f = (r.f + a/r.f)/2` can be further simplified to `r.f += a/r.f; r.o.e--;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:26:30.317",
"Id": "446708",
"Score": "1",
"body": "@JL2210: `flt / 2` will reliably optimize to `flt * 0.5` because `1/2.0` is exactly representable. (`-ffast-math` is only needed to optimize division by constants that don't have exact reciprocals). So it's still just one division, with one fewer multiplication than the original. Or yes in theory a compiler could optimize it to a decrement of the exponent field, but it's not safe without checking for underflow so compilers definitely won't. Multiply by 0.5 is very efficient. (On x86/SSE2 it is possible to do it efficiently do integer math between FP ops, with only bypass-forwarding latency.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:32:34.573",
"Id": "446709",
"Score": "1",
"body": "@JL: Optimizing `if(c % 2 == 0)` to `c&1` isn't particularly useful, compilers already know how to do this. (Even though `c` is signed, comparing the `%` result against `0` means the optimization is still possible). More useful would be unrolling the source by a factor of 2 instead of conditionally doing something every other iteration. That's what you want the compiler to do anyway. (Use an `if(!something)break` to replace the `while(something)` loop condition, or just let it always do an even number of Newton iterations if that might be more efficient than an extra check.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:33:45.460",
"Id": "446710",
"Score": "0",
"body": "@JL: or really, making the iteration count a compile-time constant so it can be fully unrolled makes a lot of sense, if your initial approximation can be accurate enough for every possible case. (Like in @ Rainer P's answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:57:24.743",
"Id": "446987",
"Score": "3",
"body": "I immediately know what `if(c % 2 == 0)` does, but I have to think multiple times to figure out what `if (!(c & 1))` does. That's premature optimization and IMHO violates clean code rules (KISS)."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:37:55.037",
"Id": "229575",
"ParentId": "229573",
"Score": "4"
}
},
{
"body": "<p>This answer uses pointer-casting for type-punning just to save space. In practice keep using your union (safe in ISO C99, and in C++ as a GNU and MSVC extension) or memcpy (safe in C and C++). This pointer-casting is only safe in MSVC, or GNU-compatible compilers with <code>-fno-strict-aliasing</code></p>\n\n<h1>Initial approximation</h1>\n\n<p>Packed bit fields are not only unnecessary here, they make the result worse. You do something along the lines of:</p>\n\n<pre><code>uint64_t i = *(uint64_t*)&f; // double to int\ni = i - (1023 << 52); // remove IEEE754 bias\ni = i >> 1; // divide exponent by 2\ni = i + (1023 << 52); // add IEEE754 bias\n</code></pre>\n\n<p>If you change the order of operations, you can handle the biasing in a single constant:</p>\n\n<pre><code>uint64_t i = *(uint64_t*)&f; // double to int\ni = i >> 1; // divide exponent by 2\ni = i + (1023 << 52) - (1023 << 51); // remove/add IEEE754 bias\n</code></pre>\n\n<p>The constant can then be simplified to:</p>\n\n<pre><code>uint64_t i = *(uint64_t*)&f; // double to int\ni = (i >> 1) + (1023 << 51); // all of the above\n</code></pre>\n\n<p>Note that I didn't bother to mask when shifting, so the exponent's rightmost bit drops into the mantissa, which is shifted as well. This is a feature, not a bug. The IEEE754 formats are deliberately chosen to be monotonic when interpreted as integers, so carry-overs between exponent and mantissa are explicitly allowed.</p>\n\n<p>With my approximation, the mapping is as follows (linear mapping within intervals):</p>\n\n<pre><code>original number is exponent manitssa orig interval\nexponent in interval in sqrt first bit maps to\n 0 [ 1.0, 2.0 ) 0 0 [ 1.0, 1.5 )\n 1 [ 2.0, 4.0 ) 0 1 [ 1.5, 2.0 )\n 2 [ 4.0, 8.0 ) 1 0 [ 2.0, 3.0 )\n 3 [ 8.0, 16.0 ) 1 1 [ 3.0, 4.0 )\n 4 [ 16.0, 32.0 ) 2 0 [ 4.0, 6.0 )\n</code></pre>\n\n<p>With your code, the mapping is (also linear within intervals):</p>\n\n<pre><code>original number is exponent orig interval\nexponent in interval in sqrt maps to\n 0 [ 1.0, 2.0 ) 0 [ 1.0, 2.0 )\n 1 [ 2.0, 4.0 ) 0 [ 1.0, 2.0 )\n 2 [ 4.0, 8.0 ) 1 [ 2.0, 4.0 )\n 3 [ 8.0, 16.0 ) 1 [ 2.0, 4.0 )\n 4 [ 16.0, 32.0 ) 2 [ 4.0, 8.0 )\n</code></pre>\n\n<h1>Newton-Raphson</h1>\n\n<p>Given a good approximation, Newton-Raphson doubles the number of significant digits on each iteration (quadratic convergence). The above approximation provides about 4 bits of accuracy (max error: 6% or ~1/16), so 3 Newton-Raphson iterations are required for single and 4 iterations for double precision.</p>\n\n<p>The entire code could look like this:</p>\n\n<pre><code>float sqrtf(float x)\n{\n float y = x;\n // Approximation\n uint32_t* i = (uint32_t*)&x;\n *i = (*i >> 1) + (127 << 22);\n // Newton-Raphson\n x = (x + y/x) / 2;\n x = (x + y/x) / 2;\n x = (x + y/x) / 2;\n return x;\n}\n\ndouble sqrt(double x)\n{\n double y = x;\n // Approximation\n uint64_t* i = (uint64_t*)&x;\n *i = (*i >> 1) + (1023 << 51);\n // Newton-Raphson\n x = (x + y/x) / 2;\n x = (x + y/x) / 2;\n x = (x + y/x) / 2;\n x = (x + y/x) / 2;\n return x;\n}\n</code></pre>\n\n<h1>Subnormals and other hazards</h1>\n\n<p>You already have special handling for <code>nan</code>, <code>inf</code>, <code>0</code> and <code>x < 0</code>, which is good, but we need to handle subnormal numbers as well. The code, both yours and mine, fails when confronted with such numbers. As a remedy, I suggest you scale subnormal numbers by <code>2^200</code> and scale the result by <code>2^-100</code>. I chose <code>2^200</code> because it safely brings all subnormals back into normal range for all precisions, including quad, but other numbers work equally well (but only powers of two retain full precision).</p>\n\n<p>Also observe that my code relies on IEEE754 properties. It doesn't work for non-IEEE754 numbers, most notably x86's 80bit <code>extended double</code> format. If you want to handle such numbers, you can convert them to <code>float</code> or <code>double</code> for the approximation step and back to <code>extended double</code> for Newton-Raphson.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:59:38.057",
"Id": "446642",
"Score": "0",
"body": "This won't work for 80-bit long double, which can't be represented as an integer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:39:14.617",
"Id": "446667",
"Score": "2",
"body": "Also note that this violates strict aliasing and is undefined behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:40:59.887",
"Id": "446669",
"Score": "0",
"body": "How many bits of accuracy does the current implementation provide?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:48:40.833",
"Id": "446672",
"Score": "4",
"body": "Your approximation is off by 41% at worst, that's about 1bit. (with my approximation it's ~6%) - @JL2210"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:50:15.130",
"Id": "446673",
"Score": "0",
"body": "How can I have something similar to your implementation that 1) doesn't violate strict aliasing and 2) works for `long double`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:19:04.063",
"Id": "446681",
"Score": "0",
"body": "I don't think the initial approximation, the way it is now, will work for a `long double`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T00:22:07.260",
"Id": "446698",
"Score": "5",
"body": "`*(uint64_t*)&f` is undefined behaviour in ISO C. It's only well-defined in MSVC or `gcc -fno-strict-aliasing`. , @JL2210 used a union to type-pun because that's well-defined in ISO C99. (But in C++ only as a GNU extension. They should probably have used `memcpy` since they bothered to include `extern \"C\" {}` stuff in case it's compiled as C++)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T00:32:39.673",
"Id": "446699",
"Score": "3",
"body": "@JL2210 and Rainer:: The other problem with 80-bit `long double` is that the leading 1 or 0 in the significand (aka mantissa) is *explicit*, not implied by the exponent field being non-zero. https://en.wikipedia.org/wiki/Extended_precision#x86_extended_precision_format So shifting a bit from the exponent into the mantissa could be a big problem, potentially creating a non-normalized value that isn't a subnormal. I forget what x86/x87 hardware does in that case. If you were using C++, you could use a `std::bitset<sizeof(T)*CHAR_BIT>`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T00:43:35.987",
"Id": "446700",
"Score": "0",
"body": "@PeterCordes I should probably just remove the `extern \"C\"` baggage. I'm not intending for this to be compiled in C++, anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:44:43.947",
"Id": "446768",
"Score": "0",
"body": "@RainerP. What would you consider a \"subnormal\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:55:16.117",
"Id": "446771",
"Score": "0",
"body": "@JL2210 - An [IEEE754 subnormal number](https://en.wikipedia.org/wiki/Denormal_number) is a number too small to be represented. These are encoded in a fixed-point manner and the exponent field is zeroed out and meaningless. Zero is a subnormal number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T22:19:52.743",
"Id": "446897",
"Score": "0",
"body": "How do I scale these?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:32:56.270",
"Id": "447042",
"Score": "0",
"body": "@JL2210 - You can distinguish subnormals using `is_normal()` (similar to `is_nan()`) and scale them with an ordinary multiplication. The FPU handles all the nasty stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:19:16.657",
"Id": "447047",
"Score": "0",
"body": "@RainerP. You mean `isnormal`? I defined `is_nan` myself as a type-generic macro. I sadly don't have `isnormal` available anyway. I haven't gotten that far in my math implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-13T07:11:30.043",
"Id": "453556",
"Score": "0",
"body": "`(1023 << 52)` is UB. Recommend `(1023ull << 52)`"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:48:19.257",
"Id": "229578",
"ParentId": "229573",
"Score": "18"
}
},
{
"body": "<p>I don't see why you define this constant yourself:</p>\n\n<blockquote>\n<pre><code>#define MANTISSA_SIZE 52\n</code></pre>\n</blockquote>\n\n<p>Given we already assume that <code>FLT_RADIX</code> is 2, we can use the appropriate macro from <code><float.h></code> (<code>DBL_MANT_DIG</code> for <code>double</code>, etc.).</p>\n\n<hr>\n\n<p>I think there's danger of integer overflow here:</p>\n\n<blockquote>\n<pre><code>/* Divide the exponent by 2 */\nr.o.e -= EXPONENT_BIAS;\nr.o.e = (r.o.e & 1) | (r.o.e >> 1);\nr.o.e += EXPONENT_BIAS;\n</code></pre>\n</blockquote>\n\n<p>We'd be better extracting into a big enough temporary, and applying the exponent bias to that:</p>\n\n<pre><code>int e = r.o.e - EXPONENT_BIAS;\ne = (e & 1) | (e >> 1);\nr.o.e = e + EXPONENT_BIAS;\n</code></pre>\n\n<p>It might be possible to shift in place and then correct using half the bias; I haven't checked whether that's equivalent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:10:44.083",
"Id": "446627",
"Score": "0",
"body": "Signed bit-shifting isn't well-defined. I don't think the second half of your answer is valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:33:37.763",
"Id": "446635",
"Score": "0",
"body": "I agree with the top point, but it would be `DBL_MANT_DIG-1`, not `DBL_MANT_DIG`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:04:25.190",
"Id": "446701",
"Score": "0",
"body": "@JL2210: Is right-shifting a signed bitfield any better defined than a signed `int`? Doesn't your current code still rely on `>>` being an arithmetic right shift that shifts in `1`s for negative exponents? Yes it's implementation-defined whether it's arithmetic or logical (not undefined). However your code uses GNU C `__attribute__((packed))` so you actually *can* rely on arithmetic right shift if you're intentionally writing in GNU C, not ISO C. https://gnu.huihoo.org/gcc/gcc-4.9.4/gcc/Integers-implementation.html specifies that \"Signed ‘>>’ acts on negative numbers by sign extension.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:05:43.053",
"Id": "446702",
"Score": "0",
"body": "@PeterCordes My bitfields aren't signed. Take a look at the `typedef`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:07:38.230",
"Id": "446703",
"Score": "1",
"body": "@JL2210: Yeah, just noticed that. I assumed they would be signed because unsigned right-shift of the 2's complement exponent (after unbiasing) doesn't make sense, does it? A negative exponent (small magnitude float) becomes a very large positive exponent (close-ish to DBL_MAX) after your logical right shift of the exponent field. Or am I missing something and your function does work correctly for inputs like `0.0001`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:15:53.590",
"Id": "446704",
"Score": "0",
"body": "@PeterCordes Yep, you're right. I get absurd output with small inputs on the original."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:22:45.690",
"Id": "446706",
"Score": "2",
"body": "@JL2210: Hardware that reads the float will effectively undo the bias. It's just an encoding method; the real *value* is a 2's complement integer. That's what you're working with after undoing the bias (decoding). Yes you have to redo the encoding to make it an IEEE float again, but so what? BTW, if you were to logical right-shift without undoing the bias first, you'd make values twice as close to the smallest possible exponent value instead of twice as close to the middle value (0 after bias). So `1.0f` would become `1e-17f` or something, if FLT_MIN is about 1e-34f."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:23:36.553",
"Id": "446707",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/99070/discussion-between-jl2210-and-peter-cordes)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:52:18.247",
"Id": "229579",
"ParentId": "229573",
"Score": "8"
}
},
{
"body": "<p>FYI, in IEEE754 <code>sqrt</code> is a \"basic\" operation that's <strong>required to be correctly-rounded</strong> (rounding error <= 0.5ulp), same as + - * /. Hardware FPUs (I think) always provide sqrt if they provide the other operations, especially division which is <a href=\"https://stackoverflow.com/questions/54642663/how-sqrt-of-gcc-works-after-compiled-which-method-of-root-is-used-newton-rap\">typically implemented similarly (and with similar performance)</a>.</p>\n\n<p>NR iterations each involving a division are <em>not</em> going to be faster than HW sqrt. I think that's part of why x86's approximation instructions are for reciprocal and rsqrt, not sqrt: the Newton iteration formula for <code>1/sqrt(x)</code> doesn't involve division, so on old CPUs with very slow sqrtps compared to mulps, it was worth using <code>sqrt(x) ~= x * approx_rsqrt(x)</code>, <a href=\"https://stackoverflow.com/questions/31555260/fast-vectorized-rsqrt-and-reciprocal-with-sse-avx-depending-on-precision\">optionally with a Newton iteration on the approx_rsqrt result</a>. Maybe sometimes still worth doing that in a loop that does nothing else, but normally you should aim for more computational intensity (do more with your data while it's hot in registers; don't write loops that just load/sqrt/store).</p>\n\n<p>IDK if it's possible for your code to converge on a value that's not the correctly-rounded result, but something you should test for by checking against the implementation's <code>sqrt</code> function.</p>\n\n<p>(Call your function something else. With GCC for example, <code>sqrt</code> is a special name unless you use <code>-fno-builtin-sqrt</code>. Callers will inline the sqrt instruction on targets that have one, like x86 <code>sqrtsd</code>, only calling the libc function for inputs that need to set errno. Or never if you compile with <code>-fno-math-errno</code>, always a good idea. Math-errno is an optional feature that not all libcs support, although GNU C does. It's a pretty bad obsolete design that <a href=\"https://stackoverflow.com/questions/57673825/how-to-force-gcc-to-assume-that-a-floating-point-expression-is-non-negative/57674631#57674631\">nobody should use</a>; that's why we have <code>fenv.h</code> to check per-thread sticky FP exception flags.)</p>\n\n<hr>\n\n<h3>Wrong initial guess for inputs < 1.0</h3>\n\n<blockquote>\n<pre><code> /* Divide the exponent by 2 */\n r.o.e -= EXPONENT_BIAS;\n r.o.e = (r.o.e & 1) | (r.o.e >> 1);\n r.o.e += EXPONENT_BIAS;\n</code></pre>\n</blockquote>\n\n<p>Your exponent bitfield type is <code>unsigned short</code><sup>1</sup> so this is a logical right shift.</p>\n\n<p>But anyway, <strong>logical right shift is a bug in your initial approximation.</strong></p>\n\n<p>The exponent field is a 2's complement integer (encoded with a bias, but that's just an encoding/decoding detail you already take care of). A logical right shift of a small exponent (like for <code>0.0001</code>) will result in a large <em>positive</em> exponent from shifting in a zero. Your initial guess for <code>0.0001</code> will be something close-ish to <code>DBL_MAX</code>, way above <code>1.0</code>.</p>\n\n<p><strong>You need an arithmetic right shift of the exponent</strong> to bring it closer to the middle exponent value (unbiased) <code>0</code> or (biased) <code>127</code>. Thus bringing the magnitude of the represented value closer to <code>1.0</code>.</p>\n\n<p><em>Most</em> C implementations make the sane choice that <code>>></code> of a signed integer type is an arithmetic right shift. ISO C requires that implementations define which it is, but unfortunately leaves them the choice of logical or arithmetic. (Unlike signed left shift, it can't be UB).</p>\n\n<p>But fortunately your code is written in GNU C (not ISO C), e.g. using <code>__attribute__((packed))</code> on a struct. <strong><a href=\"https://gcc.gnu.org/onlinedocs/gcc//Integers-implementation.html\" rel=\"nofollow noreferrer\">GNU C guarantees that <code>>></code> on signed integers is arithmetic</a></strong>. (And that signed integer types are 2's complement!) So the only implementations that can compile your code are ones where <code>>></code> on an <code>int</code> does what you want.</p>\n\n<blockquote>\n <p><a href=\"https://gcc.gnu.org/onlinedocs/gcc//Integers-implementation.html\" rel=\"nofollow noreferrer\">(GCC manual, integer implementation-defined behaviour)</a>:<br>\n Signed ‘>>’ acts on negative numbers by sign extension.</p>\n</blockquote>\n\n<p>You might want to use unsigned bitfield members and unsigned arithmetic for bias/unbias. But you can safely use <code>int32_t</code> (which is guaranteed to be a 2's complement integer type), or just <code>int</code> for the temporary holding the field value for the bias/unbias calculations. Bias/unbias may cross zero (unsigned wrapping), not signed overflow.</p>\n\n<hr>\n\n<h2>Or better, use @Rainer P's method:</h2>\n\n<p>Don't unbias first, just unsigned shift and then add half the bias constant. (See his answer for how it simplifies down to that). Doing the shift before unbiasing means the exponent is unsigned so shifting in a zero is good. (I think this works right even for tiny values with biased-exponents near zero, i.e. near the smallest possible exponent encoding).</p>\n\n<p>I tried a few values on <a href=\"https://www.h-schmidt.net/FloatConverter/IEEE754.html\" rel=\"nofollow noreferrer\">https://www.h-schmidt.net/FloatConverter/IEEE754.html</a>, manually shifting the exponent and then adding 1 (with carry) to the 2nd-highest exponent bit. e.g. <code>2.3509887E-38</code> (biased exponent = <code>0b0000'0010</code>) becomes 2.1684043E-19 (biased exponent = <code>0b0100'0001</code>).</p>\n\n<p>But beware when shifting the entire bit-pattern that you don't shift in a <code>1</code> from the sign bit of <code>-0.0</code>. You are handling <code>a == 0.0</code> as a special case so you're fine there because <code>-0.0 == 0.0</code> is true. I guess you can't let <code>0.0</code> go through the main NR loop because you'd have a division by zero.</p>\n\n<hr>\n\n<p>Footnote 1:</p>\n\n<p>IDK why you'd choose <code>unsigned short</code> instead of just <code>unsigned</code> for your exponent bitfield type. The underlying type of a bitfield can be wider than the field without hurting anything, and some compilers will do math at the width of that type. So using <code>unsigned int</code> if it's wide enough is a good idea. <code>int</code> is at least 16 bits.</p>\n\n<p>Using <code>uint64_t</code> as the bitfield type can result in slow 32-bit code with some compilers (notably MSVC), but I think <code>unsigned int</code> is always fine for the exponent. Unsigned does make sense for the biased exponent.</p>\n\n<p>Fun fact: just <code>int</code> as the bitfield type leaves the signedness up to the implementation. You can use <code>signed int</code> to force signed. <a href=\"https://stackoverflow.com/questions/42527387/signed-bit-field-represetation\">https://stackoverflow.com/questions/42527387/signed-bit-field-represetation</a></p>\n\n<hr>\n\n<h3>unroll instead of checking <code>c % 2 == 0</code></h3>\n\n<p>A compiler might do this anyway, but it probably makes more sense to just unroll your loop by 2 instead of using a counter to do something special every other iteration.</p>\n\n<p>The actual Newton iteration expression is compact enough that repeating it once is probably <em>more</em> simple for humans to read than working through the <code>c++</code> and <code>if (c%2 == 0)</code> logic.</p>\n\n<p>You can handle the <code>while(foo)</code> condition as <code>if(!foo) break;</code> when unrolling, or simply leave it out and only check for leaving the loop every 2 Newton iterations, unless you need to check both possibilities to catch alternation between two values.</p>\n\n<p>(With a bad initial estimate that will take many iterations anyway, this might be worth it. Otherwise probably not, especially on a superscalar / out-of-order CPU that can be checking the branch condition in parallel with the main dependency chain which doesn't have a lot of ILP (instruction-level parallelism); mostly one long dependency chain.)</p>\n\n<hr>\n\n<h2>Pull some checks off the fast-path</h2>\n\n<p>Your version has 4 separate checks on <code>a</code> before we reach the actual work.</p>\n\n<pre><code> if(a < -(TYPE)0)\n {\n errno = EDOM;\n return NAME_SFX(nan)(\"\");\n }\n if(a == (TYPE)0 || is_nan(a) || a > TYPE_MAX)\n {\n return a;\n }\n</code></pre>\n\n<p>Instead, <strong>catch the special cases with one or two compares, and sort them out in that block, off the fast path</strong>. The performance of <code>sqrt(NaN)</code> is much much less important than the performance of <code>sqrt(1.234)</code></p>\n\n<pre><code> if(! a > (TYPE)0)\n {\n if(a == (TYPE)0 || is_nan(a))\n return a;\n // else a < 0\n errno = EDOM;\n return NAME_SFX(nan)(\"\");\n }\n if( a > TYPE_MAX)\n {\n return a;\n }\n</code></pre>\n\n<p>If you need to handle subnormals specially (at least for generating the initial approximation?), you might use <code>if (! a>=DBL_MIN)</code>. Or you could decide that your soft-float implementation simply doesn't handle subnormals.</p>\n\n<p>IDK what your goal is with this code; if it was part of a soft-float library, simply using FP add, mul, and divide seems inefficient. You'd want to optimize multiple operations together and so on.</p>\n\n<p>But if it's for HW FPUs, then I think real all FPUs will have sqrt built-in as well.</p>\n\n<p>So I assume this is just a learning exercise. So we won't get into too detail of optimizing it for any particular hardware or compiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T02:02:15.670",
"Id": "446713",
"Score": "0",
"body": "You can't have a bitfield with a size wider than the size of the type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T02:05:19.430",
"Id": "446716",
"Score": "1",
"body": "@JL2210: I know you can't have `int a:64`, that's why I said the underlying type can be *wider* (than the field) without causing a problem, not vice versa. Apparently my wording is easy to misread, will think about how to fix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T02:07:27.470",
"Id": "446717",
"Score": "0",
"body": "You said *\"Using `uint64_t` as the bitfield type can result in slow 32-bit code [...], but I think `unsigned int` is always fine\"*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T02:09:59.923",
"Id": "446719",
"Score": "1",
"body": "@JL2210: Oh. I meant always fine *for the exponent* where you were previously using `unsigned short`. Because both types have the same minimum width in ISO C. I meant that using `uint64_t e:8` could give slower-than-necessary code for the exponent. Specifically with MSVC, I was remembering writing this answer: [Unresolved external symbol \\_\\_aullshr when optimization is turned off](//stackoverflow.com/q/54719855)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:02:35.270",
"Id": "446764",
"Score": "0",
"body": "Please read my code again. It checks if `a == 0` and `return`s `a` if so. Also read the POSIX spec for the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T23:28:20.467",
"Id": "446900",
"Score": "1",
"body": "@JL2210: Oh yes, I missed that you check separately for `== 0.0`. I was assuming that you would just use one check on the fast-path to exclude both negative an NaN inputs by requiring that `x >= 0.0`. That's false for NaN so you can move the `isnan` check inside an `if` that won't run for the fast-path. So you can do `if (! x>0.0) { further checks to detect +=0.0, NaN, or negative }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:08:21.807",
"Id": "446902",
"Score": "1",
"body": "@JL2210: Updated my answer to fix that mistake you pointed out, and talk about some of the stuff I've said in comments. And more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:20:13.850",
"Id": "446905",
"Score": "0",
"body": "This actually isn't a learning exercise. This will be the fallback for the `libm` in my C library. The assembly will take longer, but first I want to check for accurate results. I also know how Intel is when it comes to accuracy in this type of thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:27:42.833",
"Id": "446906",
"Score": "1",
"body": "@JL22: Like I said at the top of my answer, `sqrt` is *required* by IEEE to be correctly-rounded, just like + - * and /. All x86 sqrt instructions do that. (Except of course `rsqrtps` which intentionally gives a fast approximation of 1/sqrt(x)). Intel's *compiler* enables fast-math by default (unlike GCC), but Intel's HW is IEEE-compliant. Perhaps you're thinking of instructions like `fsin`, which *aren't* required to be correctly rounded and which in practice have huge relative error near Pi/2. https://randomascii.wordpress.com/2014/10/09/intel-underestimates-error-bounds-by-1-3-quintillion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:32:46.497",
"Id": "446907",
"Score": "0",
"body": "(And I'm terribly unfamiliar with SIMD instructions.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:35:34.100",
"Id": "446908",
"Score": "0",
"body": "@JL2210 If it helps, there's a scalar [`rsqrtss`](https://www.felixcloutier.com/x86/rsqrtss) which is what you'd actually use if you were considering using `x * newton(approx_rsqrt(x))` as the implementation here. But of course if you were using Intel intrinsics, you'd just use `_mm_sqrt_sd` or `_mm_sqrt_ss` after converting a scalar to a `__m128d` or `__m128` vector (with the low element being the only one you care about)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:39:29.623",
"Id": "446909",
"Score": "0",
"body": "@JL2210: Possibly you could get away with using GNU C `__builtin_sqrt(x)` if you compile with -fno-math-errno. But that could emit a call to the `sqrt()` function if it decides not to inline it, so it only works on targets where GCC can inline it, and with optimization enabled. I'm not sure if there's a good way to get GCC to do this for you on every ISA it knows how to handle, instead of writing asm by hand for each platform for the libm `sqrt` implementation. You should def. do that for every major one, though, like `sqrtsd xmm0,xmm0` / `ret` for x86-64."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:41:09.973",
"Id": "446910",
"Score": "0",
"body": "Ugh, Intel syntax.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:43:09.410",
"Id": "446911",
"Score": "0",
"body": "@JL2210: What, you *like* AT&T syntax? It's trivial to translate this case, but maybe `sqrtsd %xmm0, %xmm0` ; `ret` makes you happier? Or `sqrtss` for the `float` case, of course. And `fldt 8(%rsp)` ; `fsqrt` ; ret for the `long double` case in ABIs where `long double` is 80-bit float, unlike Windows where it's the same as `double`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:45:43.903",
"Id": "446912",
"Score": "0",
"body": ":P Thanks. I understand why some people like Intel syntax, but it just seems backwards to me (probably because I used to read GCC's output before I knew about the option to change the syntax). By now, it's a habit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:53:24.457",
"Id": "446918",
"Score": "0",
"body": "@JL2210: I used to like AT&T syntax because its addressing-mode syntax mirrored the machine encoding, making it clearer which component was which. But once I started reading Intel's manuals to look up how instructions worked, mentally translating to AT&T became extra work. Also, destination on the left is like C, so you can scan down the justified column of operands and find insns that modify a given register, vs. the ragged ends of lines having the destination in AT&T. Actually typing the `%` and `$` decorations is a pain, too. Not to mention AT&T's x87 design bug (fsubr vs. fsub etc.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:56:15.700",
"Id": "446919",
"Score": "0",
"body": "@JL2210: Anyway, unlike some people I don't hate AT&T syntax. Many more people dislike AT&T syntax than dislike Intel syntax, I think. Or they're more likely to be vocal about it. It only takes me a minute to mentally change gears and think in AT&T. But most still-relevant ISAs have destination on the left in their standard syntax, unlike AT&T, PDP-11 and m68k."
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:56:52.773",
"Id": "229602",
"ParentId": "229573",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "229578",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:16:56.673",
"Id": "229573",
"Score": "24",
"Tags": [
"c",
"reinventing-the-wheel",
"numerical-methods",
"floating-point"
],
"Title": "IEEE 754 square root with Newton-Raphson"
}
|
229573
|
<p>I need better logic that would allow this search to perform quicker and more efficiently.</p>
<p>In XAML, I have a <code>DataGrid</code> and a <code>TextBox</code>. Both need to be present.</p>
<p>I'd prefer that as the user types in the <code>TextBox</code>, the <code>Grid</code> is filtered by one or more columns. Not that the user needs to click a "Submit" button (unless this is the only way).</p>
<p>My current logic takes many seconds to complete, likely because of the binding/rebinding of the UI.</p>
<p>Here is my logic:</p>
<pre><code>private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
var textBox = sender as TextBox;
_filteredView = CollectionViewSource.GetDefaultView(MainGrid.DataContext);
_filteredView.Filter = x => ((QueueData)x).ImageCode.Contains(textBox.Text) || ((QueueData)x).Product.Contains(textBox.Text);
MainGrid.DataContext = ((System.Windows.Data.ListCollectionView)_filteredView).SourceCollection;
}
</code></pre>
<p>Below is my xaml - txtSearch is the <code>TextBox</code>:</p>
<pre><code><UserControl x:Class="Wip.Presentation.ManagerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
TextElement.FontWeight="Medium"
TextElement.FontSize="14"
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto"
TextElement.Foreground="{DynamicResource MaterialDesignBody}"
Background="{DynamicResource MaterialDesignPaper}"
FontFamily="{StaticResource MaterialDesignFont}"
mc:Ignorable="d" Height="auto" Width="auto">
<UserControl.Resources>
<Style x:Key="LeftCellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Left"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto" PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
<Grid Background="Transparent" FocusManager.FocusedElement="{Binding ElementName=txtSearch}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<!-- SEARCH -->
<Label HorizontalAlignment="Left" Grid.Row="0" Name="lblSearch" Height="30" Width="150" Margin="10,0,0,0" >SEARCH (F5 to clear)</Label>
<TextBox HorizontalAlignment="Left" Grid.Row="0" Name="txtSearch" Height="30" Width="200" Margin="160,0,0,0" TextChanged="TextBox_TextChanged" CharacterCasing="Upper"/>
<DataGrid Grid.Row="1" Grid.ColumnSpan="2" Name="MainGrid" ItemsSource="{Binding}"
Sorting="MainGrid_Sorting"
SelectionChanged="MainGrid_SelectionChanged"
MouseDoubleClick="MainGrid_MouseDoubleClick"
ColumnWidth="Auto"
AlternationCount="2"
AlternatingRowBackground="DimGray"
AutoGenerateColumns="False"
AreRowDetailsFrozen="True" Margin="0,0,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="CMP" Width="50" Binding="{Binding Company, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Company)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="DIV" Width="50" Binding="{Binding Division, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Division)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="CUS" Width="75" Binding="{Binding CustomerNumber, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(CustomerNumber)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="FORMAT" Width="75" Binding="{Binding ImageCode, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(ImageCode)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="SEQ" Width="50" Binding="{Binding Sequence, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Sequence)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="ORDER #" Width="75" Binding="{Binding OrderNumber, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(OrderNumber)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="LOGO" Width="225" Binding="{Binding Logo, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Logo)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Hold Code" Width="100" Binding="{Binding HoldCode, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(HoldCode)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Order Type" Width="85" Binding="{Binding Dhotp, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Dhotp)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Comments" Width="175" Binding="{Binding Comments, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Comments)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="IMPORT DATE" Width="160" Binding="{Binding ImportDate, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(ImportDate)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="PRODUCT" Width="110" Binding="{Binding Product, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Product)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="WORKCNTR" Width="110" Binding="{Binding Product, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(WorkCenter)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="PROCESS TYPE" Width="100" Binding="{Binding ProcessType, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(ProcessType)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="PIM EMB JOB" Width="105" Binding="{Binding PimEmbJobDisplay, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(PimEmbJob)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="dgcThreadColor" Header="THREAD COLOR" Width="105" Binding="{Binding Ink, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Ink)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="dgcStitchCnt" Header="STITCH CNT" Width="105" Binding="{Binding StitchCount, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(StitchCount)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="dgcPieces" Header="PIECES" Width="105" Binding="{Binding Pieces, Mode=OneWay}" CellStyle="{StaticResource LeftCellStyle}" SortMemberPath="(Pieces)" IsReadOnly="True">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF666666" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Mark SLC" Name="mnuMarkSLC" Click="mnuMarkSLC_Click">
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Grid>
</ScrollViewer>
</UserControl>
</code></pre>
<p>Below is QueueData.cs:</p>
<pre><code>using System;
namespace Wip.ViewModels {
public class QueueData {
#region Public Properties
public string Company { get; set; }
public string Division { get; set; }
public string CustomerNumber { get; set; }
public string ImageCode { get; set; }
public int Sequence { get; set; }
public string OrderNumber { get; set; }
public string Logo { get; set; }
public int LineNumber { get; set; }
public string HoldCode { get; set; }
public string Dhotp { get; set; }
public string Comments { get; set; }
public string WorkCenter { get; set; }
public DateTime ImportDate { get; set; }
// Due Date
public string Product { get; set; }
// Ink
public int ProcessType { get; set; }
public bool ProductionEdit { get; set; }
public bool PimEmbJob { get; set; }
public string PimEmbJobDisplay { get { return (PimEmbJob == true ? "Yes" : "No"); } }
public string Ink { get; set; }
public int StitchCount { get; set; }
public int Pieces { get; set; }
// Work Center
#endregion
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:46:45.423",
"Id": "446640",
"Score": "0",
"body": "Are you sure you need to rebind the data context when using CollectionViewSource.Filter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:49:07.140",
"Id": "446641",
"Score": "0",
"body": "I am not sure at all. I hacked through the code I found on StackExchange. Are you suggesting `filteredView` is bound implicitly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:11:11.423",
"Id": "446651",
"Score": "0",
"body": "here's a tutorial: you need to bind to the source collection and use the collectionview to filter and call refresh. but you should never rebind the data context: https://grantwinney.com/using-a-textbox-and-collectionviewsource-to-filter-a-listview-in-wpf/ This tutorial is better than my answer was :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:15:39.367",
"Id": "446652",
"Score": "0",
"body": "My TextChanged now has\n\n`CollectionViewSource.GetDefaultView(MainGrid.DataContext).Filter = x => ((QueueData)x).ImageCode.Contains(textBox.Text) || ((QueueData)x).Product.Contains(textBox.Text);`\n\nIt still lags. Is that to be expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:17:56.283",
"Id": "446654",
"Score": "0",
"body": "Try the pattern from tutorial, it sets the Filter once, and refreshes on text changed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:12:48.280",
"Id": "446679",
"Score": "0",
"body": "I've tried the pattern and find it takes 300-500ms for the first letter in the search and halfs each letter afterwards, for example: 250ms for the second letter, 20-80 for the third - starting with ~108 records. Not sure where the bottleneck is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T04:19:19.350",
"Id": "446722",
"Score": "0",
"body": "Perhaps you should put a Delay on the Binding"
}
] |
[
{
"body": "<p>I would handle the data source a little different than you:</p>\n\n<p>In your code behind for the control, you can initialize in the following way:</p>\n\n<pre><code>public ManagerWindow()\n{\n InitializeComponent();\n\n _viewSource = new CollectionViewSource();\n _viewSource.Source = InitializeView();\n _viewSource.Filter += ViewSource_Filter;\n MainGrid.ItemsSource = _viewSource.View;\n}\n\nprivate void ViewSource_Filter(object sender, FilterEventArgs e)\n{\n string text = txtSearch.Text;\n QueueData data = e.Item as QueueData;\n e.Accepted = string.IsNullOrWhiteSpace(text) || (data != null && (data.ImageCode.Contains(text) || data.Product.Contains(text)));\n}\n\nCollectionViewSource _viewSource;\n</code></pre>\n\n<p>Where <code>InitializeView()</code> is a method defined by you, that must return a collection (<code>List<QueueData></code>) or something like that. But as you probably know it can be set in many other ways.</p>\n\n<p>Notice that the <code>DataContext</code> for the data grid is not set - only the <code>ItemsSource</code>.</p>\n\n<p>The change event for the text box should then look like:</p>\n\n<pre><code>private void TextBox_TextChanged(object sender, TextChangedEventArgs e)\n{\n _viewSource.View.Refresh();\n}\n</code></pre>\n\n<hr>\n\n<p>The performance problem is mainly a render/layout-problem caused by <code>\"Auto\"</code> setting for the grid row containing the data grid, so in the xaml for the control you must remove the <code>ScrollViewer</code> and define the grid as follows:</p>\n\n<pre><code> <Grid Background=\"Transparent\" FocusManager.FocusedElement=\"{Binding ElementName=txtSearch}\">\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"></RowDefinition>\n <RowDefinition Height=\"*\"></RowDefinition>\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"></ColumnDefinition>\n <ColumnDefinition Width=\"*\"></ColumnDefinition>\n </Grid.ColumnDefinitions>\n</code></pre>\n\n<p>Notice the second row definition:</p>\n\n<pre><code><RowDefinition Height=\"*\"></RowDefinition>\n</code></pre>\n\n<p>Setting <code>Height=\"*\"</code> instead of <code>\"Auto\"</code> is important because it will eliminate the need for the outer <code>ScrollViewer</code> and speed up the calculations of the dimensions of the data grid, when rendering (You may set it to a static value, but not <code>\"Auto\"</code>)</p>\n\n<hr>\n\n<p>The data grid should then be defined as:</p>\n\n<pre><code> <DataGrid Grid.Row=\"1\" Grid.ColumnSpan=\"2\" Name=\"MainGrid\"\n ScrollViewer.VerticalScrollBarVisibility=\"Auto\"\n ScrollViewer.HorizontalScrollBarVisibility=\"Auto\"\n ScrollViewer.CanContentScroll=\"True\"\n EnableRowVirtualization=\"True\"\n Sorting=\"MainGrid_Sorting\"\n SelectionChanged=\"MainGrid_SelectionChanged\"\n MouseDoubleClick=\"MainGrid_MouseDoubleClick\"\n AutoGenerateColumns=\"False\"\n AlternationCount=\"2\"\n AlternatingRowBackground=\"DimGray\"\n Margin=\"0,0,0,0\">\n</code></pre>\n\n<p>Notice the missing <code>Binding</code> for <code>ItemsSource</code>.</p>\n\n<p>With these changes everything should work smoothly and efficiently.</p>\n\n<p>You may want to experiment with <code>EnableRowVirtualization=\"True/False\"</code> to see which state is most smooth.</p>\n\n<hr>\n\n<p>You should remove the column header style on every column because they are the same and then define it in the <code>UserControl.Resources</code> as:</p>\n\n<pre><code><Style TargetType=\"DataGridColumnHeader\">\n <Setter Property=\"Background\" Value=\"#FF666666\" />\n <Setter Property=\"VerticalAlignment\" Value=\"Center\" />\n</Style>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T08:25:42.117",
"Id": "229615",
"ParentId": "229583",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:29:31.650",
"Id": "229583",
"Score": "4",
"Tags": [
"c#",
"performance",
"event-handling",
"wpf",
"xaml"
],
"Title": "More Efficient Way To Search On-Demand"
}
|
229583
|
<p>To run this program the graphics.py module that is not in the standard library is needed and can be found here <a href="https://mcsp.wartburg.edu/zelle/python/" rel="nofollow noreferrer">https://mcsp.wartburg.edu/zelle/python/</a> </p>
<p>This amateur program is for the fun of graphics and programming in itself. Im thinking it would be a rewarding hobby for me to share and use each others shared code and therefore i would like to make it more programmer friendly.</p>
<p>Thinking out loud:</p>
<ul>
<li>The equations in this program are split into different lines for understandability. </li>
<li>Is "understandability" a subcategory of readability? </li>
<li>Or do they oppose and therefore should equations be shortened and the use of comments to clarify? </li>
<li>Less rows but of intricate code or more rows of less intricate code?</li>
<li>If its need for a programmer to reread compact intricate code comments or reread the other, is there a boundary between them other than semantics?</li>
<li>Am I getting ahead of myself and it will be clearer down the road? </li>
</ul>
<p>How can this program be made more programmer friendly?</p>
<pre class="lang-py prettyprint-override"><code>"""
Updated to be more programmer friendly
This is an implementation of John Zelles graphics.py module that is, as I understand it, a simple library of functions so that beginners can have some fun learning
graphics. The implementation paints smooth to scrambled spirals. Its free to use, edit etc.
In this code the "if command" buffers and flattens c.draw(win) while win is minimized and draws it flat when maximized
If enjoyable perhaps a filmscreen to capture as the computer paints? Or maybe a screensaver by just showing a number of brushstrokes at a time?
Thx to Reinderien comments and answer in Code Review Stack Exchange
"""
from math import *
from graphics import *
def draw_brushes(win, brush_maximum_radius, spiral_revolutions, spiral_angle_vector_acceleration, spiral_radius_acceleration, center_x, center_y, x_tremble_amplitude,
x_tremble_period, y_tremble_amplitude, y_tremble_period, light_intesity_period, light_intensity_period_displacement, maximum_light_intensity,
lowest_light_intensity, circleRGBred_weight, circleRGBgreen_weight, circleRGBblue_weight, brush_resolution, x_coordinate, y_coordinate):
for brush_current_radius1 in range(brush_resolution * brush_maximum_radius, 0, -1): #The radius of the circles constituting the spiral
brush_current_radius = brush_current_radius1 / brush_resolution
#Origo of spiral is in the middle of the screen.
#The direction of vector from origo is angle in radians
spiral_angle_vector = ((brush_maximum_radius - brush_current_radius) / brush_maximum_radius * spiral_revolutions)
spiral_angle_vector = spiral_angle_vector ** spiral_angle_vector_acceleration
#The magnitude of vector is radius.
spiral_radius = (brush_maximum_radius - brush_current_radius) ** spiral_radius_acceleration
spiral_radius = spiral_radius ** spiral_radius_acceleration
#If the spirals was an orbit tremble would be another orbit around that orbit. Moon to earth
x_tremble = (spiral_radius * x_tremble_amplitude) * cos(spiral_angle_vector * x_tremble_period)
y_tremble = (spiral_radius * y_tremble_amplitude) * sin(spiral_angle_vector * y_tremble_period)
#With use of the above variables in this function, draw_brushes, the brushstrokes position around origo, center of screen, is calculated
if x_coordinate != int(spiral_radius * cos(spiral_angle_vector) + x_tremble + center_x) or y_coordinate != int(spiral_radius * sin(spiral_angle_vector) + y_tremble + center_y):
x_coordinate = int(spiral_radius * cos(spiral_angle_vector) + x_tremble + center_x)
y_coordinate = int(spiral_radius * sin(spiral_angle_vector) + y_tremble + center_y)
#Point is used to mark the circular brushs center with its radius brush_current_radius. Width is set to zero for cosmetic reasons, looks very choppy
c = Circle(Point(x_coordinate, y_coordinate), brush_current_radius)
c.setWidth(0)
#light intensity due to distance from origo
light_intensity_at_angle = int(sin(brush_current_radius/brush_maximum_radius * pi / 2 * light_intesity_period + light_intensity_period_displacement) * maximum_light_intensity + lowest_light_intensity)
#color due to angle
amplitude = amplitude_displacement = 0.5 #So that trigonometric function is 0<y<1
circleRGBred = int(circleRGBred_weight * light_intensity_at_angle * (sin(spiral_angle_vector) * amplitude + amplitude_displacement))
circleRGBgreen = int(circleRGBgreen_weight * light_intensity_at_angle * (sin(spiral_angle_vector + pi/2) * amplitude + amplitude_displacement))
circleRGBblue = int(circleRGBblue_weight * light_intensity_at_angle * (sin(spiral_angle_vector + pi) * amplitude + amplitude_displacement))
c.setFill(color_rgb(circleRGBred, circleRGBgreen, circleRGBblue))
c.draw(win)
#The window settings where the spiral will be painted
width = 1350
height = 730
background_red = 0
background_green = 0
background_blue = 0
win = GraphWin("My, painting circles", width, height)
win.setBackground(color_rgb(background_red, background_green, background_blue))
#Origo that is the reference point that is middle of coordination in window space
center_x = int(width / 2)
center_y = int(height / 2)
#Full screen spiral settings
zoom = 1.04 #by eye adjustment for visual preference
brush_maximum_radius = int(zoom * sqrt(center_x**2 + center_y**2))#Pythagoras
#Tremble is parable to painters hands tremble. Its factors to variables that are coordinates that gives the spirals path
x_tremble_amplitude = 0.1
x_tremble_period = 3
y_tremble_amplitude = 0.1
y_tremble_period = 3
#Acceleration is an exponent variable in the function draw_brushes
spiral_angle_vector_acceleration = 1.2
spiral_radius_acceleration = 0.8
#miscellaneous variables
spiral_revolutions = 2 * pi
brush_resolution = int(7) #lower integer for more "choppy" spiral
#So that variables is assigned a value before being called
x_coordinate_initial = y_coordinate_initial = 0
#light intensity due to distance from origo
light_intesity_period = 1.3
light_intensity_period_displacement = 0.15
maximum_light_intensity = 223
lowest_light_intensity = 22
#color due to angle. Weight must be 0<integer<1
circleRGBred_weight = int(1)
circleRGBgreen_weight = int(1)
circleRGBblue_weight = int(1)
#A single brushstroke at the time, repeated with for in range() to paint a spiral
draw_brushes(win, brush_maximum_radius, spiral_revolutions, spiral_angle_vector_acceleration, spiral_radius_acceleration, center_x, center_y, x_tremble_amplitude,
x_tremble_period, y_tremble_amplitude, y_tremble_period, light_intesity_period, light_intensity_period_displacement, maximum_light_intensity,
lowest_light_intensity, circleRGBred_weight, circleRGBgreen_weight, circleRGBblue_weight, brush_resolution, x_coordinate_initial, y_coordinate_initial)
</code></pre>
<p>Heres a spiral the program paints at its current settings</p>
<p><a href="https://i.stack.imgur.com/ZWccF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZWccF.png" alt="spiral current settings"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:27:01.827",
"Id": "447041",
"Score": "0",
"body": "Its not the if command that renders the picture quicker. it happens with or without the if command while minimizing the window that pops up while running the program. Maximizing the window and then the picture is painted in one go. Should i edit the question with the program with the docstring comment?"
}
] |
[
{
"body": "<p><strong>Code formatting</strong>:</p>\n\n<ul>\n<li>Black:</li>\n</ul>\n\n<p>I recommend to use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\"><strong>black</strong></a> to format your code.</p>\n\n<ul>\n<li>Comments:</li>\n</ul>\n\n<p>Just a personal preference: if the code in one line is getting too long, put the comment regarding the line on top of it, not in the same line to stay below a certain line length. I recommend 120, you can specify this in black.</p>\n\n<p><strong>Cleaner code</strong>:</p>\n\n<ul>\n<li>Do not use * imports:</li>\n</ul>\n\n<p>When I go over your code, i am not able to see where the class <code>Circle</code> comes from. Is it from <code>math</code> or from <code>graphics</code>? Please only use explicit imports to only import what you need and make it easier to comprehend for other readers to find what code is used.</p>\n\n<ul>\n<li>Clarify 3rd party imports:</li>\n</ul>\n\n<p>In the docstring you meantion a <code>graphics.py</code> module, but as a reader I dont know where this is and I can not import it. I can not run the code without it. Tell me where I can get it or provide it.</p>\n\n<ul>\n<li>Redefining variables from outer scope:</li>\n</ul>\n\n<p>In <code>draw_brushes</code>, every argument variable overwrites a variable from the outer scope (module level) which can lead to nasty behaviour if you make a mistake.</p>\n\n<ul>\n<li>Dont call <code>int</code> on integers:</li>\n</ul>\n\n<p><code>int(1)</code> is just not needed.</p>\n\n<ul>\n<li>Configuration variables:</li>\n</ul>\n\n<p>You use many variables to configure your drawing, maybe you can put all those in a configuration file or at least all in one place in the code.\nIts a good practice to have module level variables, global variables, in ALL CAPS.</p>\n\n<p><strong>Going deeper:</strong></p>\n\n<p>You want more? Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">pep8</a>. Use <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a>.\nRun this code:<code>import this</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:24:59.277",
"Id": "229586",
"ParentId": "229585",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229586",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:59:58.173",
"Id": "229585",
"Score": "2",
"Tags": [
"python",
"beginner",
"fractals"
],
"Title": "A program that draws a spiral"
}
|
229585
|
<p><a href="https://leetcode.com/problems/queue-reconstruction-by-height/" rel="nofollow noreferrer">https://leetcode.com/problems/queue-reconstruction-by-height/</a><br></p>
<blockquote>
<p>Suppose you have a random list of people standing in a queue. Each
person is described by a pair of integers <span class="math-container">\$(h, k)\$</span>, where <span class="math-container">\$h\$</span> is the
height of the person and <span class="math-container">\$k\$</span> is the number of people in front of this
person who have a height greater than or equal to <span class="math-container">\$h\$</span>. Write an
algorithm to reconstruct the queue.</p>
<p>Note: The number of people is less than 1,100.</p>
<pre><code>Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
</code></pre>
</blockquote>
<p>Please review for performance </p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/problems/queue-reconstruction-by-height/
/// </summary>
[TestClass]
public class ReconstructQueueTest
{
[TestMethod]
public void ReconstructQueueExampleTest()
{
int[][] people = new int[6][];
people[0] = new[] { 7, 0 };
people[1] = new[] { 4, 4 };
people[2] = new[] { 7, 1 };
people[3] = new[] { 5, 0 };
people[4] = new[] { 6, 1 };
people[5] = new[] { 5, 2 };
int[][] expected = new int[6][];
expected[0] = new[] { 5, 0 };
expected[1] = new[] { 7, 0 };
expected[2] = new[] { 5, 2 };
expected[3] = new[] { 6, 1 };
expected[4] = new[] { 4, 4 };
expected[5] = new[] { 7, 1 };
int[][] res = ReconstructQueueClass.ReconstructQueue(people);
for (var index = 0; index < res.Length; index++)
{
CollectionAssert.AreEqual(expected[index], res[index]);
}
}
}
public class ReconstructQueueClass
{
public static int[][] ReconstructQueue(int[][] people)
{
int[][] res = new int[people.Length][];
Array.Sort(people, new PairComparer());
List<int> list = new List<int>();
for (int i = 0; i < people.Length; i++)
{
list.Add(i); //a list of indices 0,1,2,3,4...
res[i] = new int[2];
}
for (int i = 0; i < people.Length; i++)
{
int index = list[people[i][1]]; //the index in the result is the number of people before you
res[index][0] = people[i][0];
res[index][1] = people[i][1];
list.RemoveAt(people[i][1]); // we remove the index from the list so we keep only the un used ones
}
return res;
}
}
/// <summary>
/// sort the people, have min height first
/// for the same height for example 5,0 and 5,2
/// 5,2 is before 5,0
/// </summary>
public class PairComparer : IComparer<int[]>
{
public int Compare(int[] x, int[] y)
{
if (x[0] != y[0])
{
return x[0] - y[0];// we want min value first
}
return y[1] - x[1];
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:32:11.170",
"Id": "446660",
"Score": "3",
"body": "if you marked close let me know what is wrong, I need to learn somehow..."
}
] |
[
{
"body": "<h2>API</h2>\n\n<p>I assume it's part of the platform requirements, but <code>int[]</code> is a terrible data-structure for storing the <code>(k, h)</code> pair, because it could have any length and implies an ordering that doesn't really exist. This should be a small class or immutable struct. (Not a Tuple, because Tuples are structural, and therefore only solve part of the problem).</p>\n\n<p>Even if this was imposed upon me, I would want to map it to something sensible before doing anything else. This mapping would act as a (necessary) validation layer, to check I'm not being given nonsense.</p>\n\n<h2><code>ReconstructQueueList</code></h2>\n\n<p>This should document what it does.</p>\n\n<p>I don't see the point in initialising every element of <code>res</code>, when you could just assign them a copy of the existing person array when you set them. This makes the code much tidier. I would move the declaration of <code>res</code> toward where it is actually used.</p>\n\n<p><code>list</code> is a completely meaningless variable name. These are the positions in the queue that you have yet to be assigned, so I will call it <code>positions</code>; however, I'm sure you can think of something much better. I would create <code>positions</code> with <code>Enumerable.Range(0, people.Length)</code>, which is more compact and has less scope for errors. I doubt the added overhead will be significant, but feel free to measure it.</p>\n\n<h2><code>PairComparer</code></h2>\n\n<p><code>PairComparer</code> is not a fantastic name for something that sorts people.</p>\n\n<p>It's good that you've given some description of what the custom comparer does. However, I don't understand the description you provide.</p>\n\n<p>I'd prefer to see <code>x[0].CompareTo(y[0])</code> instead of <code>x[0] = y[0]</code>: it's much clearer what is going on, and it doesn't risk overflowing for numbers with large magnitude.</p>\n\n<h2>Performance</h2>\n\n<p><em>This section is pretty underwhelming</em></p>\n\n<p>If we ignore the problem size limit of 1100 (where did they find that number?), the main performance concern is the <code>List.Remove(int)</code> calls, which means this algorithm is quadratic in the worst case (though linear in the best case). You can address this by using a data-structure which allows <code>log(n)</code> removal by index. I threw together a simple <code>OrderedShrinkList</code>, where removing every has a cost of <code>n log(n)</code> and <code>n</code> is the number of elements with which it begins, and ran some benchmarks.</p>\n\n<p>Swapping this appears to give a significant performance boost for large problems: it is 10 times faster on a particular random instance of size 200000 <a href=\"https://gist.github.com/VisualMelon/9ba073e688f4d5fc651be0b798ef85f7\" rel=\"nofollow noreferrer\">gist of code and results</a> (it seems to be slower for smaller ones).</p>\n\n<p>Running small problems (e.g. size 1100 and smaller), the potential inefficiency of <code>List</code> based method is not immediately revealed, and the overhead of my shoddy <code>OrderedShrinkList</code> seems to make it significantly slower. I've run out of energy to keep trying things, but a linked list might actually improve things, because it replacing a linear 'move' with a linear scan, and you can choose at which end to start.</p>\n\n<p><em>Note: I did run benchmark for some different seeds, and the general trend was similar, but this isn't the most rigorous test ever.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T21:14:59.807",
"Id": "229663",
"ParentId": "229588",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229663",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:29:57.333",
"Id": "229588",
"Score": "2",
"Tags": [
"c#",
"performance",
"programming-challenge",
"sorting"
],
"Title": "LeetCode: Queue Reconstruction by Height C#"
}
|
229588
|
<p>I was working on a little Python challenge that was a bit more difficult than expected: format any non-negative number so <code>1000</code> turns into <code>"1,000"</code> , <code>10000000</code> into <code>"10,000,000"</code> and so forth. I managed to do it, but I find my solution not very readable:</p>
<pre><code>def formatting(n):
m = str(n) # Turn it into string
m2 = [] # Empty list that will have the split version of the final number
for i in range(0,len(m),3): # Iterate every three elements
m2.append(m[::-1][i:i+3][::-1]) # Append last three numbers, second to last three numbers, etc.
m2.append(',') # Add a comma between loops
m3 = ''.join(m2[::-1])[1:] # Join and drop the first element which is always a comma.
return m3
</code></pre>
<p>This works but it isn't as nice as it could be. What can be done?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:39:32.500",
"Id": "446668",
"Score": "2",
"body": "Shouldn't `m = str(m)` be `m = str(n)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:44:20.903",
"Id": "446671",
"Score": "0",
"body": "You're right! My code wasn't in function form so I had a little typo when I adapted it"
}
] |
[
{
"body": "<p>A few points:</p>\n\n<ul>\n<li><p>Reversing the string <code>m</code> multiple times is unnecessary. Slicing can be done on the original string using correct indices. <code>m[::-1][i:i+3][::-1]</code> is equivalent to <code>m[-i-3:len(m)-i]</code>. Another approach is to traverse the indices in the reverse order <code>for i in range(len(m)-1, -1, -3)</code> and then perform slicing accordingly.</p></li>\n<li><p>The logic can be simplified using <code>str.join</code>. <code>m2.append(',')</code> can be omitted. And you can just do</p>\n\n<pre><code>m3 = ','.join(m2[::-1])\n</code></pre></li>\n<li><p>Further improvements can be achieved by using list comprehensions and traversing the string from the beginning rather than in the reverse order. Some calculation for the indices are needed:</p>\n\n<pre><code>def formatting(n):\n m = str(n) # Turn it into string\n num_digits = len(m)\n seg1_len = (num_digits % 3) or 3 # Calculate length of the first segment\n segments = [m[:seg1_len], *(m[i:i+3] for i in range(seg1_len, num_digits, 3))]\n return ','.join(segments)\n</code></pre></li>\n<li><p>Python 3's built-in <a href=\"https://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"nofollow noreferrer\">formatting specification</a> actually supports the thousands separator. So you can just do this to achieve the same functionality:</p>\n\n<pre><code>formatted_n = f\"{n:,}\"\n</code></pre>\n\n<p>Or equivalently:</p>\n\n<pre><code>formatted_n = \"{:,}\".format(n)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:25:16.400",
"Id": "446682",
"Score": "0",
"body": "Thanks! That was quite insightful! Also didn't know about that formatting option. Would have saved me of using `locale` multiple times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:28:38.377",
"Id": "446683",
"Score": "0",
"body": "I'm not sure what you used `locale` for. According to the doc, *For a locale aware separator, use the 'n' integer presentation type instead.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:45:26.737",
"Id": "446687",
"Score": "0",
"body": "When I'm working with money data that I have to format in some specific currency, but that's totally outside the scope of this"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:22:13.920",
"Id": "229594",
"ParentId": "229592",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229594",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:36:50.840",
"Id": "229592",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"formatting",
"integer"
],
"Title": "Manually formatting numbers in Python"
}
|
229592
|
<p>Here I have a program I made to be an all-in-one Dungeons and Dragons 5th Edition (it probably works for other games as well but this is the only one I'm familiar with and the one it was primarily designed for) dice roller for all the common dice sizes as well as a disadvantage and advantage menu for the d20 and custom size support and even a stat roller (4d6 drop the lowest). It comes in two parts, the main program for the user to run and a subprogram designed to reduce the size of the main one by calling it instead of having the same code several times.</p>
<pre><code>"Megumin"→Str5
Lbl 00
ClrHome
Menu("How many sides?","Coin",2,"Four",4,"Six",6,"Eight",8,"Ten",10,"Page 2",P
Lbl P
Menu("How many sides?","Twelve",12,"Twenty",20,"Custom",C,"One hundred (Percentile)",99,"Stats (4d6 drop lowest)",S,"Page 1",00,"Quit",XX
Lbl 2
randInt(0,6000)→X
If not(X
Then
While not(getKey
Output(1,1,"The coin landed on
Output(2,1,"its side! Flipping again.."
End
ClrHome
Goto 2
End
If X>3000
Then
While not(getKey
Output(1,1,"The coin landed on heads
End
Else
If X
Then
While not(getKey
Output(1,1,"The coin landed on tails
End
End
End
Goto 00
Lbl 4
4→Y
prgmDICESUB
Goto 00
Lbl 6
6→Y
prgmDICESUB
Goto 00
Lbl 8
8→Y
prgmDICESUB
Goto 00
Lbl 10
10→Y
prgmDICESUB
Goto 00
Lbl 12
12→Y
prgmDICESUB
Goto 00
Lbl 20
Menu("Advantage or disadvantage?","Neither",21,"Advantage",22,"Double advantage",23,"Triple advantage",24,"Disadvantage",02,"Back to top",00,"Quit",XX
Lbl 21
21→Y
prgmDICESUB
Goto 00
Lbl 22
randInt(1,20,2→∟ADV
max(∟ADV→X
While not(getKey
If max(1/(1+abs(∟NUM-X)))=1
Then
Output(1,1,"You rolled an
Output(1,15,X
Else
Output(1,1,"You rolled a
Output(1,14,X
End
End
Goto 00
Lbl 23
randInt(1,20,3→∟ADV
max(∟ADV→X
While not(getKey
If max(1/(1+abs(∟NUM-X)))=1
Then
Output(1,1,"You rolled an
Output(1,15,X
Else
Output(1,1,"You rolled a
Output(1,14,X
End
End
Goto 00
Lbl 24
randInt(1,20,4→∟ADV
max(∟ADV→X
While not(getKey
If max(1/(1+abs(∟NUM-X)))=1
Then
Output(1,1,"You rolled an
Output(1,15,X
Else
Output(1,1,"You rolled a
Output(1,14,X
End
End
Goto 00
Lbl 02
randInt(1,20,2→∟ADV
min(∟ADV→X
While not(getKey
If max(1/(1+abs(∟NUM-X)))=1
Then
Output(1,1,"You rolled an
Output(1,15,X
Else
Output(1,1,"You rolled a
Output(1,14,X
End
End
Goto 00
Lbl 99
100→Y
prgmDICESUB
Goto 00
Lbl C
DelVar Y
prgmDICESUB
Goto 00
Lbl S
0→dim(∟STATS
For(I,1,6,1
0→dim(∟ROLLS
randInt(1,6,4)→∟ROLLS
1+sum(not(cumSum(∟ROLLS=min(∟ROLLS))))→X
∟ROLLS(X)-min(∟ROLLS)→∟ROLLS(X)
sum(∟ROLLS)→∟STATS(1+dim(∟STATS
End
toString(∟STATS(1))→Str0
For(I,2,6,1
Str0+" "+toString(∟STATS(I))→Str0
End
ClrHome
While not(getKey
Output(5,(int(length(Str0)/2-2)),Str0
End
ClrHome
SetUpEditor
Goto 00
Lbl XX
"Aqua"→Str5
ClrHome
While not(getKey
Output(2,1,"Thank you for using my
Output(3,1,"dice roller!
Output(4,1,"If you have any
Output(5,1,"suggestions I would love
Output(6,1,"To hear them! Email me at
Output(7,1," // (here I put a contact email that isn't important here)
Output(8,1,"-Yami
End
ClrHome
"
</code></pre>
<p>The DICESUB program is here:</p>
<pre><code>If Str5="Megumin"
Then
SetupEditor ∟NUM
SetupEditor
If not(Y
Input "How many sides? ",Y
randInt(1,Y)→X
ClrHome
While not(getKey
If max(1/(1+abs(∟NUM-X)))=1
Then
Output(1,1,"You rolled an
Output(1,15,X
Else
Output(1,1,"You rolled a
Output(1,14,X
End
End
Return
Else
ClrHome
While not(getKey
Output(3,1,"This program is desgined to
Output(4,1,"run with another program,
Output(5,1,"not on its own.
Output(6,1,"Please run prgmDNDDICE
End
ClrHome
Menu("Would you like to now?","Yes",1,"No",0
End
Lbl 1
prgmDNDDICE
Lbl 0
"
</code></pre>
<p>∟NUM is a list that would be shipped with the program it contains numbers 8, 11, 18, 80, 81, 82, 83, 84, 85, 86, 87, 88, and 89 (so basically any number from 1 to 100 where you would say "an" instead of "a"). Although I could, if it would be better, set that up to be initialized with the program as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:44:12.840",
"Id": "446670",
"Score": "0",
"body": "Can you format your code properly please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:51:41.290",
"Id": "446674",
"Score": "1",
"body": "That's how it's formatted on the calculator itself so I thought it was fine. But I can add indents and whatever else if need be"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:52:48.847",
"Id": "446675",
"Score": "0",
"body": "Without proper indenting your code becomes almost unreadable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:55:41.240",
"Id": "446677",
"Score": "0",
"body": "That's fair, I'll do it when I get back to my computer, on my lunch break atm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:59:57.020",
"Id": "446678",
"Score": "0",
"body": "@πάνταῥεῖ, that's BASIC for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T20:55:48.493",
"Id": "446688",
"Score": "0",
"body": "Added indents. Let me know if anything else needs fixing or if I messed up the indents anywhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T21:31:03.097",
"Id": "446690",
"Score": "0",
"body": "@Himitsu_no_Yami Several closing parenthesis are missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T21:32:58.720",
"Id": "446691",
"Score": "1",
"body": "@πάνταῥεῖ that's because in a lot of cases you can leave them off in TI-Basic to save space. since each one is a byte. The same goes for the closing quotation marks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T21:53:34.187",
"Id": "446695",
"Score": "0",
"body": "If D&D is Dungeons and Dragons could you replace D&D with the name. It might make your question more popular. Since I'm not a D&D player, how many dice are rolled per turn. Can this be integrated with a full game?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T22:01:18.867",
"Id": "446696",
"Score": "1",
"body": "@pacmaninbw I can certainly expand D&D out. As far as how many dice are rolled per turn it WIDELY varies. Some attacks roll 1 die for determining if they hit or not and 1 for damage while under certain conditions you may role as many as 3 or even 4 to try to hit and I've seen attacks that require 3 or more dice to determine damage and with the possibility of multiple attacks per turn that's not really a question that can be answered."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:41:38.393",
"Id": "229593",
"Score": "0",
"Tags": [
"dice",
"ti-basic"
],
"Title": "D&D Dice Roller"
}
|
229593
|
<p>Motivation: Partially for fun / learning, but also so I can roll out a custom JSON-like file format for a fighting game I am writing. There are two caveats: you cannot have repeated keys (requires <code>std::unordered_multimap</code>) and the keys are not in order (requires insertion order <code>std::vector</code> on the side, or some external boost lib probably). I am mainly looking for critique on my level of comments and ability to read my code, but everything else I am of course welcome to hear.</p>
<pre><code>#pragma once
#include <list>
#include <map>
#include <string>
#include <variant>
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
namespace json {
class Value;
// six json data types
using null_t = std::nullptr_t;
using bool_t = bool;
using number_t = std::double_t;
using string_t = std::string;
using array_t = std::vector<Value>;
using object_t = std::map<string_t, Value>;
using aggregate_t = std::variant<
null_t, bool_t, number_t,
string_t, array_t, object_t>;
class Value : protected aggregate_t {
public:
using aggregate_t::variant;
// removes spurious E0291
Value() = default;
// converts int into double rather than bool
Value(int integer) : aggregate_t(static_cast<double>(integer)) {}
// converts c_string (pointer) into string rather than bool
Value(const char* c_string) : aggregate_t(std::string(c_string)) {}
public:
auto operator[](const string_t& key) -> Value& {
// transform into object if null
if (std::get_if<null_t>(this))
*this = object_t();
return std::get<object_t>(*this)[key];
}
auto operator[](std::size_t key) -> Value& {
// transform into array if null
if (std::get_if<null_t>(this))
*this = array_t();
if (key >= std::get<array_t>(*this).size())
std::get<array_t>(*this).resize(key + 1);
return std::get<array_t>(*this)[key];
}
auto save(std::ostream& stream, std::string prefix = "") -> std::ostream& {
static const std::string SPACING = " "; // "\t"; // " ";
// depending on the type, write to correct value with format to stream
std::visit([&stream, &prefix](auto&& value) {
using namespace std;
using T = decay_t<decltype(value)>;
if constexpr (is_same_v<T, nullptr_t>)
stream << "null";
if constexpr (is_same_v<T, bool_t>)
stream << (value ? "true" : "false");
else if constexpr (is_same_v<T, double_t>)
stream << value;
else if constexpr (is_same_v<T, string>)
stream << '"' << value << '"';
else if constexpr (is_same_v<T, array_t>) {
stream << "[\n";
auto [indent, remaining] = make_tuple(prefix + SPACING, value.size());
// for every json value, indent and print to stream
for (auto& json : value)
json.save(stream << indent, indent)
// if jsons remaining (not last), append comma
<< (--remaining ? ",\n" : "\n");
stream << prefix << "]";
}
else if constexpr (is_same_v<T, object_t>) {
stream << "{\n";
auto [indent, remaining] = make_tuple(prefix + SPACING, value.size());
// for every json value, indent with key and print to stream
for (auto& [key, json] : value)
json.save(stream << indent << '"' << key << "\" : ", indent)
// if jsons remaining (not last), append comma
<< (--remaining ? ",\n" : "\n");
stream << prefix << "}";
}
}, *static_cast<aggregate_t*>(this));
return stream;
}
auto load(std::istream& stream) -> std::istream& {
using namespace std;
switch ((stream >> ws).peek()) {
case '"': {
// get word surrounded by "
stringbuf buffer;
stream.ignore(1)
.get(buffer, '"')
.ignore(1);
*this = buffer.str();
} break;
case '[': {
array_t array;
for (stream.ignore(1); (stream >> ws).peek() != ']';)
// load child json and consume comma if available
if ((array.emplace_back().load(stream) >> ws).peek() == ',')
stream.ignore(1);
stream.ignore(1);
*this = move(array);
} break;
case '{': {
object_t object;
for (stream.ignore(1); (stream >> ws).peek() != '}';) {
// get word surrounded by "
stringbuf buffer;
stream.ignore(numeric_limits<streamsize>::max(), '"')
.get(buffer, '"')
.ignore(numeric_limits<streamsize>::max(), ':');
// load child json and consume comma if available
if ((object[buffer.str()].load(stream) >> ws).peek() == ',')
stream.ignore(1);
}
stream.ignore(1);
*this = move(object);
} break;
default: {
if (isdigit(stream.peek()) || stream.peek() == '.') {
double_t number;
stream >> number;
*this = number;
}
else if (isalpha(stream.peek())) {
// get alphabetic word
string word;
for (; isalpha(stream.peek()); stream.ignore())
word.push_back(stream.peek());
// set value to look-up table's value
static auto keyword_lut = map<string_view, Value>{
{"true", true}, {"false", false}, {"null", nullptr}};
*this = keyword_lut[word];
}
else
*this = nullptr;
} break;
}
return stream;
}
auto save_to_path(std::string_view file_path) -> void {
auto file = std::ofstream(std::string(file_path));
save(file);
}
auto load_from_path(std::string_view file_path) -> void {
auto file = std::ifstream(std::string(file_path));
load(file);
}
static void test() {
std::stringstream ss;
{
json::Value value;
auto& employee = value["employee"];
employee["name"] = "bob";
employee["age"] = 21;
employee["friends"][0] = "alice";
employee["friends"][1] = "billy";
employee["weight"] = 140.0;
value.save(ss);
}
std::cout << ss.str() << "\n\n";
{
auto example = std::stringstream(R"(
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
})");
json::Value value;
value.load(example);
ss.clear();
value.save(ss);
}
std::cout << ss.str() << "\n\n";
}
};
}
int main() {
json::Value::test();
return getchar();
}
</code></pre>
|
[] |
[
{
"body": "<p>Let's go through the code and see what can be improved.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#pragma once\n</code></pre>\n</blockquote>\n\n<p>This shouldn't be in a non-header.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#include <list>\n#include <map>\n#include <string>\n#include <variant>\n#include <vector>\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n</code></pre>\n</blockquote>\n\n<p>Sort the include directives in alphabetical order.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>namespace json {\n class Value;\n\n // six json data types\n using null_t = std::nullptr_t;\n using bool_t = bool;\n using number_t = std::double_t;\n using string_t = std::string;\n using array_t = std::vector<Value>;\n using object_t = std::map<string_t, Value>;\n\n using aggregate_t = std::variant<\n null_t, bool_t, number_t,\n string_t, array_t, object_t>;\n</code></pre>\n</blockquote>\n\n<p><code>json</code> is a very common name used by many people, leading to name clashes. Think of a more unique name. Maybe <code>unicorn5838::json</code>?</p>\n\n<p>I don't see a reason to use <code>std::nullptr_t</code> for <code>null_t</code>. <code>std::nullptr_t</code> is a null pointer literal and can implicitly convert to pointers. Is that plausible? You can use <code>std::monostate</code> instead, or just <code>struct null_t { };</code>.</p>\n\n<p>You are mixing <code>std::double_t</code> and <code>double</code>. My advice is to just use <code>double</code>. Also, consistently use <code>number_t</code> after the alias declaration.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>class Value : protected aggregate_t {\npublic:\n using aggregate_t::variant;\n // removes spurious E0291\n Value() = default;\n // converts int into double rather than bool\n Value(int integer) : aggregate_t(static_cast<double>(integer)) {}\n // converts c_string (pointer) into string rather than bool\n Value(const char* c_string) : aggregate_t(std::string(c_string)) {}\n</code></pre>\n</blockquote>\n\n<p>Hmm ... Protected inheritance? Why do you need it in this case? (You can address this question with a comment if you have a good reason.)</p>\n\n<p>Inheriting the constructors of <code>std::variant</code> doesn't seem to be a good choice here. I see your effort in fixing the problems, but just providing your own constructors seems easier.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public:\n auto operator[](const string_t& key) -> Value& {\n // transform into object if null\n if (std::get_if<null_t>(this))\n *this = object_t();\n return std::get<object_t>(*this)[key];\n }\n\n auto operator[](std::size_t key) -> Value& {\n // transform into array if null\n if (std::get_if<null_t>(this))\n *this = array_t();\n if (key >= std::get<array_t>(*this).size())\n std::get<array_t>(*this).resize(key + 1);\n return std::get<array_t>(*this)[key];\n }\n</code></pre>\n</blockquote>\n\n<p>Don't use multiple <code>public:</code> labels.</p>\n\n<p>Do not use the trailing return type syntax unless necessary. (Yeah, I know some people advocate always using a trailing return type, but it arguably makes the code more verbose.)</p>\n\n<p>Your <code>operator[]</code> automatically constructs the element if not existent, much like <code>map::operator[]</code> but not <code>vector::operator[]</code>. I'm not sure whether this behavior is intuitive enough to justify itself, but anyway ...</p>\n\n<p><code>*this = object_t();</code> should be <code>emplace<object_t>();</code> to prevent an unnecessary move construction.</p>\n\n<p>You do <code>std::get<array_t>(*this)</code> three times, and the complex code for getting the value will be run three times. Instead, use a reference:</p>\n\n<pre><code>auto& arr = std::get<array_t>(*this);\nif (key >= arr.size())\n arr.resize(key + 1);\nreturn arr[key];\n</code></pre>\n\n<p>Also note that <code>key + 1</code> may overflow (well, probably not a real problem).</p>\n\n<blockquote>\n<pre><code>auto save(std::ostream& stream, std::string prefix = \"\") -> std::ostream& {\n static const std::string SPACING = \" \"; // \"\\t\"; // \" \";\n\n // depending on the type, write to correct value with format to stream\n std::visit([&stream, &prefix](auto&& value) {\n using namespace std;\n using T = decay_t<decltype(value)>;\n\n if constexpr (is_same_v<T, nullptr_t>)\n stream << \"null\";\n if constexpr (is_same_v<T, bool_t>)\n stream << (value ? \"true\" : \"false\");\n else if constexpr (is_same_v<T, double_t>)\n stream << value;\n else if constexpr (is_same_v<T, string>)\n stream << '\"' << value << '\"';\n else if constexpr (is_same_v<T, array_t>) {\n stream << \"[\\n\";\n auto [indent, remaining] = make_tuple(prefix + SPACING, value.size());\n // for every json value, indent and print to stream\n for (auto& json : value)\n json.save(stream << indent, indent)\n // if jsons remaining (not last), append comma\n << (--remaining ? \",\\n\" : \"\\n\");\n stream << prefix << \"]\";\n }\n else if constexpr (is_same_v<T, object_t>) {\n stream << \"{\\n\";\n auto [indent, remaining] = make_tuple(prefix + SPACING, value.size());\n // for every json value, indent with key and print to stream\n for (auto& [key, json] : value)\n json.save(stream << indent << '\"' << key << \"\\\" : \", indent)\n // if jsons remaining (not last), append comma\n << (--remaining ? \",\\n\" : \"\\n\");\n stream << prefix << \"}\";\n }\n }, *static_cast<aggregate_t*>(this));\n return stream;\n}\n</code></pre>\n</blockquote>\n\n<p>Use <code>null_t</code> and <code>string_t</code>, not <code>nullptr_t</code> and <code>string</code>. Use <code>const auto&</code> instead of <code>auto&&</code> if you don't need the universal reference semantics. <code>prefix</code> should be <code>std::string_view</code> instead of by-value <code>std::string</code>. The spacing should also be an argument instead of hard coded.</p>\n\n<p>This is a very long function. The long if constexpr chain makes the code much less readable. Use overload resolution to break it down:</p>\n\n<pre><code>// somewhere\nstruct formatter {\n std::ostream& os;\n std::string_view prefix;\n std::string_view indent;\n\n void operator()(null_t) const;\n void operator()(bool_t) const;\n // etc.\n};\n</code></pre>\n\n<p>then you can just do</p>\n\n<pre><code>std::visit(formatter{os, prefix, indent}, static_cast<aggregate_t&>(*this));\n</code></pre>\n\n<p>The string streaming should use <code>std::quoted</code> to properly handle escaping.</p>\n\n<p>Don't do this:</p>\n\n<pre><code>auto [indent, remaining] = make_tuple(prefix + SPACING, value.size());\n</code></pre>\n\n<p>It incurs a lot of overhead, both on performance and readability.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>auto load(std::istream& stream) -> std::istream& {\n using namespace std;\n\n switch ((stream >> ws).peek()) {\n case '\"': {\n // get word surrounded by \"\n stringbuf buffer;\n stream.ignore(1)\n .get(buffer, '\"')\n .ignore(1);\n *this = buffer.str();\n } break;\n case '[': {\n array_t array;\n for (stream.ignore(1); (stream >> ws).peek() != ']';)\n // load child json and consume comma if available\n if ((array.emplace_back().load(stream) >> ws).peek() == ',')\n stream.ignore(1);\n stream.ignore(1);\n *this = move(array);\n } break;\n case '{': {\n object_t object;\n for (stream.ignore(1); (stream >> ws).peek() != '}';) {\n // get word surrounded by \"\n stringbuf buffer;\n stream.ignore(numeric_limits<streamsize>::max(), '\"')\n .get(buffer, '\"')\n .ignore(numeric_limits<streamsize>::max(), ':');\n // load child json and consume comma if available\n if ((object[buffer.str()].load(stream) >> ws).peek() == ',')\n stream.ignore(1);\n }\n stream.ignore(1);\n *this = move(object);\n } break;\n default: {\n if (isdigit(stream.peek()) || stream.peek() == '.') {\n double_t number;\n stream >> number;\n *this = number;\n }\n else if (isalpha(stream.peek())) {\n // get alphabetic word\n string word;\n for (; isalpha(stream.peek()); stream.ignore())\n word.push_back(stream.peek());\n // set value to look-up table's value\n static auto keyword_lut = map<string_view, Value>{\n {\"true\", true}, {\"false\", false}, {\"null\", nullptr}};\n *this = keyword_lut[word];\n }\n else\n *this = nullptr;\n } break;\n }\n\n return stream;\n}\n</code></pre>\n</blockquote>\n\n<p>Don't use <code>stringbuf</code>. It's a low level functionality. Use <code>std::quoted</code> instead:</p>\n\n<pre><code>case '\"': {\n std::string str;\n stream >> std::quoted(str);\n emplace<string_t>(str);\n break;\n}\n</code></pre>\n\n<p><code>.ignore(1)</code> is slower than <code>.get()</code> without aggressive optimization.</p>\n\n<p>The table should be <code>const</code>, and <code>.at</code> (which looks up existing elements) should be used instead of <code>[]</code> (which creates new elements and cannot be used on <code>const</code> maps). Using a <code>map</code> for three strings is also an overkill and will introduce overhead.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>auto save_to_path(std::string_view file_path) -> void {\n auto file = std::ofstream(std::string(file_path));\n save(file);\n}\n\nauto load_from_path(std::string_view file_path) -> void {\n auto file = std::ifstream(std::string(file_path));\n load(file);\n}\n</code></pre>\n</blockquote>\n\n<p>Please don't \"always use <code>auto</code>\". I know it is suggested by Herb Sutter (right?), but it is really unidiomatic and distracting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T19:18:04.107",
"Id": "448718",
"Score": "0",
"body": "I've gone ahead and made all the corrections except the follow (please refute me if I am wrong): `#pragma once` it is a header file, `protected aggregate_t` because a json IS-A variant, not HAS-A variant, multiple `public:` labels separates my ctors / API and trailing returns is my coding style (I would change depending on my org)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T19:28:59.933",
"Id": "448721",
"Score": "0",
"body": "ah two more notes: I can't use `std::string_view` for `prefix` because I require append operations to tabify my json -> file operation, second I use a `std::map` lookup table even if it is overkill because its easy to read and I will be adding my own custom keywords for my fighting game."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T09:47:17.800",
"Id": "448820",
"Score": "1",
"body": "@Saxpy \"Is-a\" should be indicated by private inheritance, not protected inheritance. Don't abuse multiple `public:` labels, which alter semantics, for separating declaration blocks; using a comment like `// constructors` instead is much clearer. Always trailing return is a, well, unpopular, and illogical style (coding styles exist to improve readability). `string_view` provides the operations you want. Keeping the map is understandable though, but at least make it `const`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T16:55:53.467",
"Id": "448882",
"Score": "0",
"body": "I see, I'll go ahead and change it to private inheritance. Also I'll take note on the `public:` blocks into `// constructors`. I'd still like to keep trailing returns at this is my personal project and that's the style I've committed too and prefer on my own. `string_view` does not offer append operations though, how could I refactor this? The `std::map` will be const."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:54:51.310",
"Id": "449018",
"Score": "0",
"body": "@Saxpy Can you elaborate on “string view does not offer append operations”? You can concatenate them just like ordinary strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T17:34:00.903",
"Id": "449113",
"Score": "0",
"body": "IIRC `string_view` is supposed to be a read-only view of a c-string. [string_view](https://en.cppreference.com/w/cpp/string/basic_string_view) contains no APIs for mutations, only reducing the view."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:11:19.480",
"Id": "449183",
"Score": "0",
"body": "@Saxpy You can still do `sv + sv` or `sv + s` because `is_constructible<string, string_view>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:57:29.830",
"Id": "449261",
"Score": "0",
"body": "`sv + sv` and `sv + s` fails on both Clang 8 and MSVC2019. I found this [link](https://stackoverflow.com/questions/44636549/why-is-there-no-support-for-concatenating-stdstring-and-stdstring-view) from 2 years ago, but in any case I'd still prefer using a plain `string` as it is meant to be appended anyways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T09:03:26.110",
"Id": "449348",
"Score": "1",
"body": "@Saxpy Oops, I didn’t realize that the string view ctor is explicit. Sorry, I’ll reconsider the recommendation"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:40:34.060",
"Id": "230262",
"ParentId": "229597",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230262",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T22:35:16.510",
"Id": "229597",
"Score": "7",
"Tags": [
"c++",
"parsing",
"json"
],
"Title": "Minimal JSON Parser"
}
|
229597
|
<blockquote>
<p>There is a follow-up question available:
<a href="https://codereview.stackexchange.com/questions/229707/shell-sort-insertion-sort-bubble-sort-selection-sort-algorithms-python">shell-sort-insertion-sort-bubble-sort-selection-sort-algorithms-python</a>.</p>
</blockquote>
<h3>Selection Sort</h3>
<p>The selection sort algorithm sorts a list (array) by finding the minimum element from the right (unsorted part) of the list and putting it at the left (sorted part) of the list. </p>
<h3>Bubble Sort</h3>
<p>The Bubble Sort algorithm functions by repeatedly swapping the adjacent elements, if they aren't in correct order.</p>
<h3>Optimized Bubble Sort</h3>
<p>An optimized version of Bubble Sort algorithm is to break the loop, when there is no further swapping to be made, in one entire pass.</p>
<h3>Insertion Sort</h3>
<p>Insertion sort algorithm builds the final sorted array in a one item at a time manner. It is less efficient on large lists than more advanced algorithms, such as Quick Sort, Heap Sort or Merge Sort, yet it provides some advantages, such as implementation simplicity, efficiency for small datasets and sorting stability.</p>
<h3>Shell Sort (Optimized Insertion Sort)</h3>
<p>Shell Sort is just a variation of Insertion Sort, in which the elements are moved only one position ahead. When an element has to be moved far ahead, too many movements are involved, which is a drawback. In Shell Sort, we'd make the array "h-sorted" for a large value of h. We then keep reducing the value of h (<code>sublist_increment</code>) until it'd become 1. </p>
<hr>
<p>I've been trying to implement the above algorithms in Python and modified it based on prior reviews, I'd appreciate it if you'd review it for any other changes/improvements.</p>
<h3>Code</h3>
<pre><code>import random
from typing import List, TypeVar
from scipy import stats
T = TypeVar('T')
def selection_sort(input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer/float list using Selection Sort Algorithm.
Sorting:
- In-Place (space complexity O(1))
- Efficiency (Time Complexity => O(N^2))
- Unstable Sort (Order of duplicate elements is not preserved)
Iterates through the list and swaps the min from the right side
to sorted elements from the left side of the list.
"""
# Is the length of the list.
length = len(input_list)
# Iterates through the list to do the swapping.
for element_index in range(length - 1):
min_index = element_index
# Iterates through the list to find the min index.
for finder_index in range(element_index + 1, length):
if input_list[min_index] > input_list[finder_index]:
min_index = finder_index
# Swaps the min value with the pointer value.
if element_index is not min_index:
input_list[element_index], input_list[min_index] = input_list[min_index], input_list[element_index]
return input_list
def bubble_sort(input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer/float list using regular Bubble Sort algorithm.
Sorting:
- In-Place (Space Complexity => O(1))
- Efficiency (Time Complexity => O(N^2))
- Stable Sort (Order of equal elements does not change)
"""
length = len(input_list)
for i in range(length - 1):
for j in range(length - i - 1):
if input_list[j] > input_list[j + 1]:
_swap_elements(input_list, j, j + 1)
return input_list
def optimized_bubble_sort(input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer/float list using an Optimized Bubble Sort algorithm.
For optimization, the Bubble Sort algorithm stops if in a pass there would be no further swaps
between an element of the array and the next element.
Sorting:
- In-Place (Space Complexity => O(1))
- Efficiency (Time Complexity => O(N^2))
- Stable Sort (Order of equal elements does not change)
"""
# Assigns the length of to be sorted array.
length = len(input_list)
for i in range(length - 1):
number_of_swaps = 0
for j in range(length - i - 1):
if input_list[j] > input_list[j + 1]:
_swap_elements(input_list, j, j + 1)
number_of_swaps += 1
# If there is no further swap in iteration i, the array is already sorted.
if number_of_swaps == 0:
break
return input_list
def _swap_elements(input_list: List[T], current_index: int, next_index: int) -> None:
"""
Swaps the adjacent elements.
"""
input_list[current_index], input_list[next_index] = input_list[next_index], input_list[current_index]
def insertion_sort(input_list: List[T]) -> List[T]:
"""
This method returns an ascending sorted integer list
for an input integer/float list using a Insertion Sort algorithm.
Sorting:
- In-Place (space complexity O(1))
- Efficiency (time complexity O(N^2) - Good if N is small - It has too many movements)
- Stable Sort (Order of duplicate elements is preserved)
"""
# Assigns the length of to be sorted array.
length = len(input_list)
# Picks the to-be-inserted element from the right side of the array, starting with index 1.
for i in range(1, length):
element_for_insertion = input_list[i]
# Iterates through the left sorted-side of the array to find the correct position for the element to be inserted.
j = i - 1
while j >= 0 and input_list[j] > element_for_insertion:
input_list[j + 1] = input_list[j]
j -= 1
# Inserts the element.
input_list[j + 1] = element_for_insertion
return input_list
def shell_sort(input_list: List[T], sublist_increment: int) -> List[T]:
if sublist_increment // 2 == 0:
print("Please select an odd number for sublist incrementation. ")
return
# Assigns the length of to be sorted array.
length = len(input_list)
while sublist_increment >= 1:
for i in range(sublist_increment, length):
element_for_insertion = input_list[i]
# Iterates through the left sorted-side of the array to find the correct position for the element to be inserted.
j = i - sublist_increment
while j >= 0 and input_list[j] > element_for_insertion:
input_list[j + sublist_increment] = input_list[j]
j -= sublist_increment
# Inserts the element.
input_list[j + sublist_increment] = element_for_insertion
# Narrows down the sublists by two increments.
sublist_increment -= 2
return input_list
if __name__ == "__main__":
# Generates a random integer list
TEST_LIST_INTEGER = random.sample(range(-1000, 1000), 15)
# Generates a random float list
TEST_LIST_FLOAT = stats.uniform(-10, 10).rvs(10)
print(f"The unsorted integer input list is:\n{TEST_LIST_INTEGER}\n-----------------------------------\n")
print(f"The unsorted float input list is:\n{TEST_LIST_FLOAT}\n-----------------------------------\n")
# Tests the Selection Sort Algorithm:
print("---------------------------------")
print(f"Selection Sort (Integer): {selection_sort(TEST_LIST_INTEGER.copy())}")
print(f"Selection Sort (Float): {selection_sort(TEST_LIST_FLOAT.copy())}")
# Tests the Optimized Bubble Sort Algorithm:
print("---------------------------------")
print(f"Optimized Bubble Sort (Integer): {optimized_bubble_sort(TEST_LIST_INTEGER.copy())}")
print(f"Optimized Bubble Sort (Float): {optimized_bubble_sort(TEST_LIST_INTEGER.copy())}")
# Tests the Bubble Sort Algorithm:
print("---------------------------------")
print(f"Bubble Sort (Integer): {bubble_sort(TEST_LIST_INTEGER.copy())}")
print(f"Bubble Sort (Float): {bubble_sort(TEST_LIST_INTEGER.copy())}")
# Tests the Insertion Sort Algorithm:
print("---------------------------------")
print(f"Insertion Sort (Integer): {insertion_sort(TEST_LIST_INTEGER.copy())}")
print(f"Insertion Sort (Float): {insertion_sort(TEST_LIST_INTEGER.copy())}")
# Tests the Shell Sort Algorithm:
print("---------------------------------")
print(f"Shell Sort (Integer): {shell_sort(TEST_LIST_INTEGER.copy(), 5)}")
print(f"Shell Sort (Float): {shell_sort(TEST_LIST_INTEGER.copy(), 5)}")
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/229535/sorting-algorithms-python">Sorting Algorithms (Python) - Code Review</a></li>
<li><a href="https://codereview.stackexchange.com/questions/229509/selection-sort-algorithm-python">Selection Sort Algorithm (Python) - Code Review</a></li>
<li><a href="https://www.geeksforgeeks.org/shellsort/" rel="nofollow noreferrer">Shell Sort - Geeks for Geeks</a></li>
<li><a href="https://www.geeksforgeeks.org/bubble-sort/" rel="nofollow noreferrer">Bubble Sort - Geeks for Geeks</a></li>
<li><a href="https://en.wikipedia.org/wiki/Bubble_sort" rel="nofollow noreferrer">Bubble Sort - Wiki</a></li>
<li><a href="https://www.geeksforgeeks.org/selection-sort/" rel="nofollow noreferrer">Selection Sort - Geeks for Geeks</a></li>
<li><a href="https://en.wikipedia.org/wiki/Selection_sort" rel="nofollow noreferrer">Selection Sort - Wiki</a></li>
<li><a href="https://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow noreferrer">Insertion Sort - Wiki</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T23:20:13.607",
"Id": "446899",
"Score": "0",
"body": "BTW, \"optimized bubble sort\" is kind of silly. Basically the only benefit of Bubble Sort is very small code size (in machine code) and simplicity. If you want it to run faster, use Insertion Sort. There's not much use case for \"optimized bubble sort\" because it's still quite bad when the list isn't already sorted. See [Bubble Sort: An Archaeological Algorithmic Analysis](https://users.cs.duke.edu/~ola/papers/bubble.pdf) for some history about why Bubble Sort is so widely known even though it doesn't perform well."
}
] |
[
{
"body": "<h2>In-place sort</h2>\n\n<p>Your <code>selection_sort</code> is an in-place sort, so there's no need to return the same list you were given. In fact, returning the list is confusing, because it somewhat implies that you would be returning something different from what you were given. You can just drop the return, here and in similar functions.</p>\n\n<h2>Failure modes</h2>\n\n<pre><code>if sublist_increment // 2 == 0:\n print(\"Please select an odd number for sublist incrementation. \")\n return\n</code></pre>\n\n<p>This has issues. You're printing - but what if the caller doesn't want you to print? You're returning <code>None</code> - but what if the caller wants to catch an exception and try with different input? You should be <code>raise</code>ing an exception here, not printing and returning <code>None</code>.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<pre><code># Tests the Selection Sort Algorithm:\nprint(\"---------------------------------\")\nprint(f\"Selection Sort (Integer): {selection_sort(TEST_LIST_INTEGER.copy())}\")\nprint(f\"Selection Sort (Float): {selection_sort(TEST_LIST_FLOAT.copy())}\")\n\n# Tests the Optimized Bubble Sort Algorithm:\nprint(\"---------------------------------\")\nprint(f\"Optimized Bubble Sort (Integer): {optimized_bubble_sort(TEST_LIST_INTEGER.copy())}\")\nprint(f\"Optimized Bubble Sort (Float): {optimized_bubble_sort(TEST_LIST_INTEGER.copy())}\")\n# Tests the Bubble Sort Algorithm:\nprint(\"---------------------------------\")\nprint(f\"Bubble Sort (Integer): {bubble_sort(TEST_LIST_INTEGER.copy())}\")\nprint(f\"Bubble Sort (Float): {bubble_sort(TEST_LIST_INTEGER.copy())}\")\n# Tests the Insertion Sort Algorithm:\nprint(\"---------------------------------\")\nprint(f\"Insertion Sort (Integer): {insertion_sort(TEST_LIST_INTEGER.copy())}\")\nprint(f\"Insertion Sort (Float): {insertion_sort(TEST_LIST_INTEGER.copy())}\")\n\n# Tests the Shell Sort Algorithm:\nprint(\"---------------------------------\")\nprint(f\"Shell Sort (Integer): {shell_sort(TEST_LIST_INTEGER.copy(), 5)}\")\nprint(f\"Shell Sort (Float): {shell_sort(TEST_LIST_INTEGER.copy(), 5)}\")\n</code></pre>\n\n<p>This should be a loop that executes five times. You can iterate over a tuple that contains entries for</p>\n\n<ul>\n<li>the name of the sorting algorithm, and</li>\n<li>a reference to a wrapper function that passes arguments in addition to <code>TEST_LIST</code></li>\n</ul>\n\n<h2>Tests</h2>\n\n<p>It seems that there's either a bug or an unimplemented mechanism, because there is no difference between the \"integer\" and \"float\" tests. They're all integer tests.</p>\n\n<p>Also, these are only tests in the sense that a developer has to use their eyeballs and verify the output manually. You should consider writing real automated tests: pass methods a known input (as you already do), and assert that the output is equal to expected output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:11:38.387",
"Id": "446903",
"Score": "0",
"body": "For testing, perhaps using Python's built-in sort function would be useful to generate the \"expected\" output, letting you randomly generate inputs to your test function. (And/or check every permutation of an input list to catch any corner cases.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T00:15:33.330",
"Id": "446904",
"Score": "0",
"body": "@PeterCordes I had suggested that in the review of the last version of this program."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T02:15:51.323",
"Id": "229604",
"ParentId": "229598",
"Score": "11"
}
},
{
"body": "<p>Adding to @Reinderien's review, here are a few more points:</p>\n\n<h1>Testing</h1>\n\n<ul>\n<li><p>The test code has some repeated statements for every function. It would be better to put that into a <code>for</code> loop like this:</p>\n\n<pre><code>sorting_algorithms = [\n (\"Selection Sort\", selection_sort),\n ...\n # Wrap shell_sort into a lambda to make it a single-argument function for testing\n (\"Shell Sort\", lambda s: shell_sort(s, 5))\n]\n\nfor description, func in sorting_algorithms:\n ...\n print(f\"{description} (Integer): {func(TEST_LIST_INTEGER.copy())}\")\n ...\n</code></pre></li>\n<li><p>Since callers of sorting functions are normally expected to supply only the list to be sorted, it would be better to make all other arguments optional:</p>\n\n<pre><code>def shell_sort(input_list: List[T], sublist_increment: int = 5) -> List[T]:\n</code></pre>\n\n<p>This sets a default value for the <code>sublist_increment</code> argument. With this change, the lambda wrapper for <code>shell_sort</code> in the code above is no longer needed (it is still needed if you want to test calling the function with non-default arguments).</p></li>\n<li><p><code>random.sample</code> performs sampling without replacement. So every input occurs only once and there are no duplicates in the output list. This is undesired for testing purpose since the functions are expected to work with duplicated elements. <code>random.choice</code> should be used instead.</p></li>\n<li><p>It is a bit unusual to use two modules <code>scipy.stats</code> and <code>random</code> for the same task -- generating random numbers. The former is more powerful but in this case either of them is sufficient.</p></li>\n</ul>\n\n<h1>Coding style</h1>\n\n<ul>\n<li><p>Since you have defined the function <code>_swap_elements</code>, it would be better to use it everywhere when the functionality is needed. The <code>selection_sort</code> function has not used it yet.</p></li>\n<li><p>The function <code>_swap_elements</code> does not need to know what the input indices mean for the caller. The function would work as long as the indices are valid. Therefore in this declaration</p>\n\n<pre><code>def _swap_elements(input_list: List[T], current_index: int, next_index: int)\n</code></pre>\n\n<p>the argument names <code>current_index</code> and <code>next_index</code> can be changed to more general names such as <code>index1</code> and <code>index2</code>.</p></li>\n<li><p>There are some overly long lines. Although it may not always be necessary to conform to the 79-char limit recommended by PEP 8, it would also be better not to make the lines too long. Long comments can be written on multiple lines. Statements like this</p>\n\n<pre><code>print(f\"The unsorted integer input list is:\\n{TEST_LIST_INTEGER}\\n-----------------------------------\\n\")\n</code></pre>\n\n<p>can be written as this</p>\n\n<pre><code>print(\"The unsorted integer input list is:\",\n TEST_LIST_INTEGER,\n \"-----------------------------------\\n\", sep='\\n')\n</code></pre>\n\n<p>or this (Python automatically joins adjacent string literals with no separators)</p>\n\n<pre><code>print(\"The unsorted integer input list is:\\n\"\n f\"{TEST_LIST_INTEGER}\\n\"\n \"-----------------------------------\\n\")\n</code></pre>\n\n<p>The shorter-line versions are also a bit more clear since each line of code corresponds to a line in the actual output.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:14:41.830",
"Id": "446867",
"Score": "1",
"body": "Good review, thanks! You can also use `\"-\" * 70` to create these ASCII lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:29:00.973",
"Id": "446868",
"Score": "1",
"body": "If that separator line is used multiple times it is better to define a variable `sep_line = '-' * 70` and reuse it everywhere. Otherwise, I think it might be a bit clearer to just lay it out so that the alignment can be visually seen in the code. However this is purely subjective."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T03:10:04.860",
"Id": "229605",
"ParentId": "229598",
"Score": "10"
}
},
{
"body": "<h1>Rationale</h1>\n\n<p>Given that this question and your previous question, that I've seen, both mangled testing and implementation, I think you should properly setup your Python project environment. </p>\n\n<ul>\n<li>Since you have tests you should use something like <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\"><code>unittest</code></a> or <a href=\"https://docs.pytest.org/en/latest/\" rel=\"nofollow noreferrer\">pytest</a>.</li>\n<li><p>Since I would setup a test directory and a source directory I can't just <code>import se_229598</code>, and so the simplest way to ensure I'm testing the correct code is to use <a href=\"https://tox.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">tox</a> or <a href=\"https://nox.thea.codes/en/stable/\" rel=\"nofollow noreferrer\">Nox</a>.</p>\n\n<p>This comes with the added benefits that you'll; be testing your setup.py, can test against multiple Python versions and you can add other tools such as linters, hinters and documentation to your testing tool-chain.</p></li>\n</ul>\n\n<p>I should note the code that I'm providing for the <code>setup.py</code> and <code>tox.ini</code> are <a href=\"https://stackoverflow.com/help/minimal-reproducible-example\">MCVEs</a> to keep the answer small and so don't follow best practices or have many cool features.</p>\n\n<h1>Python Project Environment</h1>\n\n<ul>\n<li><p>First, you should make a directory with your desired layout. For the most part, it's whether you should use <code>/src</code> or not. I find <code>/src</code> simpler; however <a href=\"https://github.com/pypa/packaging.python.org/issues/320\" rel=\"nofollow noreferrer\">this is a mini-holy war</a>, where there are <a href=\"https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure\" rel=\"nofollow noreferrer\">some recommendations for using <code>/src</code></a> and I'm sure some for not using <code>/src</code>.</p>\n\n<pre><code>/\n|- src\n| |-- <name>\n|- tests\n| |-- test_<test_name>.py\n|- setup.py\n|- tox.ini\n</code></pre></li>\n<li><p><a href=\"https://packaging.python.org/tutorials/installing-packages/#creating-virtual-environments\" rel=\"nofollow noreferrer\">Create a virtual environment</a> and activate it, using either:</p>\n\n<ul>\n<li><code>venv</code>; or</li>\n<li><code>virtualenv</code>, by <a href=\"https://packaging.python.org/tutorials/installing-packages/#requirements-for-installing-packages\" rel=\"nofollow noreferrer\">Ensure you can install packages</a> and <a href=\"https://packaging.python.org/tutorials/installing-packages/#installing-from-pypi\" rel=\"nofollow noreferrer\">installing <code>virtualenv</code> from PyPI</a>.</li>\n</ul></li>\n<li><p>Install the package, and dependencies, in the project's virtual environment.</p></li>\n<li>Test with <code>tox</code>.</li>\n</ul>\n\n<p>On Windows this would look something like:</p>\n\n<pre><code>$ mkdir src/se_229598\n$ mkdir tests\n$ python -m pip install virtualenv\n$ python -m virtualenv venv\n$ ./venv/Scripts/activate\n(venv) $ vim setup.py\n(venv) $ vim tox.ini\n(venv) $ vim src/se_229598/__init__.py\n(venv) $ vim tests/test_all.py\n(venv) $ pip install .[dev]\n(venv) $ tox\n</code></pre>\n\n<p>Where:</p>\n\n<ul>\n<li><p><code>__init__.py</code> is the code that you have in the post.<br>\nSince you added a main guard it means that your old tests won't run. And so you can delete that if you want.</p></li>\n<li><p><code>setup.py</code></p>\n\n<pre><code>from setuptools import setup, find_packages\n\nsetup(\n name='se_229598',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n extras_require={\n 'dev': [\n 'tox',\n 'pytest',\n 'scipy',\n ]\n },\n)\n</code></pre></li>\n<li><p><code>tox.ini</code></p>\n\n<pre><code>[tox]\nenvlist =\n unit-py36\n unit-py37\n\n[testenv]\nbasepython =\n py36: python3.6\n py37: python3.7\ndeps =\n .[dev]\ncommands =\n unit: pytest\n</code></pre></li>\n<li><p><code>test_all.py</code>. It should be obvious, but I've only tested one of your functions.</p>\n\n<pre><code>import random\n\nimport pytest\nimport scipy.stats\n\nimport se_229598\n\nTEST_LIST_INTEGER = random.sample(range(-1000, 1000), 15)\nTEST_LIST_FLOAT = list(scipy.stats.uniform(-10, 10).rvs(10))\n\n\ndef test_selection_sort_int():\n assert (\n se_229598.selection_sort(TEST_LIST_INTEGER.copy())\n == sorted(TEST_LIST_INTEGER)\n )\n\n\ndef test_selection_sort_float():\n assert (\n se_229598.selection_sort(TEST_LIST_FLOAT.copy())\n == sorted(TEST_LIST_FLOAT)\n )\n</code></pre></li>\n</ul>\n\n<h1>Explanation</h1>\n\n<p>To test your code all you need to do is run <code>tox</code> in your virtual environment.</p>\n\n<pre><code>$ ./venv/Scripts/activate\n(venv) $ tox\n...\n___________ summary ___________\n unit-py36: commands succeeded\n unit-py37: commands succeeded\n congratulations :)\n$ \n</code></pre>\n\n<p>This is as we setup tox to run pytest against Python 3.7 and 3.6 in the <code>[testenv]</code> section. If we don't specify the environment then it will default to running pytest on both 3.7 and 3.6, as we specified in the <code>envlist</code>.</p>\n\n<p>Due to doing a standard pytest install we can just run <code>pytest</code> to test the code using its test auto discovery.</p>\n\n<p>From here you can setup linters and hinters in your <code>tox.ini</code> and verify these raise no problems. You can also setup Sphinx to document your code. And even add test coverage. And all this runs simply from one command, <code>tox</code>.</p>\n\n<p>Not only does this simplify local testing, tools like tox have integration with some CI software. Where <a href=\"https://github.com/Peilonrayz/typing_inspect_lib/blob/master/tox.ini\" rel=\"nofollow noreferrer\">I have used Jenkins CI and tox</a> together to allow a basic CI workflows.</p>\n\n<h1>Further reading</h1>\n\n<ul>\n<li><a href=\"https://packaging.python.org/tutorials/packaging-projects/\" rel=\"nofollow noreferrer\">PyPA's more fleshed out packaging instructions</a>.</li>\n<li><a href=\"https://pytest.org/en/latest/getting-started.html\" rel=\"nofollow noreferrer\"><code>pytest</code>'s getting started</a>.</li>\n<li><a href=\"https://tox.readthedocs.io/en/latest/examples.html\" rel=\"nofollow noreferrer\">tox configuration and usage examples</a>. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:22:01.223",
"Id": "229644",
"ParentId": "229598",
"Score": "5"
}
},
{
"body": "<p>As noted in <a href=\"https://codereview.stackexchange.com/a/229604/98493\">another answer</a> by <a href=\"https://codereview.stackexchange.com/users/25834/reinderien\">@Reinderien</a>, some of your functions modify the list in-place and some do not. This is already not so good, but it is exacerbated by the fact that all of your docstrings claim that the function <em>returns</em> a sorted list, indicating that it does not mutate any of the inputs.</p>\n\n<p>If you fix this, e.g. by, as a crude hack, making a copy of the list first, you gain immediate improvements to the testability of your code. Suddenly it becomes very easy to e.g. produce a performance comparison of your algorithms:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QAeLM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QAeLM.png\" alt=\"enter image description here\"></a></p>\n\n<p>For fairness' sake I added the line <code>input_list = input_list[:]</code> to all functions. I also gave <code>sublist_increment</code> a default value of <code>5</code> as suggested in <a href=\"https://codereview.stackexchange.com/a/229605/98493\">the answer</a> by <a href=\"https://codereview.stackexchange.com/users/207952/gz0\">@GZ0</a> and threw in the built-in <code>sorted</code> function (with a wrapper containing the <code>input_list = input_list[:]</code> line).</p>\n\n<p>A few takeaway points from this:</p>\n\n<ul>\n<li>It is hard to beat the built-in sorting function (especially with code written in Python and not C). It is between 3 and 400 times faster than the functions you wrote. For performance critical applications always prefer the built-in function unless you have some weird edge-case and a sorting function optimized for that specific case.</li>\n<li>All of your functions seem not to be only slower in absolute terms, but also in relative. The asymptotic behavior looks like it has a different slope than that of <code>sorted</code>, which is <span class=\"math-container\">\\$\\mathcal{O}(n\\log n)\\$</span>. As mentioned <a href=\"https://codereview.stackexchange.com/questions/229598/shell-sort-insertion-sort-bubble-sort-selection-sort-algorithms-python/229688?noredirect=1#comment447014_229688\">in the comments</a> by <a href=\"https://codereview.stackexchange.com/users/207952/gz0\">@GZ0</a> your algorithms are all <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>.</li>\n<li>Note that I was limited to lists of length less than about a thousand because otherwise the runtimes would become too long.</li>\n<li>The function you call \"optimized\" bubble sort does not seem to perform any better than the normal bubble sort.</li>\n<li>In contrast, the shell sort (optimized insertion sort) does actually perform better than the normal insertion sort.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:16:36.697",
"Id": "447014",
"Score": "1",
"body": "All the implemented algorithms in the post have \\$O(n^2)\\$ time complexity while a build-in sorting function in any language that has wide industrial applications would implement a \\$O(nlogn)\\$ algorithm. Hence the asymptotic behaviour."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:30:00.563",
"Id": "447016",
"Score": "1",
"body": "@GZ0 The latter I was aware of, but for the former I would have had to study the algorithms more closely. Thanks for pointing it out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T09:17:30.247",
"Id": "229688",
"ParentId": "229598",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229604",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T22:43:55.543",
"Id": "229598",
"Score": "14",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"sorting"
],
"Title": "Shell Sort, Insertion Sort, Bubble Sort, Selection Sort Algorithms (Python)"
}
|
229598
|
<p><a href="https://github.com/CrazyPython/svgmanip/" rel="nofollow noreferrer"><code>svgmanip</code></a> is a library that extends svgutils by providing rotation, import, and export primitives. It is available on PyPI, and was created a few years ago.</p>
<h2>Install</h2>
<pre><code>pip install svgmanip
</code></pre>
<h2>Bugs</h2>
<ul>
<li><a href="https://github.com/CrazyPython/svgmanip/issues/1" rel="nofollow noreferrer">Exporting does not work on Windows</a></li>
</ul>
<p>The code of the main file, <code>_generator.py</code> is here:</p>
<pre><code>from __future__ import division
import re
import os
from tempfile import NamedTemporaryFile
import svgutils
from lxml import etree
import mpmath as math
from ensure import ensure
from svgutils.compose import SVG, Figure, Unit
from svgutils import transform as _transform
math.dps = 17 # SVG's precision is double, which may be up to 17 digits
__all__ = ['Element']
def rotate_point(x, y, degrees):
radians = math.radians(degrees)
cos_theta = math.cos(radians)
sin_theta = math.sin(radians)
return x * cos_theta - y * sin_theta, \
x * sin_theta + y * cos_theta
def get_shift_and_dims(points, degrees):
rotated = [
rotate_point(*point, degrees=degrees)
for point in points
]
unrotated = points
# find highest x in rotated
max_x_unrotated = max(unrotated, key=lambda point: point[0])[0]
max_y_unrotated = max(unrotated, key=lambda point: point[1])[1]
max_x_rotated = max(rotated, key=lambda point: point[0])[0]
max_y_rotated = max(rotated, key=lambda point: point[1])[1]
min_x_rotated = min(rotated, key=lambda point: point[0])[0]
min_y_rotated = min(rotated, key=lambda point: point[1])[1]
# Python's float is double precision so we can convert losslessly
# However, mpmath has higher precision for sin, cos, and tan.
shift = float(max_x_rotated - max_x_unrotated), float(max_y_rotated - max_y_unrotated)
dims = max_x_rotated - min_x_rotated, max_y_rotated - min_y_rotated
return shift, dims
def get_quad_shift_and_dims(width, height, degrees):
return get_shift_and_dims(
[(+width / 2, -height / 2),
(-width / 2, -height / 2),
(+width / 2, +height / 2),
(-width / 2, +height / 2), ],
degrees,
)
class Element(Figure):
@staticmethod
def _parse_string_dimension(dimension):
if dimension is None:
raise ValueError('Expected `dimension` to be str, Unit, float, or int, got None.')
if isinstance(dimension, str):
dimension = dimension.strip()
groups = re.match(r'(\d+)\w*', dimension).groups()
assert len(groups) == 1 # if this errors, your SVG probably has an invalid size!
return float(groups[0])
elif isinstance(dimension, Unit):
return dimension.to('px').value
elif isinstance(dimension, float) or isinstance(dimension, int):
return dimension # it *should* be a float
def __init__(self, width_or_filename, height=None, *svgelements):
if height is None:
# some pretty hacky code to autodetect height
assert len(svgelements) == 0
svgfigure = svgutils.transform.fromfile(width_or_filename)
svg = SVG(width_or_filename).scale(1) # scale of 1 converts to an Element
super(Element, self).__init__(self._parse_string_dimension(svgfigure.width),
self._parse_string_dimension(svgfigure.height), svg)
else:
super(Element, self).__init__(width_or_filename, height, *svgelements)
def placeat(self, element, x, y):
ensure(element).is_an(Element)
ensure(x).is_numeric()
ensure(y).is_numeric()
super(Element, self).__init__(self.width, self.height, self, element.move(x, y))
@property
def width(self):
return self._parse_string_dimension(self._width)
@width.setter
def width(self, new):
self._width = new
@property
def height(self):
return self._parse_string_dimension(self._height)
@height.setter
def height(self, new):
self._height = new
def rotate(self, angle, x=None, y=None):
if x is None and y is None:
self.rotate(angle, self._parse_string_dimension(self.width) / 2,
self._parse_string_dimension(self.height) / 2)
# height then width
quad_shift, quad_dims = get_quad_shift_and_dims(self.width, self.height, angle)
figure = type(self)(quad_dims[0], quad_dims[1], self)
figure.move(*quad_shift)
return figure
else:
ensure(x).is_numeric()
ensure(y).is_numeric()
return super(Element, self).rotate(angle, x, y)
@staticmethod
def loads(string):
return svgutils.transform.fromstring(string)
@staticmethod
def load(filename):
return svgutils.transform.fromfile(filename)
def dumps(self):
# the default .tostr() function fails to return the same text .dump() would return
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
out = etree.tostring(element.root, xml_declaration=True,
standalone=True,
pretty_print=True)
# but even this doesn't make it. The encoding must be changed to UTF-8 (otherwise svgexport fails)
out = out.replace("version='1.0'", 'version="1.0"')
out = out.replace("encoding='ASCII'", 'encoding="UTF-8"')
return out
def dump(self, filename):
return self.save(filename)
def to_png(self, width, height=None):
# rather unfortunately, the two available python libraries either
# a) don't support Python 2.7 or b) generate awful images
if height is None:
wh_string = width
else:
wh_string = "{}:{}".format(width, height)
# svgexport fails on files missing the svg extension
in_tempfile = NamedTemporaryFile(suffix=".svg", delete=False)
in_tempfile.write(self.dumps())
# svgexport also fails if the file isn't closed
in_tempfile.close()
out_tempfile = NamedTemporaryFile()
command = 'svgexport {} {} {} > /dev/null'.format(in_tempfile.name, out_tempfile.name, wh_string)
exit_code = os.system(command)
if exit_code != 0:
raise RuntimeError("External command svgexport failed")
out_tempfile.seek(0)
return out_tempfile.read()
def save_as_png(self, filename, width, height=None):
with open(filename, mode="wb") as f:
f.write(self.to_png(width, height))
def find_id(self, element_id):
"""Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element
"""
element = _transform.FigureElement.find_id(self, element_id)
return type(self)(element.root)
</code></pre>
|
[] |
[
{
"body": "<p>Firstly: congratulations on listing this in pypi. That's pretty cool.</p>\n\n<h2>Documentation</h2>\n\n<p>Particularly since this is a publicly-consumable library, it's very important that you add docstrings to all of your exposed functions. You know the routine: triple-quoted comments at the top of each function describing the return value and the parameters.</p>\n\n<h2>Type hints</h2>\n\n<p>For the same reason as above, it's important to have type hints on your methods. At a guess,</p>\n\n<pre><code>def rotate_point(x, y, degrees):\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>def rotate_point(x: float, y: float, degrees: float) -> float:\n</code></pre>\n\n<h2>Lambdas</h2>\n\n<p>... are great, to a point. However, these:</p>\n\n<pre><code>max_x_unrotated = max(unrotated, key=lambda point: point[0])[0]\nmax_y_unrotated = max(unrotated, key=lambda point: point[1])[1]\n\nmax_x_rotated = max(rotated, key=lambda point: point[0])[0]\nmax_y_rotated = max(rotated, key=lambda point: point[1])[1]\nmin_x_rotated = min(rotated, key=lambda point: point[0])[0]\nmin_y_rotated = min(rotated, key=lambda point: point[1])[1]\n</code></pre>\n\n<p>are better-represented as reusable functions, perhaps</p>\n\n<pre><code>def _first_coord(point: Sequence[float]) -> float:\n return point[0]\ndef _second_coord(point: Sequence[float]) -> float:\n return point[1]\n</code></pre>\n\n<h2>Python version</h2>\n\n<p>Which one are you supporting? Because <code>super(Element, self)</code> indicates Python 2.</p>\n\n<h2>Naming convention</h2>\n\n<p><code>placeat</code> would be <code>place_at</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T06:51:01.387",
"Id": "446736",
"Score": "4",
"body": "`_first_coord` and `_second_coord` could also be implemented using [`operator.itemgetter`](https://docs.python.org/3/library/operator.html#operator.itemgetter)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:02:11.440",
"Id": "446873",
"Score": "0",
"body": "I think most of my publicly accessible functions are self-explanatory by their names. What do you suggest I add for docstrings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:08:29.250",
"Id": "446876",
"Score": "0",
"body": "\"Which one are you supporting?\" It seems like both methods of calling super are supported in Python 3, so I see no reason to break compatibility with Py3-- not until Py2 is formally deprecated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:25:22.203",
"Id": "446878",
"Score": "0",
"body": "Self-explanatory is relative. `get_shift_and_dims` probably returns two things. What are those things? This is really not self-explanatory."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T02:01:01.663",
"Id": "229603",
"ParentId": "229599",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T23:28:55.207",
"Id": "229599",
"Score": "4",
"Tags": [
"python"
],
"Title": "svgmanip - python library to programmatically import, manipulate, and composite together existing SVG files"
}
|
229599
|
<p>I have my images stored in an S3 bucket and I am serving them from AWS CloudFront. I have created 2 CNAME records for the CloudFront: <code>mywebsite.com</code> and <code>www.mywebsite.com</code></p>
<p>So the image path being served from AWS CloudFront could be either of the following urls:</p>
<p><em>www.mywebsite.con/s3-folder/img-1.jpg</em> </p>
<p><em>mywebsite.com/s3-folder/img-1.jpg</em> </p>
<p>The relative image path is stored in DB, and to display the image I would add <code>www.mywebsite.com</code> before the path...</p>
<p>But then I started getting CORS (Cross Origin Request Sharing). This was when user was vising the page using: <code>mywebsite.com</code> url and I was building the path to the image like: <code>www.mywebsite.com/s3-folder/img-1.jpg</code></p>
<p>To prevent this error, I built the following <code>PhotoPathMapper</code>, which checks the current request to see if it contains <code>www</code> or not and build the image url accordingly:</p>
<pre><code>public static class PhotoPathMapper
{
private static readonly string _wwwSubDomain = "www.";
private static readonly string _fileUploadRootWithWWW;
private static readonly string _fileUploadRootWithoutWWW;
static PhotoPathMapper()
{
if (EnvironmentConfig.IsDevEnvironment)
{
// ignore CORS violation for DEV Environment as it runs under localhost
_fileUploadRootWithWWW = _fileUploadRootWithoutWWW = GlobalConfig.FileUploadRoot;
}
else
{
int indexOfWWW = GlobalConfig.FileUploadRoot.IndexOf(_wwwSubDomain, StringComparison.InvariantCultureIgnoreCase);
if (indexOfWWW >= 0)
{
// build 2 website roots: https://www.mywebsite.com and https://mywebstite.com
_fileUploadRootWithWWW = GlobalConfig.FileUploadRoot;
_fileUploadRootWithoutWWW = GlobalConfig.FileUploadRoot.Remove(indexOfWWW, _wwwSubDomain.Length);
}
else
{
throw new Exception($"FileUploadRoot '{GlobalConfig.FileUploadRoot}' Config value should include www subdomain, e.g. use https://www.mywebsite.com instead of https://mywebsite.com");
}
}
}
public static string AddAbsoluteRootOfPhotos(string relativePath)
{
// check to see if current request includes www subdomain or not (i.e is it mywebsite.com or www.mywebsite.com)
// and build the absolute path accordingly. This would prevent any CORS access violation
if (IncludeWWWSubdomain())
{
return _fileUploadRootWithWWW + relativePath;
}
return _fileUploadRootWithoutWWW + relativePath;
}
public static string RemoveAbsoluteRootOfPhotos(string absolutePath)
{
if (!string.IsNullOrEmpty(absolutePath))
{
int indexOfDomainWithWWW = absolutePath.IndexOf(_fileUploadRootWithWWW);
if (indexOfDomainWithWWW >= 0)
{
return absolutePath.Remove(indexOfDomainWithWWW, _fileUploadRootWithWWW.Length);
}
int indexOfDomainWithoutWWW = absolutePath.IndexOf(_fileUploadRootWithoutWWW);
if (indexOfDomainWithoutWWW >= 0)
{
return absolutePath.Remove(indexOfDomainWithoutWWW, _fileUploadRootWithoutWWW.Length);
}
}
return string.Empty;
}
private static bool IncludeWWWSubdomain()
{
if (!string.IsNullOrEmpty(HttpContext.Current.Request.Url.Host))
{
if (HttpContext.Current.Request.Url.Host.StartsWith(_wwwSubDomain, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
throw new Exception($"Host name is empty string.");
}
}
</code></pre>
<p>This has resolved the CORS issue. </p>
<p>I have seen <a href="https://www.html5rocks.com/en/tutorials/cors/" rel="nofollow noreferrer">this article</a> where they change the <code>XMLHttpRequest</code> and change certain permissions on S3 bucket to get around the CORS error. I am wondering if my solution is good or would it be better to follow the above article.</p>
<p>Appreciate any feedback about this solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T05:19:33.750",
"Id": "446727",
"Score": "2",
"body": "The real solution is to use relative addresses: `/s3-folder/img-1.jpg`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T07:55:27.943",
"Id": "446742",
"Score": "0",
"body": "@PeterTaylor: thanks a lot. I have changed the `FileUploadRoot` to `/` char and everything works fine. The CORS error does not appear whether I include `www` in the url or not."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T01:54:19.603",
"Id": "229601",
"Score": "1",
"Tags": [
"c#",
"security",
"asp.net-mvc",
"amazon-web-services",
"cors"
],
"Title": "Getting around CORS error for displaying images on my website"
}
|
229601
|
<p>I am developing this angular app and it has big forms with 100 + fields. I was thinking about using <code>[(ngModel)]</code> without reactive forms, so that it's easier to do validations and I only have to provide the same JSON to the web service endpoint. Is this a right approach?</p>
<p><strong>Reactive forms</strong></p>
<pre><code>export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
}
<input type="text" formControlName="firstName">
</code></pre>
<p><strong>Alternative</strong></p>
<pre><code> export class ProfileEditorComponent {
profileForm = {
firstName:""
}
}
<input type="text" [(ngModel)]="profileForm.firstName">
</code></pre>
<p>My idea was to handle all the validations and everything manually.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T05:08:02.090",
"Id": "229611",
"Score": "2",
"Tags": [
"javascript",
"comparative-review",
"template",
"form",
"angular-2+"
],
"Title": "Angular forms - reactive vs. [(ngModel)]"
}
|
229611
|
<p>I have written a small and simple <code>ThreadPool</code> class for rather simple multithreading applications.</p>
<ul>
<li>The <code>Threadpool</code> class manages a vector with the actual threads.</li>
<li>The <code>Thread</code> struct is used to store the thread's function. </li>
<li><code>ThreadPoolElement</code> keeps track of the thread and its state.</li>
</ul>
<pre><code>#pragma once
#include <vector>
#include <thread>
#include <mutex>
namespace frm { namespace util {
template <typename F, typename ... Args>
struct Thread {
Thread(F&& f)
: func(f) {
}
std::function<void(Args...)> func;
};
class Threadpool {
public:
Threadpool(const size_t& capasity = std::thread::hardware_concurrency())
: m_capacity(capasity) {
m_threads.reserve(m_capacity);
}
virtual ~Threadpool() {
for (auto& t : m_threads) {
t.thread.join();
}
}
template <typename Thread, typename ... Args>
void getThread(Thread& t, Args... args) {
while (m_threads.size() >= m_capacity) {
cleanup();
}
std::lock_guard<std::mutex> lock(m_mutex);
m_threads.emplace_back(ThreadPoolElement());
ThreadPoolElement& elem = m_threads[m_threads.size() - 1];
elem.thread = std::thread([&] (ThreadPoolElement* e, Thread& t, Args... args) {
t.func(args...);
e->is_done = true;
}, &elem, t, args...);
}
size_t activeThreads() const {
return m_threads.size();
}
size_t reservedThreads() const {
return m_capacity;
}
void cleanup() {
for (int i = 0; i < m_threads.size(); i++) {
if (m_threads[i].is_done) {
std::lock_guard<std::mutex> lock(m_mutex);
m_threads[i].thread.join();
m_threads.erase(m_threads.begin() + i--);
}
}
}
private:
struct ThreadPoolElement {
std::thread thread;
volatile bool is_done = false;
};
size_t m_capacity;
std::mutex m_mutex;
std::vector<ThreadPoolElement> m_threads;
};
} }
</code></pre>
<p>My questions are pretty simple:</p>
<ul>
<li><p>Has this implementation any significant downsides that would make it a 'Please do not use this' implementation?</p></li>
<li><p>What are the most important parts I'm missing?</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:17:02.387",
"Id": "446760",
"Score": "2",
"body": "Welcome to Code Review!"
}
] |
[
{
"body": "<p>I found a few issues, here they are (in order in which they were found). The list may seem long, but this does not mean that you did a bad job. Instead, it means that the feedback is detailed ;)</p>\n\n<p>If some issue starts with <strong>[major]</strong>, it means that it would stop me from using your class.</p>\n\n<ul>\n<li><strong>[major]</strong> There is zero documentation.</li>\n<li>The <code>Thread</code> struct is not really a thread. In fact, it just stores a single <code>std::function</code> member. Why did you name it like that?</li>\n<li>The <code>Threadpool</code> has a virtual destructor. This is not necessary, because it does not make sense to inherit from it. I suggest you make it non-virtual.</li>\n<li>The prefix <code>get</code> usually indicates that you return something from it. However, <code>getThread</code> does not return anything. Even though <code>t</code> is passed by reference, you do not change it. Maybe <code>addTask</code> is a better name.</li>\n<li><strong>[major]</strong> If the thread pool is full, <code>getThread</code> blocks until one of the threads is free. This is bad. In addition, you use an active loop to block, which means that waiting takes 100% of one CPU core. This is really bad. The whole point of threads and thread pools is that the user does not need to wait. I suggest that you copy or move the task (your <code>std::function</code>) into the pool and execute it as soon as some thread is free. This way, <code>getThread</code> can return immediately.</li>\n<li><strong>[major]</strong> The thread pool currently creates one <code>std::thread</code> for each task that is added. However, creating threads has some overhead and this will make a big difference if you have many small tasks. I suggest that you create <code>m_capacity</code> worker threads that grab the tasks from some container. This transforms your problem into a typical <em>producer-consumer problem</em> (adding a task is <em>producing</em> work, which is then <em>consumed</em> by the threads).</li>\n<li><strong>[major]</strong> You are using <code>std::function<void(Args...)></code> to store a single task. This means that the thread pool does not support return values. A common pattern is that <code>addTask</code> returns a <code>std::future</code> which will receive the return value after some thread completed the task. Additionally, thread pool users can use the <code>std::future</code> to check whether the task completed and they can use it to wait for completion.</li>\n<li><strong>[major]</strong> The <code>getThread</code> function uses references of <code>t</code>. This means that problems will occur if <code>t</code> is destroyed while the thread is still running. This is bad, because <code>t</code> is passed by the user, so the pool has no control over its lifetime. The non-existing documentation would have been a good place to mention that <code>t</code> must not be destroyed before the task is finished :) Typically, you would <code>std::move</code> the task, which transfers the control to the pool.</li>\n<li>If I understand <code>m_mutex</code> correctly, it guards <code>m_threads</code> against race conditions. This means that you want to lock the mutex whenever you use <code>m_threads</code>. Since reading from a variable while another thread modifies it is undefined behavior, you need to lock the mutex in some more places. There are some usages of <code>m_thread</code> or of its elements where the mutex is not locked (and I do not mean constructor/destructor).</li>\n<li>The <code>ThreadPoolElement</code> has a <code>volatile bool</code>. Depending on compiler and platform, <code>volatile</code> may do what you think it does. However, you can not rely on that. You should use <code>std::atomic<bool></code> instead.</li>\n<li><code>Threadpool</code> has a lower case <code>p</code>, but <code>ThreadPoolElement</code> has an upper case <code>P</code>.</li>\n</ul>\n\n<p>I suggest that you refactor the <code>Threadpool</code> such that you do not need to create a new <code>std::thread</code> object for each task. Typically, a thread pool has a queue with pending tasks and a fixed number of worker threads. The worker threads grab tasks from the queue and complete them. This way, it is possible to add many tasks without the overhead of creating new threads.</p>\n\n<p>You may want to look into the <code>std::packaged_task</code> and <code>std::future</code> classes, since they can simplify your implementation. You can probably get rid of the <code>Thread</code> and <code>ThreadPoolElement</code> classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:16:50.103",
"Id": "446759",
"Score": "2",
"body": "Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:52:43.140",
"Id": "446763",
"Score": "2",
"body": "You have done a great job. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T12:43:45.417",
"Id": "446777",
"Score": "0",
"body": "I'm unable to figure out, how to queue the task's. I tried to push them to a deque, obviously, this is not possible if the parent class shall not be a template class. Is there any way, to put the queue at some place, there the threads can access it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:42:52.040",
"Id": "446789",
"Score": "1",
"body": "@Alphastrick That part is tricky if you have never seen it :) Say your task is `std::function<R(Args...)> task`. Independent of return and argument types, the queue always stores `std::function<void()>`. You dont push `task` to the queue, but a lambda `[=]() { task(args...); }`. You could also use `std::packaged_task<R(Args...)>` as task, which easily allows you to create a `std::future<R>` that can be given to the user, but you need C++14 to `std::move` the `packaged_task` into the lambda."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:48:31.120",
"Id": "446792",
"Score": "1",
"body": "@Alphastrick Another solution would be the following: Add a base `class TaskBase` with a pure virtual `void execute()` method. Add a derived class `template <typename R, typename... Args> class Task : public TaskBase`. The `Task` constructor takes a `std::function<R(Args...)>` and the arguments and stores them. The overridden `execute` method calls the function with its arguments. Then the `addTask` method creates a `Task` and adds it to a `TaskBase` queue. The workers grab a `TaskBase` and call `execute`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:26:23.403",
"Id": "446798",
"Score": "0",
"body": ":) Thank you! I already asked a college and he also recommended your 1-st approach...."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:48:30.830",
"Id": "229624",
"ParentId": "229613",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "229624",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T07:37:04.987",
"Id": "229613",
"Score": "10",
"Tags": [
"c++",
"c++11",
"multithreading"
],
"Title": "C++ Standard-Thread Threadpool"
}
|
229613
|
<blockquote>
<p>Q: Given a list of Persons, return the first two Students having the last name starting with “C”</p>
</blockquote>
<p>My classes:</p>
<p><strong>Person class</strong></p>
<pre><code>public class Person {
protected String firstName;
protected String lastName;
protected int age;
}
</code></pre>
<p><strong>Student class</strong></p>
<pre><code>public class Student extends Person {
}
</code></pre>
<p><strong>Method</strong></p>
<pre><code>public static List<Student> findStudentsByFirstLetterFromLastName(List<Person> list) {
return list.stream()
.filter(person -> person instanceof Student
&& person.getLastName() != null
&& person.getLastName().length() > 0
&& person.getLastName().charAt(0) == 'C')
.map(person -> (Student) person)
.collect(Collectors.toList())
}
</code></pre>
<p>Is this the right way to do it? I've tried to think about the edge cases that's why there are many conditions in filter</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:12:15.197",
"Id": "446750",
"Score": "6",
"body": "You are missing part of the task: \"return the **first two** Students\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:22:44.097",
"Id": "446751",
"Score": "0",
"body": "I would sort the stream before processing it. Given it is not clear if it is already sorted in this question. Since you are using an object which doesn't implement Comparator you can use [this][1] version of the sort call for the stream. And as RoToRa pointed out you need to retrieve the first two and not all matching students.\n\n[1][https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted-java.util.Comparator-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:32:31.257",
"Id": "446754",
"Score": "2",
"body": "@Nico The task doesn't call for or require for any sorting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:46:52.730",
"Id": "446808",
"Score": "0",
"body": "@RoToRa it's unclear whether sorting is required. _the first two_ -> according to which comparison method? This question is unclear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:53:58.950",
"Id": "446811",
"Score": "1",
"body": "@dfhwze The input is a `List` so it already has an order. \"The first two\" is very unambiguous without needing a comparison method. It would be something else if the input were a `Collection` or a `Set`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:04:50.593",
"Id": "446875",
"Score": "0",
"body": "Why was this closed. Sure it didn't fullfill the task, but it only has to be correct **to the best of the author's knowledge**, and IMHO the author did believe that."
}
] |
[
{
"body": "<p>Using one large boolean expression with <code>&&</code> is not wrong and most efficient way, however if the focus is on using streams, then it would make more sense to put each sub-expression into a separate <code>.filter()</code>:</p>\n\n<pre><code>.filter(person -> person instanceof Student)\n.filter(persion -> person.getLastName() != null)\n.filter(persion -> person.getLastName().length() > 0)\n.filter(persion -> person.getLastName().charAt(0) == 'C')\n</code></pre>\n\n<p>To simplify it, instead of checking the length and the first character, you could use <code>.startsWith()</code>:</p>\n\n<pre><code>.filter(persion -> person.getLastName().startsWith(\"C\"))\n</code></pre>\n\n<p>Alternatively to get rid of repeatingly calling <code>person.getLastName()</code> moving that check into a separate method:</p>\n\n<pre><code>.filter(ClassName::checkLastName) // ClassName being this classes name\n\nprivate static boolean checkLastName(Person persion) {\n String lastName = person.getLastName();\n return lastName != null && lastName.startsWith(\"C\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:49:18.560",
"Id": "446810",
"Score": "4",
"body": "First you report part of the solution is missing and then you answer the question? How can we vote to close?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:03:01.433",
"Id": "446874",
"Score": "0",
"body": "@pacmaninbw Because any correction to the code would no effect on the validity of the review of the existing code. Also rules state the code has to be correct **to the best of the author's knowledge**, which I believe it was."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:26:11.977",
"Id": "229622",
"ParentId": "229617",
"Score": "-3"
}
}
] |
{
"AcceptedAnswerId": "229622",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T08:46:51.743",
"Id": "229617",
"Score": "-3",
"Tags": [
"java",
"stream"
],
"Title": "how to write streams in java"
}
|
229617
|
<p>I have the following collection :</p>
<pre><code>var items = new[]
{
new { Name = "A", Values = new [] { 20, 4, 5, 9, 3, 22 } },
new { Name = "B", Values = new [] { 10, 7, 9, 8, 42 } },
new { Name = "C", Values = new [] { 11, 103, 0 } },
new { Name = "D", Values = new [] { 7, 35, 42 } }
};
</code></pre>
<p>I would like to find which items have at least one common integer value with the others items. For example, "A" has 9 in common with "B", so "A" and "B" are related each other.</p>
<p>At the end, this should be the result :</p>
<pre><code>A => [B]
B => [A, D]
C => []
D => [B]
</code></pre>
<p>I wrote this code :</p>
<pre><code>var tuples = items
.SelectMany(x => x.Values, (x, y) => new { x.Name, Value = y })
.ToList();
var result = tuples.Join(tuples,
x => x.Value,
x => x.Value,
(x, y) => new { NameA = x.Name, NameB = y.Name })
.Distinct()
.GroupBy(x => x.NameA, x => x.NameB,
(a, b) => new { Name = a, Overlaps = b.Where(x => x != a)) });
</code></pre>
<p>It works (and return expected results). I was wondering if there would be a more efficient (faster and with a lower memory footprint) way do to it. I wanted to use <code>GroupJoin()</code> but since I need to filter out duplicate values (using Distinct) I used <code>Join()</code> instead.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:41:21.063",
"Id": "446887",
"Score": "1",
"body": "Regarding the on-topicness of the question and the rollbacks around it. As per meta policy answers to off-topic questions are not considered for the purposes of evaluating rollback criteria. As such fixing the code to make the question on topic is **always** acceptable."
}
] |
[
{
"body": "<p>I would make use of <code>Intersect()</code>, which, when combined with <code>Any()</code>, compares two lists of values and returns <code>true</code> if any matching values exist. I tested it and it runs significantly faster.</p>\n\n<p>Separating and storing all the name-value pair combinations in memory seems overly costly and unnecessary.</p>\n\n<pre><code>var result = items.Select(x => new \n{ \n x.Name, \n Related = items.Where(y => \n y.Name != x.Name \n && \n y.Values.Intersect(x.Values).Any()\n )\n .Select(y => y.Name) \n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:49:59.253",
"Id": "446770",
"Score": "1",
"body": "This is \\$O(n^2)\\$, so it'll perform significantly worse for larger numbers of items. You'll only notice when you actually start enumerating the results (and their `Related` properties) though, due to the 'lazy' nature of `Select`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:15:37.223",
"Id": "446842",
"Score": "0",
"body": "@PieterWitvoet is O(n) even possible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T22:05:42.753",
"Id": "446895",
"Score": "0",
"body": "I think tigrou's solution is \\$O(n)\\$, with \\$n\\$ being the total number of values. `Join`, `Distinct` and `GroupBy` will use some sort of hash-based lookup internally, so they should all be \\$O(n)\\$."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:21:51.820",
"Id": "229628",
"ParentId": "229620",
"Score": "2"
}
},
{
"body": "<p>For set-based operations like this it's better to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>HashSet<T></code></a>.</p>\n\n<blockquote>\n <p>The <code>HashSet<T></code> class provides high-performance set operations.</p>\n</blockquote>\n\n<p>The items can easily be converted to ones containing <code>HashSet</code>s. Then, the <code>Overlaps</code> method does the comparison:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var hashed = items\n .Select(i => new { Name = i.Name, Values = i.Values.ToHashSet() })\n .ToList();\nvar overlaps = hashed.Select(h1 => new\n{\n h1.Name,\n Overlaps = hashed\n .Where(h2 => h2.Name != h1.Name && h2.Values.Overlaps(h1.Values))\n .Select(h => h.Name)\n});\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>A => B \nB => A,D \nC \nD => B \n</code></pre>\n\n<p>Of course, if possible, it would be better to create items with <code>HashSet</code>s at the outset.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Triggered by your comment I did some benchmarking. I blew up your array a 1000 times, keeping unique names and then just measured both methods, using Linqpad:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var items = Enumerable.Range(1,1000).SelectMany(e => new[]\n{\n new { Name = \"A\" + e, Values = new [] { 20, 4, 5, 9, 3, 22 } },\n new { Name = \"B\" + e, Values = new [] { 10, 7, 9, 8, 42 } },\n new { Name = \"C\" + e, Values = new [] { 11, 103, 0 } },\n new { Name = \"D\" + e, Values = new [] { 7, 35, 42 } }\n});\n\nvar sw = Stopwatch.StartNew();\nvar hashed = items.Select(i => new { Name = i.Name, Values = i.Values.ToHashSet() }).ToList();\n\nsw.Elapsed.Dump();\n\nvar overlaps = hashed.Select(h1 => new\n{\n h1.Name,\n Overlaps = hashed\n .Where(h2 => h2.Name != h1.Name && h2.Values.Overlaps(h1.Values))\n .Select(h => h.Name).ToList()\n}).ToList();\nsw.Stop();\nsw.Elapsed.Dump();\n\nsw.Restart();\nvar tuples = items\n .SelectMany(x => x.Values, (x, y) => new { x.Name, Value = y })\n .ToList();\n\nsw.Elapsed.Dump();\nvar result = tuples.Join(tuples,\n x => x.Value,\n x => x.Value,\n (x, y) => new { NameA = x.Name, NameB = y.Name })\n .Where(x => x.NameA != x.NameB)\n .Distinct()\n .GroupBy(x => x.NameA, x => x.NameB)\n .ToList();\nsw.Stop();\nsw.Elapsed.Dump();\n\n</code></pre>\n\n<p>The results:</p>\n\n<pre><code>00:00:00.0035664\n00:00:02.0326684\n00:00:00.0029370\n00:00:06.3872002\n</code></pre>\n\n<p>As you see, the preparatory actions for both methods are done in 'no time', but the hashset-based method is considerably faster. Interestingly, if I blow up the arry 2000 times, the hashset-based method takes 7.7s and your method throws an <code>OutOfMemoryException</code> on my box.</p>\n\n<p>Side note: if I don't make the names unique both methods are comparable. (On which I based my previous comment).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:12:16.073",
"Id": "446766",
"Score": "0",
"body": "I tried your solution and it is much slower than original one. `Overlaps()` is not the issue. Bottleneck is the two inner loops on `hashed`. It is basically `O(n^2)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:41:01.427",
"Id": "446767",
"Score": "0",
"body": "OK, I didn't really have data to benchmark this, but then, I didn't expect this because the hashset comparison itself is really fast. It may turn out that your `SelectMany` version is the most efficient/scalable way to do it because `Join`'s time complexity is O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:58:02.860",
"Id": "446772",
"Score": "0",
"body": "If I blow up your items array 2000 times I get comparable results as for execution time (adding `ToList` to the inner `Select` to force execution). Did you notice that I added `ToList()` later to the creation of `hashed`? Anyway, comparable results is nothing like \"faster\", so if I can't think of any improvement I'll leave this answer here for reference, but of course it's not acceptable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T12:47:45.883",
"Id": "446779",
"Score": "0",
"body": "Please check my test code [here](https://gist.github.com/tigrouind/eb763f2d58214a6a33c6bfaca94c612f). Your solution is considerably slower. I am not sure why it differs from results you got."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:01:44.210",
"Id": "446781",
"Score": "1",
"body": "It seems that the chance of overlaps is decisive here. When there are no overlaps, HashSet.Overlaps has to exhaust both sets to come to a conclusion, while `Join` benefits from fewer overlaps. However, when the number of items in the arrays increases (take max 40) then the hashset-based method gets the better one. So it seems to depends much on content and it's yours to decide which method suits you best. I think one advantage of my method is that it's less complex (more self-explanatory) and it seems to have a better memory consumption."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:23:18.547",
"Id": "229629",
"ParentId": "229620",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:17:43.100",
"Id": "229620",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"linq",
"set"
],
"Title": "Finding which items have at least one common value with other items"
}
|
229620
|
<p>I watched Robert Martin's <a href="https://cleancoders.com/video-details/programming-101-episode-1" rel="nofollow noreferrer">programming 101 video</a>. I'll explain what problem he talks about in the video for those of you who haven't watched it.</p>
<p>Robert Martin is in his house and shows a light switch. If this switch goes up, a light is on. If switch goes down, the light is off. He wrote a code to handle it. This is simple but the situation is getting more complicated when he shows second, third and fourth light switch. All of them change state of the same light. Each of them is dependent on the others. He also shows how to handle it in a code.</p>
<p>Robert Martin explains that this code is not the best solution because there can be a situation when two people come to the same room and they want to turn the light on. He demonstrated that the code he has written doesn't work well because the light doesn't change its state. It's happening because a computer doesn't see simultaneous events. One of them occurs first. That's happening when two people want to turn on the light. It happens simultaneously only from human perspective. For a computer one person changes state of the light first so in fact the state of the light is changed twice. Fortunately Uncle Bob shows how to solve this problem. He measures time elapsed from the last light state change. If the next change is happening in 500 ms, he rejects it. Now when two people want to turn the light on the light is actually on.</p>
<p>Unfortunately implementing above solution breaks a case when one person quickly turns on and turns off the light. Because the second change is happening in 500 ms it is rejected. So it is not possible to quickly turn on and turn off the light. Uncle Bob didn't show how to solve this problem. He left it as a homework.</p>
<p>It took me long to figure it out how can I solve this but finally I've came to a working solution. I'm not sure though if my solution is good or maybe I only think it is good. Can you tell me if I solved the problem correctly or there is a better solution?</p>
<p>Uncle Bob's code looks like this:</p>
<pre><code>void lightLogic() {
boolean a = switchA.isUp();
boolean b = switchB.isUp();
boolean c = switchC.isUp();
boolean d = switchD.isUp();
int currentSwitchState = 0;
int base=10;
if (a) currentSwitchState += base*base*base;
if (b) currentSwitchState += base*base;
if (c) currentSwitchState += base;
if (d) currentSwitchState += 1;
int currentTime = millis();
if (currentSwitchState != lastSwitchState) {
if (currentTime - lastChangeTime > 500) {
light.state = !light.state;
lastChangeTime = currentTime;
}
}
lastSwitchState = currentSwitchState;
</code></pre>
<p>}</p>
<p>I introduced a new variable called <em>penultimateSwitchState</em> and I check if the current state of the light equals to penultimate state. If yes, I know that the same switch has been used to change light state so I accept that change:</p>
<pre><code>void lightLogic() {
boolean a = switchA.isUp();
boolean b = switchB.isUp();
boolean c = switchC.isUp();
boolean d = switchD.isUp();
int currentSwitchState = 0;
int base=10;
if (a) currentSwitchState += base*base*base;
if (b) currentSwitchState += base*base;
if (c) currentSwitchState += base;
if (d) currentSwitchState += 1;
int currentTime = millis();
if (currentSwitchState != lastSwitchState) {
if ((currentTime - lastChangeTime > 500) || (penultimateSwitchState == currentSwitchState)) {
light.state = !light.state;
lastChangeTime = currentTime;
}
penultimateSwitchState = lastSwitchState;
}
lastSwitchState = currentSwitchState;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your implementation is interesting, but it does not save from waiting in some cases:\nIf two users U1 and U2 switch on simultaneously and U2 switch was handled after U1, then U1 have to wait 500 ms for switch-off.</p>\n\n<p>I have following suggestion: What if we just compare <code>currentSwitchState</code> and <code>lastSwitchState</code> and state can be result of this comparison:</p>\n\n<pre><code>if (currentSwitchState != lastSwitchState) {\n light.state = currentSwitchState > lastSwitchState;\n}\nenter code here\n</code></pre>\n\n<p>In this case we can remove waiting and some code.</p>\n\n<p>I hope it makes sense. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T06:21:46.807",
"Id": "446935",
"Score": "0",
"body": "Unfortunately, it can't look like this. State of a light should change regardless if the current switch state is greater or less than last switch state. Let's imagine that all four switches are down. Light is off. When first switch goes up (current switch state is greater than last switch state) light is going to be on but then when second switch goes up the light is going to be off even though the current switch state is greater than last switch state. In your implementation state of light will not change if subsequent swiches will go up."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:56:17.490",
"Id": "229646",
"ParentId": "229630",
"Score": "1"
}
},
{
"body": "<p>Welcome to the world of programming where you never know exactly when you're done because the client doesn't know precisely what they want!</p>\n\n<p>The business solution is to this problem is to first sit down with the client, write down a proposal about some precise interpretation of what should happen. Have the client agree with this interpretation and sign it. Then implement this exactly as proposed.</p>\n\n<p>Then later on when the client tests your code they're either happy (yay, we're done!) or they are not. If they're not you write down what they want to change and make them pay for it again. Happy times! (for you at least, the client doesn't like paying again for something \"you should have known\" in the first place).</p>\n\n<p>Extra note: sometimes a client asks for something that cannot work. They might only realise the contradiction after you explained what exactly happens and offer them 2 possible ways that achieve 1 of the 2 things they ask for. In such a case you let the client decide which of the 2 is more important.</p>\n\n<hr>\n\n<p>To write working code we first need to know which exact result we want to get.<br>\nHere's the current problem more precisely:</p>\n\n<p>1) If 2 (or more) different switches are flipped within a certain time (half a second) of each other, ignore one of them and change the state of the light.<br>\n2) If a switch is flipped twice in rapid succession the second flip should <strong>not</strong> be ignored. </p>\n\n<p>Question: If (1) and (2) happen within half a second, should the light change state?</p>\n\n<p>My answer would be: If a switch is flipped once within half a second, the light should change state (compared to half a second earlier) irregardless of other switches.</p>\n\n<hr>\n\n<h1>Solution 1:</h1>\n\n<p>One possible solution is to modify the implementation of the switches themselves. If a switch is first in state off, and then flipped on, it will still say it's off for half a second. Only if it has remained on for half a second will it say it's turned on. This solves the problem of flipping the same switch twice in rappid succession ... with the downside that a light state will change at the earliest half a second after a switch is flipped. This is something the client has to agree on.</p>\n\n<p>If the client agrees on that change, the lightLogic can remain exactly the same as in Bob's solution since that correctly handles the remaining requirement of ignoring multiple switches flipping \"simultaniously\".</p>\n\n<p>This kind of solution is often used to prevent flickering in oversensitive keys. Consider a switch that has a bad contact. If switched halfway, it might rappidly say ON>OFF>ON>OFF even though you only flicked it once. Looking at a change from a small delay before makes sure that it will only fire once in such cases as intended.</p>\n\n<hr>\n\n<h1>Solution 2:</h1>\n\n<p>Alternatively if you require that the light switches on immediatly after a single switch is flipped, you'll have to do it differently.</p>\n\n<p>Let's say the light is switched from off to on. For the next 500 milliseconds, under which condition should the light be switched back off? -> If ALL switches are back to what they were when the light was still off.</p>\n\n<p>This looks similar to your idea, but only looking at the penultimate state isn't enough. If switch A is flipped, and then switch B is flipped 4 times, the light should still be ON because of switch A.</p>\n\n<p>An idea would be like this (<strong>note not tested</strong>):</p>\n\n<pre><code>int currentTime = millis();\nif (currentTime - lastChangeTime <= 500) { // might be considered simultanious\n if(currentSwitchState == initialSwitchState) { //all switches back to initial state\n light.state = initialLightState;\n lastChangeTime = 0; //respond to any new flip after this as if it was new.\n } // else light stays as it is now\n} else {\n if (currentSwitchState != previousSwitchState) { // start new case\n light.state = !light.state;\n lastChangeTime = currentTime;\n initialSwitchState = previousSwitchState;\n } // else nothing changed\n}\npreviousSwitchState = currentSwitchState; //always update latest known state\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T11:17:26.653",
"Id": "447595",
"Score": "0",
"body": "I like your second solution. To make the code work properly I had to add a new variable called _lastLightState_ and then assign it to _initialLightState_ when new case is going to happen. If I understand correctly, there is no one correct answer to this problem because all depends on requirements. Am I right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T11:22:16.827",
"Id": "447597",
"Score": "0",
"body": "Yes. It always depends on what you are trying to solve. Most often some details are missing so it's a good idea to write code in such a way that you can change it relatively easy later on, while at the same time only writing the code that is needed at that time to solve the part of the problem that is actually known to you. It's almost always impossible to tell which is the best solution (if one such solution even exists)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:26:21.893",
"Id": "447655",
"Score": "0",
"body": "Thank you for clarification and potential solutions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:44:50.600",
"Id": "229699",
"ParentId": "229630",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229699",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:44:56.503",
"Id": "229630",
"Score": "3",
"Tags": [
"java",
"algorithm"
],
"Title": "Changing state of a light (Uncle Bob's light switch problem)"
}
|
229630
|
<p><strong>Please review my BST Code</strong></p>
<p><strong>1. Class node</strong></p>
<p><code>class Node:</code></p>
<p><strong>2. Constructor</strong></p>
<pre><code>def __init__(self, data):
self.left = None
self.right = None
self.data = data
</code></pre>
<p><strong>3. Insert node</strong></p>
<pre><code>def insert(self, data):
if self.data:
if data < self.data:
if not self.left:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if not self.right :
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
</code></pre>
<p><strong>4. Node in delete any value</strong></p>
<pre><code>def getMinValue(self,node):
current = node
while(current.left is not None):
current = current.left
return current
def delValue(self,data):
if data < self.data:
self.left = self.left.delValue(data)
elif data > self.data:
self.right = self.right.delValue(data)
else:
if self.left is None:
temp = self.right
self = None
return temp
elif self.right is None:
temp = self.left
self = None
return temp
temp = self.getMinValue(self.right)
self.data = temp.data
self.right = self.right.delValue(temp.data)
return self
</code></pre>
<p><strong>5. Node in search any value</strong></p>
<pre><code>def getSearchValue(self,data):
if data == self.data:
return print(self.data,"True")
if data < self.data:
if self.left:
self.left.getSearchValue(data)
if data > self.data:
if self.right:
self.right.getSearchValue(data)
</code></pre>
<p><strong>6. Print tree</strong></p>
<pre><code>def print_tree(self):
if self.left:
self.left.print_tree()
print(self.data)
if self.right:
self.right.print_tree()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:45:24.673",
"Id": "446769",
"Score": "0",
"body": "Welcome to Code Review! You are welcome to also include a little bit of example code in your question and also telling the reviewers about your intention. Did you merely write it to learn Python? etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:23:30.580",
"Id": "446797",
"Score": "1",
"body": "Welcome to Code Review. 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 you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T09:13:34.447",
"Id": "446963",
"Score": "0",
"body": "Why did you add [tag:linked-list] as a tag?"
}
] |
[
{
"body": "<p>A few quick points that came to my mind when looking at your code:</p>\n\n<h1>Documentation</h1>\n\n<p>Your code has no documentation whatsoever. Python has so called <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">documentation strings</a>, which are basically <code>\"\"\"triple quoted text blocks\"\"\"</code> immediately following <code>def whatever(...)</code>. Example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def print_tree(self):\n \"\"\"Print the content of the tree\n\n This method performs an in-order traversal of the tree\n \"\"\"\n # ... your code here\n</code></pre>\n\n<p>Since your question title indicates that you're working with Python 3, also consider using <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> to document your code.</p>\n\n<h1>Naming</h1>\n\n<p>There is the infamous <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (aka PEP 8) which recommends to use <code>lower_case_with_underscores</code> for variable names and (member) functions. You do this for <code>print_tree</code>, but use <code>camelCase</code> for the other member functions.</p>\n\n<h1>Searching the tree</h1>\n\n<p>Your <code>getSearchValue</code> function is a little bit awkward in that it always returns <code>None</code>. Although your code promises to \"get\" the value, you instead print it to the console (together with the string <code>\"True\"</code>) and return the return value of <code>print</code> which is <code>None</code> (aka no return value in that case). Your function also only returns something (other than the implicit <code>None</code>) if the value was found. In my opinion something like </p>\n\n<pre><code>def has_value(self, data):\n \"\"\"Return True or False indicating whether the value is in the BST\"\"\"\n if data == self.data:\n return True\n if data < self.data:\n if self.left is not None:\n return self.left.has_value(data) \n if data > self.data:\n if self.right is not None:\n return self.right.has_value(data)\n return False\n</code></pre>\n\n<p>would be a more appropriate approach. As you can see, this function returns an appropriate bool value to signal the result. </p>\n\n<p>Another minor tweak: this implementation uses <code>if ... is not None:</code> to explicitly check for <code>None</code> as signaling value. <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">Since <code>None</code> is a singleton in Python, you should always use <code>is (not)</code> to check for equality.</a></p>\n\n<h1>Unnecessary parentheses</h1>\n\n<p>The parentheses around the condition in <code>while(current.left is not None):</code> are not needed. <code>while</code> works the same way as <code>if</code> in that regard. They are sometimes used for longer conditions that span multiple lines, since Python does implicit line joining in that case.</p>\n\n<hr>\n\n<p>I'm also not fully convinced about your <code>delValue</code> function, but unfortunately I'm a little bit short on time at the moment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T12:32:50.233",
"Id": "446776",
"Score": "0",
"body": "Thank a lot Alex to spent your valuable time to get the review of my code. Let me correct as per your suggestion and get back to you. Today I learned many coding fundamentals and styles from your suggestions. Thanks a lot once again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T12:45:21.563",
"Id": "446778",
"Score": "0",
"body": "Please remember that [it's against the site-policy to change the code in question once you have an answer](https://codereview.stackexchange.com/help/someone-answers). If you have significant improvements over the current version, asking a new question is the way to go."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T11:42:47.237",
"Id": "229632",
"ParentId": "229631",
"Score": "3"
}
},
{
"body": "<pre><code>**Code after the suggestion**\n</code></pre>\n\n<p><strong>1. Class node</strong></p>\n\n<p><code>class Node:</code></p>\n\n<p><strong>2. Constructor</strong></p>\n\n<pre><code>'''this is the constructor'''\ndef __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n</code></pre>\n\n<p><strong>3. Insert node</strong></p>\n\n<pre><code>def insert(self, data):\n''' this function work is insert the data in bst'''\n if self.data:\n '''insert left side value '''\n if data < self.data:\n if not self.left:\n self.left = Node(data)\n else:\n self.left.insert(data)\n '''insert right side value'''\n elif data > self.data :\n if not self.right :\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n</code></pre>\n\n<p><strong>4. Node in delete any value</strong></p>\n\n<pre><code>def getMinValue(self,node):\n '''this fuction work is get minimum value'''\n current = node\n while current.left is not None:\n current = current.left\n return current\ndef delValue(self,data): \n '''this fuction work delete value'''\n if data < self.data:\n self.left = self.left.delValue(data)\n elif data > self.data:\n self.right = self.right.delValue(data)\n else:\n if self.left is None:\n temp = self.right\n self = None\n return temp\n elif self.right is None:\n temp = self.left\n self = None\n return temp\n temp = self.getMinValue(self.right)\n self.data = temp.data\n self.right = self.right.delValue(temp.data)\n return self\n</code></pre>\n\n<p><strong>5. Node in search any value</strong></p>\n\n<pre><code>def getSearchValue(self,data):\n '''this function work finde a value in bst or return True or False'''\n if data == self.data:\n return print(True)\n if data < self.data:\n if self.left:\n self.left.getSearchValue(data)\n if data > self.data:\n if self.right:\n self.right.getSearchValue(data)\n return print(False)\n</code></pre>\n\n<p><strong>6. Print tree</strong></p>\n\n<pre><code>def printTree(self):\n '''this fuction work print a tree'''\n if self.left:\n self.left.printTree()\n print(self.data)\n if self.right:\n self.right.printTree()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T17:11:40.860",
"Id": "229650",
"ParentId": "229631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229632",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T10:47:15.347",
"Id": "229631",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tree",
"binary-search"
],
"Title": "Binary Search Tree implementation in Python 3"
}
|
229631
|
<p>I am currently working on an API and came across the following design.</p>
<p><a href="https://i.stack.imgur.com/IKcxI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IKcxI.jpg" alt="erm"></a></p>
<pre><code> // not mandatory
@ManyToOne
@JoinColumn(name = "person_id")
private Person person;
</code></pre>
<p>Actually, a telephone number should belong to a company, person or a contact form. However, this is logically not possible with the current design. So there is a small validation at the service level to make sure that there is always at least one dependency. </p>
<p>Now I was wondering if there is a better way to solve this. Because theoretically something can always go wrong and dependencies can be lost and the data would still be valid according to today's status.</p>
<p>I thought about creating a separate phone number object for each entity that inherits from the phone number. But somehow I don't really like the solution, but I think it's better than the previous one. What I don't like so much is that a lot more objects are created which also contain inheritance. </p>
<p><a href="https://i.stack.imgur.com/9pOsA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9pOsA.jpg" alt="new erm"></a></p>
<p>Is the new approach ok or how do you solve such problems? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:03:55.383",
"Id": "446783",
"Score": "4",
"body": "What speciality is there about the phone number for it to be in it's own entity? Just wondering cause from first thought I don't really think thats needed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:35:50.430",
"Id": "446786",
"Score": "0",
"body": "You can add a `constraint` on the database to ensure Phone Number is always referenced to another table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:32:11.473",
"Id": "446800",
"Score": "2",
"body": "A phone number itself shouldn't justify a database table. It's ok if you store metadata about the number or if you actually mean a \"phone contract\" (though contact form suggests otherwise). If not, consider the effects on transaction management that an additional table brings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:33:50.023",
"Id": "446845",
"Score": "0",
"body": "@Nico Sorry for the late answer. Um there is a phone type and a numbering of the numbers, but don't ask me why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:35:30.213",
"Id": "446848",
"Score": "0",
"body": "@TorbenPutkonen Thanks for your comment. Yes, I am aware of that. I'm in the process of optimizing the whole construct because it contains a lot of unnecessary stuff. Why it is an object I mentioned above."
}
] |
[
{
"body": "<p>I don't see anything wrong with your approach. </p>\n\n<p>Another option is to add a <code>PhoneNumberType</code> to the PhoneNumber table.</p>\n\n<p>In any case you should ensure the table has appropriate constraints added so that a PhoneNumber must relate to a table.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:32:27.540",
"Id": "446844",
"Score": "1",
"body": "Okay, thanks for your answer! That's what you like to hear. I also thought it was more important that the data is always 100% correct. We currently do this with the type simply via a string, but that's true, you should also replace that with an enum to further reduce the susceptibility to errors."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:38:54.060",
"Id": "229640",
"ParentId": "229634",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229640",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T12:39:41.070",
"Id": "229634",
"Score": "3",
"Tags": [
"java",
"hibernate",
"jpa"
],
"Title": "Hibernate - entity design with multiple dependencies"
}
|
229634
|
<p>I programmed a little in java a while back, and now I'm learning C#.<br>This is the first exercise of "medium" or "respectable" difficulty according to Codility, so I'm pretty pleased of finding out that the approach used by me was the same Sheng followed in codesays.<br>Writing here and in SO as a mémoire (check <a href="https://stackoverflow.com/a/58064536/6457989">this</a> if you'd like) helped me see that sometimes I get in a web of complicated thoughts and things that are very hard to program and are really bad in readability and performance. In the link I just posted I said I was going to talk me out of following futile, complicated ideas from that moment on, and so I did here and found the right solution.<br>
I already asked in three other posts, how my code was in terms of quality this past week, and I'm happy with the results of applying the great contributions I received by members of this amazing community.<br> This solution, as well as the others (<a href="https://codereview.stackexchange.com/questions/229566/earliest-time-frog-can-jump-to-the-other-side-of-a-river-in-c-codilitys-task">EarliestFrogJump</a>, <a href="https://codereview.stackexchange.com/questions/229371/codility-cyclic-rotation-in-c">cyclicRotation</a> & <a href="https://codereview.stackexchange.com/questions/229525/codilitys-permutation-check-in-c">permCheck</a>) pass with a 100% score (time complexity detected O(N+M)).</p>
<blockquote>
<p><strong><em>Task description</em></strong></p>
<hr>
<p>You are given N counters, initially set to 0, and you have two
possible operations on them:</p>
<ol>
<li><strong>increase(X) =></strong> counter X is increased by 1</li>
<li><strong>max counter =></strong> all counters are set to the maximum value of any counter. </li>
</ol>
<p>A non-empty array A of M
integers is given. This array represents consecutive operations:</p>
<p>if <code>A[K] = X</code>, such that 1 ≤ X ≤ N, then operation K is increase(X), if
<code>A[K] = N + 1</code> then operation K is max counter. For example, given
integer N = 5 and array A such that:</p>
<pre><code>A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
</code></pre>
<p>the values of the counters after each consecutive operation will be:</p>
<pre><code>(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)
</code></pre>
<p>The goal is to calculate the value of every counter after all operations.</p>
<p>Write a function:</p>
<p>class Solution { public int[] solution(int N, int[] A); }</p>
<p>that, given an integer N and a non-empty array A consisting of M
integers, returns a sequence of integers representing the values of
the counters.</p>
<p>Result array should be returned as an array of integers.</p>
<p>For example, given:</p>
<pre><code>A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
</code></pre>
<p>the function should return [3, 2, 2, 4, 2], as explained above.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N and M are integers within the range [1..100,000]; each element of
array A is an integer within the range [1..N + 1].</p>
</blockquote>
<p>And this is my code</p>
<pre><code> /// <summary>
/// Perform operations in a given array, according to another array's values
/// </summary>
/// <returns>
/// The array created of length <paramref name="N"> after applying operations
/// interpreted by integers found in <paramref name="A"/>
/// </returns>
public static int[] GetCountersAfterApplyingOperations(int N, int[] A)
{
//array of counters
int[] countersArr = new int[N];
//<max> is the largest value found in <countersArr>
int max = 0;
int index;
//when <N> is found in <A[]>, means all counters have to be set to <max>
int setAllCountersOp = N ;
//<floor> stores the value of <max> when a <setAllCountersOp> is found in <A[]>
int floor = 0;
for ( int i = 0; i < A.Length; i++ )
{
//As A[i] = 1, should convert <countersArr>={0} to {1}, then
index = A[i] - 1;
//if <index> == <setAllCountersOp> then the new <floor> = <max>
if ( index == setAllCountersOp )
{
floor = max;
}
//If 0 <= index < N, then the counterArr[index] should be incremented
else if ( index < N && index >= 0 )
{
//if <setAllCountersOp> was found, no counter can be smaller than <floor>
if ( countersArr[index] < floor )
{
countersArr[index] = floor + 1;
}
else
{
++countersArr[index];
}
if (countersArr[index] > max )
{
++max ;
}
}
}
//if counter is smaller than <floor>, it is set to that value.
for ( int i = 0; i < countersArr.Length; i ++ )
{
if ( countersArr[i] < floor)
{
countersArr[i] = floor;
}
}
return countersArr;
}
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:12:10.597",
"Id": "446818",
"Score": "2",
"body": "Do you mean _Thanks in advance_ or _Thanks for advise_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:13:06.473",
"Id": "446819",
"Score": "1",
"body": "I mean thanks in advance. Looks like english.stackexchange is merging with codereview lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:16:37.677",
"Id": "446821",
"Score": "2",
"body": "Since you're posting multiple posts with the same format, I'd like to say that you always put the same example twice (everything that follow **For example, given:** is useless, it's already explained above). I think it adds no value to your post. Apart from that, though, your posts are well written, good job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:19:45.173",
"Id": "446822",
"Score": "1",
"body": "Thanks @IEatBagels as you probably see I followed the valuables advices you gave me yesterday"
}
] |
[
{
"body": "<p>(It's me, once again, same review format)</p>\n<h2>Readability</h2>\n<ul>\n<li>There are <strong>way too many</strong> comments in your code. Comments should explain why you do something when it's not already clear in the code. In my opinion, the less comments some code needs, the better it is. Also, considering your comments are formatted almost exactly as your code is, it is veerryyy confusing. So, you comments only when absolutely necessary. For example : If a variable declaration needs a comment, your variable isn't well named. <code>max</code> could be renamed <code>maxValueInCounters</code> or... something like that. You get the vibe.</li>\n<li>Your variables should have better names. <code>index</code> doesn't mean much in this context. You could rename it <code>counterIndex</code>, for example.</li>\n<li>I'm not a big fan of this format : <code>if ( blablabla )</code>, I think the standard is <code>if (blablabla)</code>. At least, you should try to be consistent in your style, because you sometimes have extra space sometimes not.</li>\n</ul>\n<h2>Algorithm</h2>\n<ul>\n<li>When can this happen <code>index < N && index >= 0</code>? We already checked the scenario where <code>index == setAllCountersOp</code>, so in that case the <code>if</code> doesn't do anything.</li>\n</ul>\n<p>Apart from that, I think your algorithm is fine.</p>\n<h1></h1>\n<pre><code>public static int[] GetCountersAfterApplyingOperations(int N, int[] A)\n{\n int[] countersArr = new int[N];\n int max = 0;\n int index;\n int setAllCountersOp = N ;\n int floor = 0;\n\n for (int i = 0; i < A.Length; i++)\n {\n index = A[i] - 1;\n\n if (index == setAllCountersOp)\n {\n floor = max;\n continue;\n }\n\n if (countersArr[index] < floor)\n {\n countersArr[index] = floor + 1;\n }\n else\n {\n ++countersArr[index];\n }\n\n if (countersArr[index] > max)\n {\n ++max ;\n }\n }\n\n for (int i = 0; i < countersArr.Length; i ++)\n {\n if (countersArr[i] < floor)\n {\n countersArr[i] = floor;\n }\n }\n\n return countersArr;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:49:11.123",
"Id": "446834",
"Score": "1",
"body": "@dfhwze That's up to you but OP might learn a thing or two!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:50:39.353",
"Id": "446835",
"Score": "0",
"body": "I will think about it :) I'm not sure whether to start from your answer and refactor further or not. I think my answer might even be off-topic for being an alternative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:52:55.170",
"Id": "446836",
"Score": "1",
"body": "@dfhwze If you want to start from my answer I wouldn't be mad about it, if this changes your mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:32:29.260",
"Id": "446884",
"Score": "0",
"body": "Thanks again, I really appreciate it, and will use your advices. The thing about the `index < N && index >= 0` is very important actually... Index out of bound exceptions everywhere. `setAllCountersOp` is a different operation, and hence the name of the variable (which probably should be a constant.) I like the spacing between the parentheses, I just remove it to save space specially when posting here, so reader doesn't have to scroll horizontally, I will try to find better names and commend better in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:33:25.157",
"Id": "446885",
"Score": "1",
"body": "@newbie Then you should find the cause of those `IndexOutOfBoundException`s, because, reading your problem description, I don't see how they can happen!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:57:50.023",
"Id": "446888",
"Score": "0",
"body": "@ieatbagels imagine that A comes with negative ints - zeroes too-, or ints that are bigger than N, which definitely will happen. Then as the elements of A should increment countersArr[A[i] - 1] must go from 1 to N - 1, you couldn't just increment outside those bounds. I didn't get those exceptions while compiling because I knew I had to check that. But I'm pretty sure that only asking if the element is setAllCountersOp is not enough. I agree though in something, problem description and test cases are not that closely related in codility's tasks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T13:32:37.350",
"Id": "447000",
"Score": "0",
"body": "@newbie In your problem description you have the constraint **each element of array A is an integer within the range [1..N + 1].** In this case I don't see how the scenario you describes could happen *in the scope of the challenge*. If you wrote this piece of code to make it \"work for real life\", then I understand your point, but it wasn't clear in the question that's what you wanted to achieve :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:18:01.970",
"Id": "447035",
"Score": "1",
"body": "@ieatbagels as I said, I agree with you in the fact that the problem's description says numbers will go from 1 to N + 1, but as you also said, in real life scenarios it could happen. Still, I've done every exercise in codility in order till this one, and every time test cases try negative numbers and larger number that the exercise's range describes. I don't know if it's by chance or they intend that who solves the problem think of every case but they accomplished that on me. Now I analyze empty lists, negative numbers, huge numbers, 1 element list, etc, before compiling"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:18:39.527",
"Id": "447036",
"Score": "1",
"body": "@newbie I understand then!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:37:19.040",
"Id": "229645",
"ParentId": "229642",
"Score": "4"
}
},
{
"body": "<p>Most things have already been addressed by IEatBagels in <a href=\"https://codereview.stackexchange.com/a/229645/200620\">his answer</a>.</p>\n\n<h2>Compactness</h2>\n\n<p>I believe readability could be increased by writing more succinct code.</p>\n\n<p>Starting from this if-else block:</p>\n\n<blockquote>\n<pre><code>if (countersArr[index] < floor)\n{\n countersArr[index] = floor + 1;\n}\nelse\n{\n ++countersArr[index];\n}\n</code></pre>\n</blockquote>\n\n<p>We can see that we want to assign <code>x + 1</code> to <code>countersArr[index]</code> with <code>x</code> depending on the condition <code>countersArr[index] < floor</code>. Written more clearly:</p>\n\n<pre><code>if (countersArr[index] < floor)\n{\n countersArr[index] = floor + 1; // x = floor\n}\nelse\n{\n countersArr[index] = countersArr[index] + 1; // x = countersArr[index] \n}\n</code></pre>\n\n<p>Written in compact form using <code>Math.Max</code>, because we want <code>x</code> to be <code>countersArr[index]</code> with a bottom limit of <code>floor</code>:</p>\n\n<pre><code>countersArr[index] = Math.Max(countersArr[index], floor) + 1;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T20:37:26.583",
"Id": "446886",
"Score": "1",
"body": "Thanks. I will have this in mind from now on. I really like that last line"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T04:19:51.183",
"Id": "446926",
"Score": "0",
"body": "The intermediate code is to get from the initial code to that last line :) Just a thought process"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:26:40.673",
"Id": "229649",
"ParentId": "229642",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229649",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:04:08.833",
"Id": "229642",
"Score": "5",
"Tags": [
"c#",
"performance",
"beginner",
"programming-challenge",
"array"
],
"Title": "MaxCounters solution in C# from Codility"
}
|
229642
|
<p>I have an app that takes in "commands" in the form of <code>strings</code> that are parsed, and then passed off to a specific class based on the first word in the string.</p>
<p>Every <code>string</code> command is comprised of two or three words separated by spaces, and can also have an '=' followed by more words/numbers separated by commas.</p>
<p>Some examples:</p>
<p><code>add layer layerName=path,style</code> - commands with an <code>=</code> will follow this format. Three "parts" before the <code>=</code>, and any number of "parts" after, separated by commas.</p>
<p><code>assign database C:\temp folder\temp.mdb</code> - commands without an <code>=</code> will follow this format. At most three "parts".</p>
<p>Right now, I have a <code>List</code> comprised of all the possible "first" words, which are action verbs.</p>
<p>I parse the <code>string</code> command into a <code>string[]</code>, and switch on the first element to determine the correct function to call.</p>
<p>Here's the <code>List</code> containing the possible action verbs (shortened for better readability):</p>
<pre><code>//list of all types of commands. Add to this list if more commands are created.
private static readonly List<string> Commands = new List<string>
{"add", "assign", "cancel", "reload"}; //the actual list has ~50 strings
private static readonly string[] EmptyString = { string.Empty };
</code></pre>
<p>Here's my parse function:</p>
<pre><code>/// <summary>
/// Given a command string, will parse it
/// </summary>
public static void StartParse(string command)
{
if (string.IsNullOrWhiteSpace(command)) //make sure the command isn't empty
{
Log("Command is empty.");
return;
}
string textToParse = command;
if (textToParse.Contains('='))
{
string[] parts = textToParse.Split(new[] { '=' }, 2); //split the command into two parts
string[] secondPart;
//special case, only one command will have this format:
//ex: add layer layerName=filepath| ( OBJECTID = 10 ) OR ( OBJECTID = 20),styleName
if (parts[1].Contains('|') && parts[1].Contains('('))
{
string secondParts = "";
for (int i = 1; i < parts.Length; i++)
{
secondParts += parts[i];
}
secondPart = secondParts.Replace(@"""", "").Split(',');
}
else
{
secondPart = parts.Last().Replace(@"""", "").Split(',');
}
string[] firstPart = parts.First().Replace(@"""", "").Split(' '); //get rid of any quotes and split by spaces
//if a filepath is in the first part of a command and contains spaces, it could be split into more than three parts
//Note: if the above is true, the filepath will always start at the THIRD parameter
//ex: use database c:\users\test folder\temppath.mdb=...
if (firstPart.Length > 3)
{
StringBuilder sb = new StringBuilder();
for (int i = 2; i < firstPart.Length; i++) //file path will always start at the third parameter
{
sb.Append(firstPart[i] + " "); //make the different parts of the filepath one string
}
firstPart = new[] { firstPart[0], firstPart[1], sb.ToString() };
}
string[] allParts = MergeArrays(firstPart, secondPart); //make one array out of the two parts of the command
allParts[0] = allParts[0].ToLower(); //make everything lower
//If first element is not in the command list
if (!Commands.Contains(allParts.First()))
{
Log(allParts.First() + " is not a proper command.");
}
CallCommand(allParts);
}
else //if there is no '=' in the command
{
//creates a string array out of the command string, split by spaces
string[] parts = TextParser.ParseText(textToParse, ' ', '"').ToArray();
parts[0] = parts[0].ToLower();
//If first element is not in the command list
if (!Commands.Contains(parts.First()))
{
Log(parts.First() + " is not a proper command.");
}
CallCommand(parts);
}
}
</code></pre>
<p>Here's the function that determines which function to call using a switch statement:</p>
<pre><code>/// <summary>
/// Calls the correct command function or sends off a message based on the command verb.
/// The command verb is always the first argument.
/// </summary>
/// <param name="command">An array of strings representing all the arguments of a commmand.</param>
public static void CallCommand(string[] command)
{
string commandVerb = command.First().ToLower();
//shortened for better readability, actual switch has ~50 cases
switch (commandVerb)
{
case "add":
AddCommand.AddObj(command);
break;
case "assign":
AssignCommand.ParseCommand(command);
break;
case "cancel":
CancelCommand.ParseCommand(command);
break;
case "reload":
ReloadCommand.ParseCommand(command);
break;
default:
Log("This command doesn't exist.");
break;
}
}
/// <summary>
/// Merges two arrays into one
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns>Returns the merged array</returns>
public static T[] MergeArrays<T>(T[] first, T[] second)
{
T[] result = new T[first.Length + second.Length];
Array.Copy(first, result, first.Length);
Array.Copy(second, 0, result, first.Length, second.Length);
return result;
}
</code></pre>
<p>Here's a helper parser class I'm using:</p>
<pre><code>public static class TextParser
{
/// <summary>
/// Parses text given a delimiter and a text qualifier
/// </summary>
public static IEnumerable<string> ParseText(string line, char delimiter, char textQualifier)
{
if (line == null)
yield break;
bool inString = false;
StringBuilder token = new StringBuilder();
for (int i = 0; i < line.Length; i++)
{
var currentChar = line[i];
var prevChar = '\0';
prevChar = i > 0 ? line[i - 1] : '\0';
var nextChar = '\0';
nextChar = i + 1 < line.Length ? line[i + 1] : '\0';
if (currentChar == textQualifier && (prevChar == '\0' || prevChar == delimiter) && !inString)
{
inString = true;
continue;
}
if (currentChar == textQualifier && (nextChar == '\0' || nextChar == delimiter) && inString)
{
inString = false;
continue;
}
if (currentChar == delimiter && !inString)
{
yield return token.ToString();
token = token.Remove(0, token.Length);
continue;
}
token = token.Append(currentChar);
}
yield return token.ToString();
}
}
</code></pre>
<p>Here's an example of one of the command classes (they are all set up like this):</p>
<pre><code>public static class AssignCommand
{
/// <summary>
/// Starts parsing the command and assigns a tag to a feature object if one is found with the given name
/// </summary>
public static void ParseCommand(string[] command)
{
if (command.Length < 4)
{
Log("Assign command failed: must have at least four arguments total", null)
return;
}
var objectName = command[2];
var tag = command[3];
var feature = GlobalObjects.Map.FindFeatureByName(objectName); //Map is a third party object. GlobalObjects is a global class in the app containing the Map object. I didn't make it, it's been there forever.
if (feature != null)
{
feature.Tag = tag;
}
}
}
</code></pre>
<p>The priority is improving speed as much as possible, because there will be hundreds of thousands of these commands coming in.</p>
<p>One thing to note is that for each action verb, there is a class that matches it to handle the command, which is what you see in the switch statements. I'm not including these because they are long, but each of these have a <code>ParseCommand</code> function that just parses the string array into an object. I was thinking of making a base class for them, and using some kind of generics to reduce the switch statement to a single line maybe. Not sure if this would actually increase performance though.</p>
<p>Another thought was using a <code>Dictionary</code> instead of a switch statement, with the <code>Key</code> being the action verb and the <code>Value</code> being a delegate.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:29:10.467",
"Id": "446825",
"Score": "1",
"body": "Your examples don't match your code, is that as intended? We are also missing source code for your commands. And what is TextParser?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:34:01.163",
"Id": "446826",
"Score": "1",
"body": "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 title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:00:41.953",
"Id": "446838",
"Score": "1",
"body": "Sorry about that. Updated the title, and added the source code for TextParser. @dfhwze the command classes are very long so I'd rather not post, but the main part of them is that they all have a `ParseCommand(string[] command)` function that takes the parsed string command and turns them into specific objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:34:37.893",
"Id": "446846",
"Score": "1",
"body": "Added an example of one of the command classes at the bottom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:35:24.443",
"Id": "446847",
"Score": "0",
"body": "@ShapeOfMatter You added that class after an answer was made, but I don't think it invalidated the answer. ShapeOfMatter Is the edit ok for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:18:38.000",
"Id": "446979",
"Score": "1",
"body": "yeah, I'm fine with it."
}
] |
[
{
"body": "<p>It looks like what you've given us is a system that takes a string and parses it into a semantic command. </p>\n\n<p>About the code you've shown, I would suggest building less stuff yourself. Your whole parsing system should probably just be a (compiled) regex with capture groups. I do suggest using a dictionary instead of a switch statement. All that will probably make this system a lot smaller and easier to read, and <em>may</em> make it more performant. </p>\n\n<p>That said, this routing system (hopefully) isn't the performance bottleneck, and you're asking how to improve performance. You need to look at the system <em>that gets the list of command strings in the first place</em>, and you need to look at the system(s) that <em>run the commands</em>.</p>\n\n<p>Probably your end goal will be a stream reader feeding an asynchronous for-each loop with shared pools of connections to outside resources. But we can't see most of that system from here, and if there are \"only\" 100k items to process it <em>might</em> be overkill.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T01:01:30.457",
"Id": "446920",
"Score": "0",
"body": "Thanks for the answer! It's true this isn't the performance bottleneck, but I have no control over what is sending the commands and what is running the command (which is a third party control). I just wanted to do as much as possible with what I do have control. In reality, there could be ~100 commands being sent or hundreds of thousands, depending on what the user is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:16:02.807",
"Id": "446977",
"Score": "1",
"body": "Doing as much as possibly to speed up a piece of a system that's not slowing anything down isn't a good idea. You could reduce the time spend executing this code by 100, and it might make no perceivable difference in the system's performance. Furthermore, when you focus on just speed you tend to sacrifice other stuff. It's important to keep an eye out for bone-headed decisions that will _slow down_ the code, but your priorities should probably be readability, brevity, ease of testing, and ease of troubleshooting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T16:14:40.200",
"Id": "229647",
"ParentId": "229643",
"Score": "5"
}
},
{
"body": "<h3>General Observations</h3>\n\n<ul>\n<li>Method name <code>StartParse</code> suggests there would also be its complement <code>EndParse</code>. But there isn't. So the name is unfortunate.</li>\n<li>Method <code>StartParse</code> does not have a return value. This makes it a bit of a black box to consumers. I would expect is to return the command that you parsed. <em>\"I was thinking of making a base class for them\"</em> -> make a base class if commands share sufficient state, but prefer to make an interface <code>ICommand</code> if they share some state/operations.</li>\n<li>Since method <code>StartParse</code> is void, your silent capturing of argument checks goes unnoticed to the consumer. Prefer throwing an <code>ArgumentException</code> or <code>ArgumentNullException</code>.</li>\n<li>You have too many inline comments. If you feel these comments are required to accomodate the code, you might want to reconsider whether the code was written in a readable way to begin with. And comments as <code>.ToLower(); // make everything lower</code> are completely redundant.</li>\n<li>Method <code>StartParse</code> calls <code>CallCommand</code>. While I think it should have returned a command, calling a method name <code>CallCommand</code> in a parser feels very strange. <code>CallCommand</code> to me means that you're executing a command, not parsing some input data to a command.</li>\n<li>The method body of <code>StartParse</code> is verbose. You should really think about writing more compact code. The alternative solution provided in the other answer using a regex would be a good option, since the input language is rather simple.</li>\n<li>I see no benefit in having a context of allowed verbs <code>List<string> Commands</code> if the switch case in method <code>CallCommand</code> does not use that list to verify against. You have hard-coded the <code>commandVerb</code> switches. Again on bad input, you silently ignore the bad input without the consumer knowing that the command was unrecognized.</li>\n<li>Class <code>TextParser</code> could also use some refactoring. If you have recurring code like <code>currentChar == textQualifier && (prevChar == '\\0'</code> this should be a signal to rewrite the code to only have this line written once.</li>\n<li><code>AssignCommand</code> internally uses a reference to global shared static data <code>GlobalObjects.Map</code>. This makes testing and reusing the class hard. Consider using IoC. Rather than a static parse method, you could provide <code>ICommandParser</code> interface with one or more specific parser implementations. They could then be registered to a IoC container.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:08:51.063",
"Id": "447032",
"Score": "1",
"body": "All great points. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T04:39:36.983",
"Id": "229677",
"ParentId": "229643",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229647",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:18:14.703",
"Id": "229643",
"Score": "5",
"Tags": [
"c#",
"performance",
"parsing"
],
"Title": "Parsing ~100,000 strings and matching them to various classes"
}
|
229643
|
<p><strong>Turtle Doodle</strong> presents several panels which arrange themselves responsively. There is a canvas where the Turtle will move, leaving a paint trail behind him. A control panel allows various commands to be sent to the Turtle such as Forward, Back, Left, Right. An "info" area shows a textual <em>run-length-encoded</em> listing of all the Turtle commands that have been executed. Attached to the "info" area is a listing of the "undo" stack showing what pieces will be added when <em>redo</em> is clicked. Finally, iff the session is logged in to the database (using the "sign in" or "sign up" buttons) another panel lists all the saved doodles which can be loaded by clicking.
<a href="https://i.stack.imgur.com/LDnyV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LDnyV.png" alt="Turtle Doodle - medium layout"></a></p>
<p>This is my first project using php, and the largest chunk of javascript I've written so far. I'd like to know how I might better organize all the javascript code. I think it isn't <em>horrible</em> at the moment, but I feel that it's right on the verge of becoming unmanageble if I start adding more features. </p>
<p>Sizes (and <code># description</code>) of all my files:</p>
<pre><code>$ shopt -s extglob
$ wc *([^.]).{php,js,css}
66 105 1521 index.php # entry point
110 327 3684 page.php # page html
29 36 252 style.css # style tweaks
690 2043 15729 script.js # page js
177 542 4280 db.php # database functions
4 3 57 create.php # script - create db tables
4 3 52 delete.php # script - delete db tables
4 3 55 list.php # script - list all tables
7 15 133 load.php # script - simulate ajax request
1091 3077 25763 total
</code></pre>
<p>The directory also has local copies of jQuery and w3.css. I have the local jQuery arranged as a backup to the cdn link, but I haven't quite managed to arrange the same magic for w3.css yet. (see the top of <code>page.php</code> for this part)</p>
<h2>index.php</h2>
<p>This is the entry point for the project. In response to <code>GET</code> requests, it produces the html content from <code>page.php</code>. In response to <code>POST</code> requests, it checks the <code>$_POST['req']</code> field for a command name and then calls the appropriate database function defined in <code>db.php</code>.</p>
<pre><code><?php
session_start();
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
handle_post();
} else {
require "page.php";
}
function set_session_variables(){
if( isset($_SESSION['user']) ){
?>
<script>
sessionStorage.setItem('user', '<?php echo $_SESSION['user']; ?>' );
sessionStorage.setItem('pass', '<?php echo $_SESSION['pass']; ?>' );
</script>
<?php
} else {
?>
<script>
sessionStorage.removeItem('user');
sessionStorage.removeItem('pass');
</script>
<?php
}
}
function handle_post(){
global $pdo;
include("db.php");
switch( $_POST['req'] ){
case 'signin':
sign_in($_POST['user'], $_POST['pass']);
header("Location: ");
break;
case 'signup':
sign_up($_POST['user'], $_POST['mail'], $_POST['pass']);
header("Location: ");
break;
case 'signout':
sign_out();
session_unset();
$_SESSION = array();
session_destroy();
header("Location: ");
break;
case 'save':
save_doodle($_POST['user'], $_POST['pass'],
$_POST['name'], $_POST['drawing']);
break;
case 'delete':
delete_doodle($_POST['user'], $_POST['pass'],
$_POST['doodle']);
break;
case 'load':
header('Content-Type: application/json');
load_doodles($_POST['user'], $_POST['pass']);
break;
}
$pdo = null;
}
</code></pre>
<h2>page.php</h2>
<p>This file produces the html content for the page. If the session is logged in, it includes a bit of javascript (defined in <code>index.php</code>) to set the <code>user</code> and <code>pass</code> variables in <code>sessionStorage</code>. I've adopted a style here which deliberately omits any markup which isn't absolutely necessary. So, I never close <code><p></code> tags. And there isn't even a <code><body></code> tag. This seems to really help in making less code overall.</p>
<pre><code><!doctype html>
<html lang=en>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset=utf-8>
<title>Turtle Doodle</title>
<link href=w3css.4.w3.css rel=stylesheet type=text/css>
<!-- https://www.w3schools.com/w3css/4/w3.css -->
<link href=style.css rel=stylesheet type=text/css>
<script src=https://code.jquery.com/jquery-3.4.1.min.js></script>
<script>window.jQuery ||
document.write('<script src="jquery.3.4.1.min.js"\x3C/script>');</script>
<?php set_session_variables(); ?>
<script src="script.js"></script>
<header class="w3-container w3-green" >
<div id=brand class="w3-container w3-half">
<h1 ><nobr >Turtle Doodle</nobr></h1>
</div>
<div class="sign w3-container w3-half w3-bar w3-lightgreen" >
<div class="signedout w3-lightgreen" >
<button class="w3-bar-item w3-button" id="signin" >Sign In</button>
<button class="w3-bar-item w3-button" id="signup" >Sign Up</button>
</div>
<div class="signin w3-lightgreen" style="display:none" >
<form method=post >
<input type=hidden name=req value=signin >
<input class="w3-bar-item" type=text size=10
name=user id=userin placeholder="Username">
<input class="w3-bar-item" type=text size=10
name=pass placeholder="Password">
<button class="w3-bar-item w3-button" type=submit >Sign In</button>
</form>
</div>
<div class="signup w3-lightgreen" style="display:none" >
<form method=post >
<input type=hidden name=req value=signup>
<input class="w3-bar-item" type=text size=10
name=user id=userup placeholder="Username">
<input class="w3-bar-item" type=text size=10
name=mail placeholder="Email">
<input class="w3-bar-item" type=text size=10
name=pass placeholder="Password">
<button class="w3-bar-item w3-button" type=submit >Sign Up</button>
</form>
</div>
<div class="signout w3-lightgreen" style="display:none" >
<form method=post >
<input type=hidden name=req value=signout>
<button class="w3-bar-item w3-button" >Signout</button>
</form>
</div>
</div>
</header>
<main class="w3-container w3-row" >
<section class="canvas w3-container w3-col l6 m9 s12" >
<canvas>
</section>
<section class="controls w3-container w3-col l3 m3 s6" >
<h2 >controls</h2>
<nobr >
<button id=moveForward >F &#x2191;</button>
<button id=Slink >S</button>
<input id=step type=text size=1 value=20 onFocus=this.select()>
<button id=moveBack >B &#x2193;</button>
</nobr>
<nobr >
<button id=turnLeft >L &#x21b6;</button>
<button id=Alink >A</button>
<input id=angle type=text size=1 value=90 onFocus=this.select()>
<button id=turnRight >R &#x21b7;</button>
</nobr>
<p>
<nobr >
<button id=Tlink style="display:none" >Turtle</button>
<button id=Nlink >No Turtle</button>
</nobr>
<p>
</section>
<section class="info w3-container w3-col l3 m3 s6" >
<input id=doodleName type=text size=10 onFocus=this.select()>
<button align=right id=save >Save</button>
<button align=right id=new >New</button>
<h2 ><span align=left>info</span>
<span align=right>
<button id=undo align=right >Undo</button>
</span>
</h2>
<p><div class=doodle ></div></p>
<h2 align=right >
<button id=redo >Redo</button>
</h2>
<p align=right><div class=undo align=right></div></p>
</section>
<section class="saved w3-container w3-col l6 m12 s12" >
<h2 >doodles</h2>
<ol class=list >
</ol>
</section>
</main>
<footer class="w3-container" >
<p >Inspired by the ideas of Seymour Papert
<br >&copy; M. Joshua Ryan 2019
<br ><span id=debug ></span>
</footer>
</code></pre>
<h2>style.css</h2>
<p>I'm using w3.css to handle responsive layout and basic styling. So this file just defines a few colors and tweaks.</p>
<pre><code>h1 {
font: 2em/1.5 sans-serif;
}
#sign {
padding: .5em;
}
ul li {
display: inline;
padding: 0 1em;
}
main {
font: 11px/1.2 serif;
}
h2 {
font: 1.5em/1.2 sans-serif;
background: lightgreen;
color: darkgreen;
}
</code></pre>
<h2>script.js</h2>
<p>The big pile of javascript. I wonder if there are opportunities to make better use of jQuery constructs to simplify the js? Roughly, the top few functions are involved in attaching event handlers; the next portion implements these handlers and calling appropriate model-transforming functions; the next portion is a grab bag of all the remaining functions.</p>
<p>Would any of my (sets of) functions abstract nicely into separate modules?</p>
<pre><code>var List = [
];
var Doodle = {
drawing: [],
undo: []
};
$(function(){
let cx = $('canvas')[0].getContext('2d');
test_stroke( cx );
attach_controls();
load_local_doodle();
set_default_values();
if( sessionStorage.getItem('user') ){
show_signout();
load_doodles();
}
update();
});
function test_stroke( cx ){
cx.strokeStyle='blue';
cx.lineWidth=2;
cx.moveTo( 10, 10 );
cx.lineTo( 20, 20 );
cx.stroke();
}
function attach_controls(){
$("#signin").click(show_signin);
$("#signup").click(show_signup);
keys_on();
$("button.signout").click(destroy_session);
$("#moveForward").click(moveForward);
$("#moveBack").click(moveBack);
$("#turnLeft").click(turnLeft);
$("#turnRight").click(turnRight);
$("#Slink").click(focusStep);
$("#step").keypress(numeric);
$("#step").change(setStep);
$("#Alink").click(focusAngle);
$("#angle").keypress(numeric);
$("#angle").change(setAngle);
$("#Tlink").click(showTurtle);
$("#Nlink").click(hideTurtle);
$("#save").click(save);
$("#undo").click(undo);
$("#redo").click(redo);
$("#new").click(new_doodle);
$("#doodleName").focus(()=>keys_off());
$("#doodleName").change(()=>{Doodle.name = $("#doodleName").val();keys_on()});
}
function keys_on(){
document.addEventListener("keydown",onKey);
//$("document").keypress(onKey);
}
function keys_off(){
document.removeEventListener("keydown",onKey);
//$("body").off("keypress");
}
function set_default_values(){
let canvas = $('canvas')[0];
fix_canvas();
window.matchMedia( "(min-width: 400px)" ).
addEventListener( "change", fix_canvas);
window.matchMedia( "(min-width: 600px)" ).
addEventListener( "change", fix_canvas);
$("#step").val(20);
$("#angle").val(90);
}
function fix_canvas(){
if( window.matchMedia( "(min-width: 601px)" ).matches ){
fix_canvas_large();
} else if( window.matchMedia( "(min-width: 993px)" ).matches ){
fix_canvas_mid();
} else {
fix_canvas_small();
}
update();
}
function fix_canvas_small(){
let canvas = $('canvas')[0];
if( is_portrait() ){
canvas.width = -30 + $(window).width() * 12/12;
canvas.height = $(window).height() * 2/5;
} else {
canvas.width = -30 + $(window).width() * 12/12;
canvas.height = $(window).height() * 2/5;
}
}
function fix_canvas_mid(){
let canvas = $('canvas')[0];
if( is_portrait() ){
canvas.width = -30 + $(window).width() * 9/12;
canvas.height = $(window).height() * 2/5;
} else {
canvas.width = -30 + $(window).width() * 9/12;
canvas.height = $(window).height() * 2/5;
}
}
function fix_canvas_large(){
let canvas = $('canvas')[0];
if( is_portrait() ){
canvas.width = -30 + $(window).width() * 6/12;
canvas.height = $(window).height() * 3/5;
} else {
canvas.width = -30 + $(window).width() * 6/12;
canvas.height = $(window).height() * 3/5;
}
}
function is_portrait(){
return ($(window).height / $(window).width) > 1;
}
function onKey( event ){
//debug( "key: " + event.which );
if( event.ctrlKey ){
return true;
}
switch( event.which ){
case A('f'): case A('F'): case 38: return moveForward();
case A('l'): case A('L'): case 37: return turnLeft();
case A('r'): case A('R'): case 39: return turnRight();
case A('b'): case A('B'): case 40: return moveBack();
case A('a'): case A('A'): return focusAngle();
case A('s'): case A('S'): return focusStep();
case A('t'): case A('T'): return showTurtle();
case A('n'): case A('N'): return hideTurtle();
}
}
function A( c ){ return c.charCodeAt(0); }
function numeric( event ){
let whence = event.target;
let c = event.keyCode || event.which;
if( A('0') <= c && c <= A('9') ){
return true;
} else {
event.preventDefault();
event.stopPropagation();
whence.blur();
//doodle_add_mod( whence );
onKey( event );
return false;
}
}
function show_signin(){
$(".signedout").hide();
$(".signin").show();
$("#userin").focus();
keys_off();
return false;
}
function show_signup(){
$(".signedout").hide();
$(".signup").show();
$("#userup").focus();
keys_off();
return false;
}
function show_signout(){
$(".signedout").hide();
$(".signout").show();
}
function destroy_session(){
sessionStorage.removeItem('user');
sessionStorage.removeItem('pass');
$("form.signout")[0].submit();
}
function load_doodles(){
let u = sessionStorage.getItem('user');
let p = sessionStorage.getItem('pass');
$.ajax({
url: 'index.php',
type: 'POST',
data: {
'req': 'load',
'user': u,
'pass': p
},
dataType: 'json',
success: function(data){
//debug("ajax returned "+ JSON.stringify(data));
List = data;
update_list();
},
error: function(request,error){
debug("ajax error "+ error);
}
});
}
function save(){
let u = sessionStorage.getItem('user');
let p = sessionStorage.getItem('pass');
$.ajax({
url: 'index.php',
type: 'POST',
data: {
'req': 'save',
'user': u,
'pass': p,
'name': Doodle.name,
'drawing': Doodle.info
},
dataType: 'text',
success: function(data){
debug("ajax returned "+ data);
},
error: function(request,error){
debug("ajax error "+ error);
}
});
load_doodles();
update();
return false;
}
function new_doodle(){
Doodle.drawing = [];
Doodle.name = "doodle" + (List.length + 1);
update();
return false;
}
function moveForward(){
doodle_add_element('F');
return false;
}
function moveBack(){
doodle_add_element('B');
return false;
}
function turnLeft(){
doodle_add_element('L');
return false;
}
function turnRight(){
doodle_add_element('R');
return false;
}
function focusAngle(){
$("#angle").focus();
return false;
}
function setAngle(){
doodle_add_mod( $("#angle")[0] );
}
function focusStep(){
$("#step").focus();
return false;
}
function setStep(){
doodle_add_mod( $("#step")[0] );
}
function showTurtle(){
doodle_add_mod( { 'id': 'turtle', 'value': true } );
$("#Tlink").hide();
$("#Nlink").show();
return false;
}
function hideTurtle(){
doodle_add_mod( { 'id': 'turtle', 'value': false } );
$("#Tlink").show();
$("#Nlink").hide();
return false;
}
function undo(){
if( Doodle.drawing.length > 0 ){
Doodle.undo.push(Doodle.drawing.pop());
}
update();
return false;
}
function redo(){
if( Doodle.undo.length > 0 ){
Doodle.drawing.push(Doodle.undo.pop());
}
update();
return false;
}
function update(){
update_doodle_info();
update_undo_info();
update_drawing();
save_doodle_locally();
}
function save_doodle_locally(){
sessionStorage.setItem('doodle', JSON.stringify( Doodle ) );
}
function load_local_doodle(){
let x = sessionStorage.getItem('doodle');
if( x !== null ){
Doodle = JSON.parse( x );
debug(" loaded doodle, type: " + typeof( Doodle ) );
} else {
new_doodle();
}
}
function update_list(){
$(".list").html("");
List.forEach(function(val, idx){
$(".list").append(
"<li><a href=# onClick='return choose("+ idx +")'>"+
val.name +" "+
add_breaking_spaces( val.drawing ) +"</a> "+
"<a href=# onClick='return deletedoodle("+ val.id +")' >delete</a>"
);
});
}
function deletedoodle( idx ){
let u = sessionStorage.getItem('user');
let p = sessionStorage.getItem('pass');
$.ajax({
url: 'index.php',
type: 'POST',
data: {
'req': 'delete',
'user': u,
'pass': p,
'doodle': idx
},
dataType: 'text',
success: function(data){
debug("ajax returned "+ data);
load_doodles();
},
error: function(request,error){
debug("ajax error "+ error);
}
});
}
function choose( idx ){
Doodle.name = List[idx].name;
Doodle.drawing = [];
for( var i = 0; i < List[idx].drawing.length; i++){
switch( List[idx].drawing.charAt(i) ){
case 'F':
var s = read_number( List[idx].drawing, i+1 );
i += s.len;
doodle_add_element( { type: 'F', F: s.num } );
break;
case 'B':
var s = read_number( List[idx].drawing, i+1 );
i += s.len;
doodle_add_element( { type: 'B', B: s.num } );
break;
case 'L':
var s = read_number( List[idx].drawing, i+1 );
i += s.len;
doodle_add_element( { type: 'L', L: s.num } );
break;
case 'R':
var s = read_number( List[idx].drawing, i+1 );
i += s.len;
doodle_add_element( { type: 'R', R: s.num } );
break;
case 'T':
showTurtle();
break;
case 'N':
hideTurtle();
break;
case 'A':
var s = read_number( List[idx].drawing, i+1 );
i += s.len;
doodle_add_mod( { id: 'angle', value: +s.num } );
break;
case 'S':
var s = read_number( List[idx].drawing, i+1 );
i += s.len;
doodle_add_mod( { id: 'step', value: +s.num } );
break;
}
}
update();
return false;
}
function read_number( str, idx ){
var n = str.substring( idx ).match(/^\d+/);
if( n !== null ){
return { num: Number( n[0] ), len: n[0].length };
} else {
return { num: 1, len: 0 };
}
}
function update_drawing(){
let cx = $('canvas')[0].getContext('2d');
let pt = doodle_path_and_final_turtle();
let p = pt[0];
let t = pt[1];
cx.setTransform( 1, 0, 0, 1, 0, 0 );
cx.clearRect( 0, 0, cx.canvas.width, cx.canvas.height );
cx.beginPath();
cx.strokeStyle = 'blue';
cx.linewidth = 2;
autoscale( cx, p );
draw_path( cx, p );
cx.stroke();
if( t.show ){
draw_turtle( cx, t );
}
}
function autoscale( cx, p ){
let minx = p.map(
s => s.map( v=>v[0] ).reduce( (a, b) => Math.min( a, b ) )
).reduce( (a, b) => Math.min( a, b ) );
let maxx = p.map(
s => s.map( v=>v[0] ).reduce( (a, b) => Math.max( a, b ) )
).reduce( (a, b) => Math.max( a, b ) );
let miny = p.map(
s => s.map( v=>v[1] ).reduce( (a, b) => Math.min( a, b ) )
).reduce( (a, b) => Math.min( a, b ) );
let maxy = p.map(
s => s.map( v=>v[1] ).reduce( (a, b) => Math.max( a, b ) )
).reduce( (a, b) => Math.max( a, b ) );
debug( "x["+minx + ","+maxx + "] y["+miny + ","+maxy + "]" );
minx = Math.min( minx - 20, 0 );
maxx = Math.max( maxx + 20, cx.canvas.width);
miny = Math.min( miny - 20, 0 );
maxy = Math.max( maxy + 20, cx.canvas.height);
let dx = maxx - minx;
let dy = maxy - miny;
let sx = (cx.canvas.width) / dx;
let sy = (cx.canvas.height) / dy;
let s = Math.min( sx, sy );
let ss = Math.min( s, 1 );
//let ss = s * .5;
cx.translate( - minx, - miny ); debug( "translate -" + minx + ", -" + miny );
//cx.translate( minx + dx/2, miny + dy/2 ); debug( "translate " + (minx + dx/2) + ", " + (miny + dy/2) );
cx.scale( ss, ss ); debug( "scale " + ss + ", " + ss );
//cx.translate( (- dx/2)*ss, (- dy/2)*ss ); debug( "translate " + ((- dx/2)*ss) + ", " + ((- dy/2)*ss) );
}
function draw_path( cx, path ){
path.forEach(function(subpath){
cx.moveTo(...subpath[0]);
//debug( "moveto (" + subpath[0][0] + ", " + subpath[0][1] + ")" );
subpath.slice(1).forEach(function(point){
cx.lineTo(...point);
//debug( "lineto (" + point[0] + ", " + point[1] + ")" );
});
});
}
function doodle_path_and_final_turtle(){
let T = Turtle();
let p = [];
let s = [ [ T.xpos, T.ypos ] ];
Doodle.drawing.forEach(function(val){
if( val.type == 'mod') {
if( 'A' in val ){
T.adel = val.A;
}
if( 'S' in val ){
T.step = val.S;
}
if( 'T' in val ){
T.show = val.T;
if( T.show ){
p.push( s );
s = [ [ T.xpos, T.ypos ] ];
}
}
} else {
let t = val.type;
switch( val.type ){
case 'F':
T.xpos += val[t] * T.step * Math.cos( rad( T.angle ) );
T.ypos += val[t] * T.step * Math.sin( rad( T.angle ) );
if( T.show ){ s.push( [ T.xpos, T.ypos ] ); }
break;
case 'B':
T.xpos -= val[t] * T.step * Math.cos( rad( T.angle ) );
T.ypos -= val[t] * T.step * Math.sin( rad( T.angle ) );
if( T.show ){ s.push( [ T.xpos, T.ypos ] ); }
break;
case 'L':
T.angle -= val[t] * T.adel;
break;
case 'R':
T.angle += val[t] * T.adel;
break;
}
}
});
if( s ){
p.push( s );
}
return [ p, T ];
}
function draw_turtle( cx, t ){
cx.translate( t.xpos, t.ypos );
cx.scale( 1.5, 1.5 );
cx.rotate( rad( t.angle ) );
cx.beginPath();
var p = [ [.5, 0], [1, 1], [2, 3], [4, 4], [6, 4], [8, 3], [9, 1], [9.5, 0],
[9,-1], [8,-3], [6,-4], [4,-4], [2,-3], [1,-1],
[2, 0], [3, 3], [3, 0], [3,-3], [4, 2], [4,-2], [6, 2],
[6,-2], [7, 3], [7, 0], [7,-3], [8, 0] ];
var v = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0,
1, 14, 13, 14, 16,
18, 15, 2, 15, 3, 15, 18,
20, 22, 4, 22, 5, 22, 20,
23, 25, 6, 25, 7, 25, 23,
21, 24, 9, 24, 10, 24, 21,
19, 17, 11, 17, 12, 17 ];
cx.moveTo(...p[v[0]]);
for( let i = 1; i < v.length; i++ ){
cx.lineTo(...p[v[i]]);
}
cx.strokeStyle = 'darkgreen';
cx.lineWidth = 1;
cx.stroke();
}
function rad( deg ){
return deg * ( Math.PI / 180.0 );
}
function Turtle(){
return {
xpos: 10,
ypos: 10,
angle: 0,
step: 20,
adel: 90,
show: true,
};
}
function update_doodle_info(){
$("#doodleName").val(Doodle.name);
$(".doodle").html("");
var x = "";
Doodle.drawing.forEach(function(val){
if( val.type == 'mod' ){
if( 'A' in val ){
x += 'A' + val.A;
}
if( 'S' in val ){
x += 'S' + val.S;
}
if( 'T' in val ){
x += val.T ? 'T' : 'N';
}
} else {
if( val[val.type] == 1 ){
x += val.type;
} else {
x += val.type + val[val.type];
}
}
});
Doodle.info = x;
x = add_breaking_spaces( x );
//debug( x );
$(".doodle").html(x);
}
function update_undo_info(){
$(".undo").html("");
var x = "";
Doodle.undo.forEach(function(val){
if( val.type == 'mod' ){
if( 'A' in val ){
x = 'A' + val.A + x;
}
if( 'S' in val ){
x = 'S' + val.S + x;
}
if( 'T' in val ){
x = (val.T ? 'T' : 'N') + x;
}
} else {
if( val[val.type] == 1 ){
x = val.type + x;
} else {
x = val.type + val[val.type] + x;
}
}
});
Doodle.undoinfo = x;
x = add_breaking_spaces( x );
$(".undo").html(x);
}
function add_breaking_spaces( x ){
let y = x.split("");
let i = x.length - 1;
let gap = 4;
i -= i % gap;
//debug( i );
for( ; i > 0; i -= gap ){
//debug( "splice( " + i + ", '&lt;wbr>' );");
y.splice( i, 0, '<wbr>' );
}
let z = y.join("");
//debug( z );
return z;
}
function doodle_add_element( el ){
if( typeof(el) == 'object' ){
if( Doodle.drawing.length > 0 ){
let last = Doodle.drawing[ Doodle.drawing.length - 1 ];
if( last.type == el.type ){
if( el.type == 'mod' ){
Object.assign( last, el );
} else {
last[el.type] += el[el.type];
}
} else {
Doodle.drawing.push( el );
}
} else {
Doodle.drawing.push( el );
}
update();
} else {
//debug( "creating move object" );
let x = { 'type': el };
x[el] = 1;
doodle_add_element( x );
}
}
function doodle_add_mod( whence ){
switch( whence.id ){
case 'angle':
doodle_add_element( { 'type': "mod", 'A': whence.value } );
break;
case 'step':
doodle_add_element( { 'type': "mod", 'S': whence.value } );
break;
case 'turtle':
doodle_add_element( { 'type': "mod", 'T': whence.value } );
break;
}
}
function debug(msg){
let x = $("#debug").html();
$("#debug").html( x + '<br>' + msg );
}
</code></pre>
<h2>db.php</h2>
<p>Connect to database and define functions for interaction. <code>index.php</code> calls these functions in response to <code>POST</code> requests. The command line scripts <code>create.php</code>, <code>delete.php</code>, <code>list.php</code>, <code>load.php</code> also call these functinos. Prepared statements are used throughout to protect the database from injections.</p>
<pre><code><?php
$host = '127.0.0.1';
$user = '';
$pass = '';
$db = 'doodle';
$charset = 'utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
function create_database_tables(){
global $pdo;
$stmt = $pdo->query('CREATE TABLE users (
uid INT NOT NULL AUTO_INCREMENT,
user VARCHAR(100),
email VARCHAR(100),
pass VARCHAR(100),
PRIMARY KEY(uid) );');
if( ! $stmt ){ die("Error creating users table"); }
$stmt = $pdo->query("INSERT INTO users (user, email, pass)
VALUES ('m', 'm@m.m', 'm')");
if( ! $stmt ){ die("Error creating user"); }
$sql = $pdo->query('CREATE TABLE doodles (
id INT NOT NULL AUTO_INCREMENT,
uid INT NOT NULL,
name VARCHAR(100),
drawing VARCHAR(512),
created TIMESTAMP,
PRIMARY KEY(id) );');
if( ! $stmt ){ die("Error creating doodles table"); }
$stmt = $pdo->query("INSERT INTO doodles (uid, name, drawing)
VALUES (1, 'doodle1', 'FRFLFRFLF')");
if( ! $stmt ){ die("Error creating doodle"); }
}
function list_database_tables(){
global $pdo;
echo "users:\n";
$stmt = $pdo->query('SELECT * FROM users');
while( $row = $stmt->fetch() ){
print_r($row);
echo "\n";
}
echo "doodles:\n";
$stmt = $pdo->query('SELECT * FROM doodles');
while( $row = $stmt->fetch() ){
print_r($row);
echo "\n";
}
}
function delete_database_tables(){
global $pdo;
$stmt = $pdo->query('DROP TABLE users;');
if( ! $stmt ){ die("Error deleting users table"); }
$stmt = $pdo->query('DROP TABLE doodles');
if( ! $stmt ){ die("Error deleting doodles table"); }
}
function sign_in( $user, $pass ){
global $pdo;
$user = sanitize( $user, 'string' );
$pass = sanitize( $pass, 'string' );
$stmt = $pdo->prepare('SELECT * FROM users WHERE
(user = ? OR email = ?) AND pass = ?;');
$stmt->execute([$user, $user, $pass]);
$row = $stmt->fetch();
if( ! $row ){ die( "No such user or wrong password." ); }
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
}
function sign_up( $user, $mail, $pass ){
global $pdo;
$user = sanitize( $user, 'string' );
$pass = sanitize( $pass, 'string' );
$mail = sanitize( $user, 'email' );
$stmt = $pdo->prepare('INSERT INTO users (user, email, pass)
VALUES (?, ?, ?);');
$status = $stmt->execute([$user, $mail, $pass]);
if( ! $status ){ die("Failed to add user."); }
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
}
function sign_out(){
global $pdo;
}
function save_doodle( $user, $pass, $name, $drawing ){
global $pdo;
$uid = get_uid( $user, $pass );
$stmt = $pdo->prepare('INSERT INTO doodles (uid, name, drawing)
VALUES (?, ?, ?);');
$status = $stmt->execute([$uid, $name, $drawing]);
if( ! $status ){ die("Failed to save drawing."); }
echo "Ok.";
}
function delete_doodle( $user, $pass, $doodle ){
global $pdo;
$uid = get_uid( $user, $pass );
$stmt = $pdo->prepare('DELETE FROM doodles WHERE uid=? AND id=?');
$status = $stmt->execute([$uid, $doodle]);
if( ! $status ){ die("Failed to delete doodle."); }
echo "Ok.". $doodle . " " . $status;
}
function load_doodles( $user, $pass ){
global $pdo;
$uid = get_uid( $user, $pass );
echo json_encode( pdo($pdo, 'SELECT * FROM doodles WHERE uid=?',
[ $uid ] )->fetchAll() );
}
function get_uid( $user, $pass ){
global $pdo;
return pdo( $pdo, 'SELECT (uid) FROM users WHERE user=? AND pass=?;',
[ sanitize($user, 'string'), sanitize($pass, 'string') ]
)->fetch()['uid'];
}
function sanitize( $var, $type ){
switch($type){
case 'string':
return filter_var( $var, FILTER_SANITIZE_STRING );
case 'email':
return filter_var( $var, FILTER_SANITIZE_EMAIL );
}
}
function pdo($pdo, $sql, $args = NULL)
{
if (!$args)
{
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
</code></pre>
<h2>create.php</h2>
<p>Script to set up database tables, creating default user 'm' and saving one doodle for 'm'.</p>
<pre><code><?php
include_once("db.php");
create_database_tables();
</code></pre>
<h2>delete.php</h2>
<p>Script to delete all database tables.</p>
<pre><code><?php
include("db.php");
delete_database_tables();
</code></pre>
<h2>list.php</h2>
<p>Script to list contents of all database tables.</p>
<pre><code><?php
include_once("db.php");
list_database_tables();
</code></pre>
<h1>load.php</h1>
<p>Script to simulate the ajax request that script.js:load_doodles() performs. Outputs the exact JSON encoded data that the javascript function will receive.</p>
<pre><code><?php
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST['req'] = 'load';
$_POST['user'] = 'm';
$_POST['pass'] = 'm';
require 'index.php';
</code></pre>
<p>Of course I'd love to know if any parts can be improved, but I'm specifically concerned about how to organize all the javascript into manageable pieces.</p>
|
[] |
[
{
"body": "<p>I would limit my review to db.php file only.</p>\n<p>First of all, I see you made use of some of my advises already, probably visited some of my articles. Sadly, not all recommendations are followed, but that's OK, we'll review them.</p>\n<h3>Connection</h3>\n<p>The connection part is simply OK, nothing to review</p>\n<h3>Structure</h3>\n<p>Regarding the structure, I would say this file is a bit bloated. And contain a code belongs to different, so to say, <em>layers of responsibility</em>. Such parts as the connection and a pdo() function have a global responsibility. they could be used in any project and even in any part of every project.</p>\n<p>Whereas other functions are quite specific and totally useless in any other project part. Also, the connection credentials are project-specific.</p>\n<p>It order to make your design modular and reusable, I would</p>\n<ul>\n<li>leave in db.php only the connection code and general purpose functions such as pdo()</li>\n<li>move the credentials into a separate file and include it in db.php</li>\n<li>all specific functions I would move into respective files. Honestly, I don't see a point in having a file consists of a single line that calls a function. Why not to put the function code directly into specific files? At least it will make your code better organized and editing each particular code block would be easier. Honestly, finding a particular function in the current db.php is a challenge.</li>\n</ul>\n<h3>Global</h3>\n<p>is frowned upon. it adds magic. You see a function call but have no idea where does it take the database connection from. It is always good to have all resources used by a function to be explicitly set.</p>\n<h3>Error reporting</h3>\n<p>Your current approach is simply redundant. In reality, you will never see an error message like "Error creating users table" - PDO will throw an exception and and halt the script execution prior that. So, all such code snippets</p>\n<pre><code>if( ! $stmt ){ die("Error creating users table"); }\n</code></pre>\n<p>are rather useless and need to be removed.</p>\n<h3>Inconsistent use of the helper function.</h3>\n<p>Somewhere you are using it and somewhere not. It would be a good idea to make it consistent.</p>\n<p>Let's rewrite save_doodle() function based on the tree recent recommendations:</p>\n<pre><code>function save_doodle($pdo, $user, $pass, $name, $drawing )\n{\n $uid = get_uid( $user, $pass );\n $sql = 'INSERT INTO doodles (uid, name, drawing) VALUES (?, ?, ?)');\n pdo($pdo, $sql, [$uid, $name, $drawing]);\n}\n</code></pre>\n<p>Much more clean, isn't it?</p>\n<h3>Sanitization</h3>\n<p>This is a complex one. There are many things that are get confused in a single word "santitization", so it's better to avoid it at all.</p>\n<p>Regarding the process, you need to differentiate two things,</p>\n<ul>\n<li>data validation</li>\n<li>data formatting</li>\n</ul>\n<p>Sadly, both are misplaced in your sanitize() function.</p>\n<p><strong>Data validation</strong> is testing the user input according to some rules and <strong>telling the user back</strong> if some tests failed. Checking email format for example. Just calling "sanitize" on the wrong email will save an empty string in the database which is not what you want. You need to decide, whether you want to validate the user input. If you do, make it vocal: notify a user about a failed validation.</p>\n<p>However, for such a simple script you may put it aside for the moment.</p>\n<p><strong>Data formatting</strong> is make the data usable in the <strong>certain medium</strong> it is going to be used. Some examples</p>\n<ul>\n<li>when used inside HTML, the data must be HTML-formatted</li>\n<li>when used inside SQL, the data must be SQL-formatted (by using prepared statements)</li>\n<li>when used inside JS, the data must be JS-formatted</li>\n<li>and so on, you get the idea</li>\n</ul>\n<p>But <strong>neither is done by the <code>sanitize()</code> function</strong>. So you have to get rid of it and make your data formatting <strong>destination-specific</strong>. In other words you have to format your data right before use and limit such a formatting only to a certain medium. For example, for the DSQL query, all formatting you need is a prepared statement.</p>\n<h3>Storing user passwords</h3>\n<p>Is a notorious story. Never ever store passwords in plain text but only in the form of a cryptographic hash. There are <a href=\"https://stackoverflow.com/questions/30279321/how-to-use-password-hash\">specific functions</a> for that. In order to help you with the user login part, I've got a ready made <a href=\"https://phpdelusions.net/pdo_examples/password_hash\" rel=\"nofollow noreferrer\">code for the user authorization</a> whose password is properly hashed</p>\n<h3>Authorization</h3>\n<p>I see you are asking a user to enter the username and the password every time they perform an action. Although you could leave it as is for the time being, consider using a simple authentication. it is as simple as calling <code>session_start()</code> on every request and storing the authenticated user's id in the $_SESSION array element. Then you could get the user id any time from that variable back.</p>\n<h3>Separation of concerns</h3>\n<p>This is a rather important one. but it can be simplified as a rule of thumb: <strong>no function should output anything on its own</strong> (unless the only purpose of the function is output).</p>\n<p>There is a business logic and there is a display logic. They should never interfere. <code>delete_doodle()</code> is a <strong>business logic</strong>. You'd never know how you would call this function and how you would notify a user of its success. Make this function return only a boolean value whereas output should be done elsewhere.</p>\n<p>In practice this one rather contradicts with the earlier suggestion to move the code from function to files, so it's just a generalized advise on using functions in general. A function just calculates some result and returns it, while any output is only done in a designated placeor by a designated agent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T10:20:34.443",
"Id": "446969",
"Score": "0",
"body": "Much obliged! I'll get to work on these issues. Evidently I did not read your articles closely enough. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T08:35:55.663",
"Id": "229685",
"ParentId": "229652",
"Score": "6"
}
},
{
"body": "<h2>PHP</h2>\n\n<h3>Constants</h3>\n\n<p>The first five variables in <code>db.php</code> could be declared as constants since they shouldn't be changed:</p>\n\n<pre><code>define('DB_HOST', '127.0.0.1');\ndefine('DB_USER', '');\ndefine('DB_PASS, '');\ndefine('DB_NAME, 'doodle');\ndefine('DB_CHARSET', 'utf8mb4');\n</code></pre>\n\n<p>And notice the prefix <code>DB_</code> was added to those names to specify that those values pertain to the database. That way variable names like <code>$user</code> don't get re-used between the database connection information and parameters to functions like <code>sign_in()</code>, <code>sign_up()</code>, etc.</p>\n\n<p>However string interpolation wouldn't work with constant, so a line like:</p>\n\n<blockquote>\n<pre><code>$dsn = \"mysql:host=$host;dbname=$db;charset=$charset\";\n</code></pre>\n</blockquote>\n\n<p>would need to rely on concatenation: </p>\n\n<pre><code>$dsn = \"mysql:host=\" . DB_HOST . \";dbname=\" . DB_NAME . \";charset=\" . DB_CHARSET;\n</code></pre>\n\n<h3>short echo</h3>\n\n<p>In <em>index.php</em> there are script tags with PHP renderings - like:</p>\n\n<pre><code>sessionStorage.setItem('user', '<?php echo $_SESSION['user']; ?>' );\n</code></pre>\n\n<p>Depending on your version of PHP, you could consider using <a href=\"https://www.php.net/manual/en/language.basic-syntax.phptags.php\" rel=\"nofollow noreferrer\"><code><?=</code></a> instead of <code><?php echo</code>. </p>\n\n<p>For more information, refer to <a href=\"https://softwareengineering.stackexchange.com/a/151694/244085\">this answer and others to <em>Is it bad practice to use <code><?=</code> tag in PHP?</em></a></p>\n\n<h2>JS</h2>\n\n<p>Overall I see quite a bit of redundancy in these functions. Perhaps event delegation could be used to simplify all the event handlers setup in <code>attach_controls()</code>. For example, a single click handler could check the <em>id</em> attribute of the element that was clicked and if that corresponds to a defined function then call that function (e.g. <code>turnLeft</code>, <code>turnRight</code>, <code>save</code>, <code>undo</code>, etc.</p>\n\n<p>There is also a lot of repeated code in the <code>fix_canvas_*</code> functions. The only differences appear to be the multipliers on the fractions (e.g. <code>12/12</code>, <code>9/12</code>, <code>6/12</code> and <code>2/5</code>, <code>3/5</code>. Those values could be passed as parameters or a parameter could be made for <code>large</code>, <code>mid</code> or <code>small</code> that leads to those values being used.</p>\n\n<h3>Simply anonymous function</h3>\n\n<p>The second to last focus handler setup in <code>attach_controls()</code> has an arrow function with one statement:</p>\n\n<blockquote>\n<pre><code>$(\"#doodleName\").focus(()=>keys_off());\n</code></pre>\n</blockquote>\n\n<p>that could be simplified using a function name reference instead:</p>\n\n<pre><code>$(\"#doodleName\").focus(keys_off);\n</code></pre>\n\n<h3><code>document.write()</code></h3>\n\n<p>In <em>page.php</em> I see </p>\n\n<blockquote>\n<pre><code><script>window.jQuery ||\n document.write('<script src=\"jquery.3.4.1.min.js\"\\x3C/script>'); \n</script>\n</code></pre>\n</blockquote>\n\n<p>Note that <code>document.write()</code> will: </p>\n\n<blockquote>\n <p>Writing to a document that has already loaded without calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/open\" rel=\"nofollow noreferrer\"><code>document.open()</code></a> will automatically call <code>document.open</code>.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/write#Notes\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>And </p>\n\n<blockquote>\n <p>The <code>Document.open()</code> method opens a document for <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/write\" rel=\"nofollow noreferrer\">writing</a>.</p>\n \n <p>This does come with some side effects. For example:</p>\n \n <ul>\n <li>All event listeners currently registered on the document, nodes inside the document, or the document's window are removed.</li>\n <li>All existing nodes are removed from the document. <sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/open\" rel=\"nofollow noreferrer\">2</a></sup></li>\n </ul>\n</blockquote>\n\n<p>Which means that you should be aware that the entire HTML could be replaced by <code><script src=\"jquery.3.4.1.min.js\"\\x3C/script></code> if <code>window.jQuery</code> evaluates to <code>false</code> when that script executes. Perhaps it would be better to wait for either that jQuery script or else the DOM to load and if jQuery isn't loaded then create a script tag and append it to the DOM instead of using <code>document.write()</code>.</p>\n\n<h3>Prefer <code>const</code></h3>\n\n<p>Use <code>const</code> instead of <code>let</code> for values that shouldn't be re-assigned. For example, in <code>deletedoodle()</code> the variables <code>u</code> and <code>p</code> don't get re-assigned and can be declared with <code>const</code>. This helps avoid accidental re-assignment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:55:12.477",
"Id": "448442",
"Score": "0",
"body": "Having a single click handle is brilliant! I added that very early in [my new design](https://groups.google.com/d/msg/comp.lang.javascript/nQH8iVneyu8/5bk6nQDpBAAJ)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:15:21.620",
"Id": "229919",
"ParentId": "229652",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229685",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T17:36:01.530",
"Id": "229652",
"Score": "6",
"Tags": [
"javascript",
"php",
"jquery",
"ecmascript-6"
],
"Title": "Turtle Doodle (my first web app)"
}
|
229652
|
<p><a href="https://docs.microsoft.com/en-gb/windows/win32/winmsg/timers" rel="nofollow noreferrer">WinAPI Timers</a> can be quite tricky to work with, as anyone who's tried to use them and fallen foul of one of the many pitfalls probably knows. Problems such as screen freezing, crashes, uncontrolled printing to the debug window etc. will be familiar, and so I've tried to make some code to mitigate these issues, by providing a friendlier API to wrap the temperamental bits and hopefully make working with timers a bit easier:</p>
<p><a href="https://i.stack.imgur.com/udU9l.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/udU9l.gif" alt="Example program"></a></p>
<p>As you can see, editing cells (even using the formula bar), multiple timers, switching windows etc. are all possible within the limitations of WinAPI timers.</p>
<p>I was going to post a section here about the specific problems I've encountered, what causes them (to the best of my knowledge) and how I try to deal with them. However it was getting way too big, so I've moved it to the <a href="https://github.com/Greedquest/VBA-Timing-Methods" rel="nofollow noreferrer">Github Repo's README</a>, I would recommend checking it out if, after reading the code, you're still not sure why I've gone about it the way I have. Also I'd like to arm any potential reviewers with the subject specific knowledge to break my code efficiently!</p>
<h1>Project Layout</h1>
<p>The code is intended for use in an add-in (a <em>.xlam</em> file). The main public interface is the <code>TickerAPI</code> predeclared class (used like a static class in other languages); this exposes some friendly helper methods which take in callback functions and other timer parameters and pass them on to the underlying APIs. It also responsible for raising public errors and it stores references to data from the user so that they can be passed to callbacks without risk of the data falling out of scope.</p>
<h3>Main Class:<code>TickerAPI</code></h3>
<pre><code>'@Exposed
'@Folder("FirstLevelAPI")
'@PredeclaredID: To ensure it's a singleton in other projects and avoid async nulling
'@ModuleDescription("API for setting up timers to callback functions, wraps Windows Timers")
Option Explicit
Public Enum TimerError
[_ErrBase] = 0
[_Start] = vbObjectError + [_ErrBase]
CreateTimerError
DestroyTimerError
TimerNotFoundError
SynchronousCallError
InvalidTimerFunctionError
GenerateTimerDataError
[_End]
End Enum
Private Const Default_Max_Timer_Count As Long = 100
Private Type tCallback
maxTimerCount As Long
timerManager As ITimerManager
timerDataRepo As New TimerRepository
End Type
Private this As tCallback
Private Sub Class_Initialize()
'Set up defaults
this.maxTimerCount = Default_Max_Timer_Count
Set this.timerManager = New WindowsTimerManager
End Sub
'@Description("Create new timer instance with optional synchronous first call. Returns the ID of the newly created windows timer. Can raise SynchronousCallError if timerFunction fails (and is trapped - unlikely). Raises CreateTimerError if there is an API error")
Public Function StartUnmanagedTimer(ByVal timerFunction As LongPtr, Optional ByVal runImmediately As Boolean = True, Optional ByVal delayMillis As Long = 500, Optional ByVal data As Variant) As LongPtr
Const loggerSourceName As String = "StartUnmanagedTimer"
On Error GoTo generateTimerDataFail
Dim timerInfo As TimerData
Set timerInfo = this.timerDataRepo.Add(UnmanagedCallbackWrapper.Create(timerFunction, data))
On Error GoTo createTimerFail
this.timerManager.StartTimer timerInfo, delayMillis
StartUnmanagedTimer = timerInfo.ID
On Error GoTo scheduleProcFail
If runImmediately Then
If Not this.timerManager.tryTriggerTimer(timerInfo) Then
'queue is too full right now, no point scheduling as it wouldn't be evaluated in time anyway
'could try flushing the queue instead
log WarnLevel, loggerSourceName, "Message queue is too full to post to, so cannot runImmediately"
End If
End If
log InfoLevel, loggerSourceName, printf("UnmanagedTimer with id {0} created", timerInfo.ID)
Exit Function
generateTimerDataFail:
logError "timerSet.Add", Err.Number, Err.Description
raisePublicError GenerateTimerDataError, loggerSourceName
Resume 'for debugging - break above and jump to the error-raising statement
createTimerFail:
logError "createTimer", Err.Number, Err.Description
this.timerDataRepo.Remove timerInfo
raisePublicError CreateTimerError, loggerSourceName
Resume
scheduleProcFail:
logError "scheduleProc", Err.Number, Err.Description
KillTimerByID timerInfo.ID 'NOTE may raise its own public error
raisePublicError SynchronousCallError, loggerSourceName
Resume
End Function
Public Function StartManagedTimer(ByVal timerFunction As ITimerProc, Optional ByVal runImmediately As Boolean = True, Optional ByVal delayMillis As Long = 500, Optional ByVal data As Variant) As LongPtr
Const loggerSourceName As String = "StartManagedTimer"
On Error GoTo generateTimerDataFail
Dim timerInfo As TimerData
Set timerInfo = this.timerDataRepo.Add(ManagedCallbackWrapper.Create(timerFunction, data))
On Error GoTo createTimerFail
this.timerManager.StartTimer timerInfo, delayMillis
StartManagedTimer = timerInfo.ID
On Error GoTo scheduleProcFail
If runImmediately Then
If Not this.timerManager.tryTriggerTimer(timerInfo) Then
'queue is too full right now, no point scheduling as it wouldn't be evaluated in time anyway
'could try flushing the queue instead
log WarnLevel, loggerSourceName, "Message queue is too full to post to, so cannot runImmediately"
End If
End If
log InfoLevel, loggerSourceName, printf("ManagedTimer with id {0} created", timerInfo.ID)
Exit Function
generateTimerDataFail:
logError "timerSet.Add", Err.Number, Err.Description
raisePublicError GenerateTimerDataError, loggerSourceName
Resume 'for debugging - break above and jump to the error-raising statement
createTimerFail:
logError "createTimer", Err.Number, Err.Description
this.timerDataRepo.Remove timerInfo
raisePublicError CreateTimerError, loggerSourceName
Resume
scheduleProcFail:
logError "scheduleProc", Err.Number, Err.Description
KillTimerByID timerInfo.ID 'NOTE may raise an error
raisePublicError SynchronousCallError, loggerSourceName
Resume
End Function
'@Description("API kills windows timer on this handle by ID. Unregistered ID raises TimerNotFoundError, failure to destroy a registered ID raises DestroyTimerError")
Public Sub KillTimerByID(ByVal timerID As LongPtr)
Const loggerSourceName As String = "KillTimerByID"
If this.timerDataRepo.Exists(timerID) Then
On Error GoTo killTimerFail
Dim timerInfo As TimerData
Set timerInfo = this.timerDataRepo.Item(timerID)
this.timerDataRepo.Remove timerInfo
this.timerManager.KillTimer timerInfo
log InfoLevel, loggerSourceName, printf("Timer with id {0} destroyed", timerInfo.ID)
Else
raisePublicError TimerNotFoundError, loggerSourceName
End If
Exit Sub
killTimerFail:
logError "killTimer", Err.Number, Err.Description
raisePublicError DestroyTimerError, loggerSourceName
Resume 'for debugging - break above and jump to the error-raising statement
End Sub
'@Description("Loops through all timers and kills those matching timerFunction - this can be a functionID, a functionObject(ITimerProc) or a functionName")
Public Sub KillTimersByFunction(ByVal timerFunction As Variant)
Const errorSourceName As String = "KillTimersByFunction"
'REVIEW slightly nasty how this method catches and rethrows PUBLIC errors which doubles the cleanup unnecessarily
'Could just remove error guard and raise them itself, but that's risky as there might be unhandled internal errors
On Error GoTo safeThrow
If IsNumeric(timerFunction) Then
If Int(timerFunction) = timerFunction Then 'not a decimal
Me.KillTimersByFunctionID timerFunction
Else
raisePublicError InvalidTimerFunctionError, errorSourceName
End If
ElseIf IsObject(timerFunction) Then
If TypeOf timerFunction Is ITimerProc Then
Me.KillTimersByFunctionID ObjPtr(timerFunction)
Else
raisePublicError InvalidTimerFunctionError, errorSourceName
End If
ElseIf TypeName(timerFunction) = "String" Then
Me.KillTimersByFunctionName timerFunction
Else
raisePublicError InvalidTimerFunctionError, errorSourceName
End If
Exit Sub
safeThrow:
'check if within custom error range; if so then don't rethrow as that would re-terminate and double log the error
If Err.Number > TimerError.[_End] Or Err.Number < TimerError.[_Start] Then
'Unexpected Errors: must throw them to public; no sense condensing as these are all unexpected
raisePublicError Err.Number, "KillTimersByFunction"
Else
'Public Errors: all the cleanup is done, safe to just re-throw
Err.Raise Err.Number
End If
Resume
End Sub
Public Sub KillTimersByFunctionID(ByVal timerFunctionID As LongPtr)
On Error GoTo safeThrow
Dim timer As TimerData
For Each timer In this.timerDataRepo.FilterByFunctionID(timerFunctionID)
KillTimerByID timer.ID
Next timer
Exit Sub
safeThrow:
raisePublicError Err.Number, "KillTimersByFunctionID"
Resume 'for debugging
End Sub
Public Sub KillTimersByFunctionName(ByVal timerFunctionName As String)
On Error GoTo safeThrow
Dim timer As TimerData
For Each timer In this.timerDataRepo.FilterByFunctionName(timerFunctionName)
KillTimerByID timer.ID
Next timer
Exit Sub
safeThrow:
raisePublicError Err.Number, "KillTimersByFunctionName"
Resume 'for debugging
End Sub
Public Sub KillAll()
'NOTE this is called when raising errors so must not generate any itself
On Error Resume Next
this.timerManager.KillAllTimers this.timerDataRepo.ToArray
this.timerDataRepo.Clear
If Err.Number <> 0 Then logError "KillAll", Err.Number, Err.Description
On Error GoTo 0
End Sub
Private Sub raisePublicError(ByVal errorCode As TimerError, Optional ByVal Source As String = "raiseError")
log TraceLevel, "raiseError", "Destroying timers so error can be raised"
Me.KillAll
Select Case errorCode
Case TimerError.CreateTimerError
Err.Description = "Couldn't create Timer"
Case TimerError.DestroyTimerError
Err.Description = "Uh Oh, can't kill the timer :("
Case TimerError.GenerateTimerDataError
Err.Description = "Unable to add/retrieve timer data from the repository"
Case TimerError.InvalidTimerFunctionError
Err.Description = "Invalid timer function supplied; timer functions must be one of:" & vbNewLine _
& " - a TIMERPROC or ITimerProc pointer" & vbNewLine _
& " - an ITimerProc instance" & vbNewLine _
& " - a class name String"
Case TimerError.SynchronousCallError
Err.Description = "Error when running synchronously"
Case TimerError.TimerNotFoundError
Err.Description = "Timer not found"
Case Else
'rethrow error
On Error Resume Next
Err.Raise errorCode 'fake raise to grab text for logging
Dim errDescription As String
errDescription = Err.Description
On Error GoTo 0
Err.Description = errDescription
End Select
logError Source, errorCode, Err.Description 'possibly overkill
Err.Raise errorCode
End Sub
'For testing
Friend Property Get messageWindowHandle()
'only on windows
Dim timerManager As WindowsTimerManager
Set timerManager = this.timerManager
messageWindowHandle = timerManager.messageWindowHandle
End Property
</code></pre>
<p>The <code>TickerAPI</code> class holds references to all running timers. It does this by creating an <code>ICallbackWrapper</code> object which holds a reference to the callback function and data passed to the timer. Depending on the kind of callback function (<code>ITimerProc</code> or raw <code>AddressOf TIMERPROC</code>), a Managed/Unmanaged wrapper is created respectively.</p>
<h3>Interface Class: <code>ICallbackWrapper</code></h3>
<pre><code>'@Folder("FirstLevelAPI.Utils.Wrappers")
'@Exposed
Option Explicit
Public Property Get FunctionID() As LongPtr
End Property
Public Property Get FunctionName() As String
End Property
</code></pre>
<h3>Constructor Class: <code>UnmanagedCallbackWrapper</code></h3>
<pre><code>'@Folder("FirstLevelAPI.Utils.Wrappers")
'@PredeclaredID
'@Exposed
Option Explicit
Implements ICallbackWrapper
Private Type tUnmanagedWrapper
callbackFunction As LongPtr
data As Variant
Name As String
End Type
Private this As tUnmanagedWrapper
Private Sub Class_Initialize()
Set this.data = Nothing
this.callbackFunction = 0
'TODO allow custom name
this.Name = WinAPI.GetGUID 'something unique to the function; could be the ptr but that might be reallocated
End Sub
Friend Function Create(ByVal callbackFunction As LongPtr, Optional ByVal data As Variant) As UnmanagedCallbackWrapper
'NOTE only API needs to be able to create these so don't expose
With New UnmanagedCallbackWrapper
.storeData IIf(IsMissing(data), Nothing, data)
.callBack = callbackFunction
Set Create = .Self
End With
End Function
Friend Property Get Self() As UnmanagedCallbackWrapper
Set Self = Me
End Function
Friend Property Let callBack(ByVal value As LongPtr)
this.callbackFunction = value
End Property
Public Sub storeData(ByVal data As Variant)
LetSet this.data, data
End Sub
Public Property Get userData() As Variant
LetSet userData, this.data
End Property
Public Property Get timerID() As LongPtr
timerID = ObjPtr(Me)
End Property
Private Property Get ICallbackWrapper_FunctionID() As LongPtr
ICallbackWrapper_FunctionID = this.callbackFunction
End Property
Private Property Get ICallbackWrapper_FunctionName() As String
ICallbackWrapper_FunctionName = this.Name
End Property
'for testing
Friend Property Get debugName() As String
debugName = this.Name
End Property
</code></pre>
<h3>Constructor Class: <code>ManagedCallbackWrapper</code></h3>
<pre><code>'@Folder("FirstLevelAPI.Utils.Wrappers")
'@PredeclaredID
Option Explicit
Implements ICallbackWrapper
Private Type tManagedWrapper
callbackFunction As ITimerProc
data As Variant
End Type
Private this As tManagedWrapper
Private Sub Class_Initialize()
Set this.data = Nothing
Set this.callbackFunction = New ITimerProc
End Sub
Public Function Create(ByVal callbackFunction As ITimerProc, Optional ByVal data As Variant) As ManagedCallbackWrapper
'NOTE only API needs to be able to create these so don't expose
With New ManagedCallbackWrapper
.storeData data
Set .callBack = callbackFunction
Set Create = .Self
End With
End Function
Public Property Get Self() As ManagedCallbackWrapper
Set Self = Me
End Function
Public Property Set callBack(ByVal obj As ITimerProc)
Set this.callbackFunction = obj
End Property
Public Property Get callBack() As ITimerProc
Set callBack = this.callbackFunction
End Property
Public Sub storeData(ByVal data As Variant)
LetSet this.data, data
End Sub
Public Property Get userData() As Variant
LetSet userData, this.data
End Property
Public Property Get timerID() As LongPtr
timerID = ObjPtr(Me)
End Property
Private Property Get ICallbackWrapper_FunctionID() As LongPtr
ICallbackWrapper_FunctionID = ObjPtr(this.callbackFunction)
End Property
Private Property Get ICallbackWrapper_FunctionName() As String
ICallbackWrapper_FunctionName = TypeName(this.callbackFunction)
End Property
Public Property Get callbackWrapper() As ICallbackWrapper 'just return the interface; makes it easier to work with
Set callbackWrapper = Me
End Property
</code></pre>
<p>These wrapper objects are stored in a <code>TimerRepository</code>, and their <code>ObjPtr()</code>s are used as the unique id for the <code>SetTimer</code> API. This has the side effect of meaning that the <code>TIMERPROC</code> can dereference the pointer back into a <code>(Un)ManagedCallbackWrapper</code> and so the <code>TickerAPI</code> doesn't have to expose them manually. The pointer is to the wrapper's <em>default interface</em> rather than its <code>ICallbackWrapper</code> interface, so the signatures of managed and unmanaged timerProcs are slightly different.</p>
<h3>Class: <code>TimerRepository</code></h3>
<pre><code>'@Folder("FirstLevelAPI")
Option Explicit
Private Type repositoryData
TimerData As New Scripting.Dictionary '{id:TimerData}
End Type
Private this As repositoryData
'@DefaultMember
Public Function Item(ByVal timerID As LongPtr) As TimerData
Set Item = this.TimerData.Item(timerID)
End Function
Public Function Add(ByVal callbackWrapper As Object) As TimerData
Dim newData As TimerData
Set newData = TimerData.Create(callbackWrapper)
this.TimerData.Add newData.ID, newData
Set Add = newData
End Function
Public Sub Remove(ByVal timerInfo As TimerData)
this.TimerData.Remove timerInfo.ID
End Sub
Public Sub Clear()
this.TimerData.RemoveAll
End Sub
Public Function ToArray() As Variant
ToArray = this.TimerData.Items
End Function
Public Property Get Exists(ByVal timerID As LongPtr) As Boolean
On Error Resume Next 'if there's a problem then the timerID is as good as unregistered anyway
Exists = this.TimerData.Exists(timerID)
On Error GoTo 0
End Property
Public Function FilterByFunctionID(ByVal funcID As LongPtr) As Collection
Dim matches As New Collection
Dim data As TimerData
For Each data In this.TimerData
If data.callbackWrapperInterface.FunctionID = funcID Then
matches.Add data
End If
Next data
Set FilterByFunctionID = matches
End Function
Public Function FilterByFunctionName(ByVal funcName As String) As Collection
Dim matches As New Collection
Dim data As TimerData
For Each data In this.TimerData
If data.callbackWrapperInterface.FunctionName = funcName Then
matches.Add data
End If
Next data
Set FilterByFunctionName = matches
End Function
</code></pre>
<p>The callback wrapper is itself stored within a <code>TimerData</code> object, which provides quick access to the properties required by the <code>ITimerManager</code>; an <code>ITimerManager</code> is responsible for taking the <code>TimerData</code> (which is essentially a generic definition of a timer) and using that info to call WinAPI functions and make a timer with those parameters.</p>
<h3>Constructor Class: <code>TimerData</code></h3>
<pre><code>'@Folder("FirstLevelAPI")
'@PredeclaredId: For constructor method
Option Explicit
Private Type tTimerData
callbackWrapper As Object
timerProc As LongPtr
End Type
Private this As tTimerData
Public Function Create(ByVal timerCallbackWrapper As Object) As TimerData
With New TimerData
Set .callbackWrapper = timerCallbackWrapper
If TypeOf timerCallbackWrapper Is ManagedCallbackWrapper Then
.timerProc = VBA.CLngPtr(AddressOf InternalTimerProcs.ManagedTimerCallbackInvoker)
Else
.timerProc = .callbackWrapperInterface.FunctionID
End If
Set Create = .Self
End With
End Function
Friend Property Get Self() As TimerData
Set Self = Me
End Function
Public Property Get callbackWrapperPointer() As LongPtr
callbackWrapperPointer = ObjPtr(this.callbackWrapper)
End Property
Friend Property Get callbackWrapperInterface() As ICallbackWrapper
Set callbackWrapperInterface = this.callbackWrapper
End Property
Public Property Set callbackWrapper(ByVal value As Object)
Set this.callbackWrapper = value
End Property
Public Property Get ID() As LongPtr 'alias
ID = Me.callbackWrapperPointer
End Property
Public Property Get timerProc() As LongPtr
timerProc = this.timerProc
End Property
Friend Property Let timerProc(ByVal value As LongPtr)
this.timerProc = value
End Property
</code></pre>
<p>The callback function that is eventually passed to the WinAPI methods is given by the ObjPtr of the <code>ITimerProc</code> associated with a <code>ManagedCallbackWrapper</code>, or it is the default <code>TIMERPROC</code> used by <code>UnManagedCallbackWrappers</code>:</p>
<h3>Module: <code>Internal Timer Procs</code></h3>
<pre><code>'@Folder("FirstLevelAPI.Utils")
Option Explicit
Option Private Module
Private Const killTimerOnExecError As Boolean = False 'TODO make these configurable
Private Const terminateOnUnhandledError As Boolean = True
'@Description("TIMERPROC callback for ManagedCallbacks which executes the callback function within error guards")
'@Ignore ParameterNotUsed: callbacks need to have this signature regardless
Public Sub ManagedTimerCallbackInvoker(ByVal windowHandle As LongPtr, ByVal message As WindowsMessage, ByVal timerParams As ManagedCallbackWrapper, ByVal tickCount As Long)
Const loggerSourceName As String = "ManagedTimerCallbackInvoker"
'NOTE could check message and ObjPtr(timerparams) to ensure this is a valid managedTimer caller
On Error Resume Next
timerParams.callBack.Exec timerParams.timerID, timerParams.userData, tickCount
Dim errNum As Long
Dim errDescription As String
errNum = Err.Number 'changing the error policy will wipe these, so cache them
errDescription = Err.Description
'Log any error the callback may have raised, kill it if necessary
On Error GoTo cleanFail 'this procedure cannot raise errors or we'll crash
If errNum <> 0 Then
logError timerParams.callbackWrapper.FunctionName & ".Exec", errNum, errDescription
If killTimerOnExecError Then
On Error GoTo cleanFail
TickerAPI.KillTimerByID timerParams.timerID
End If
End If
cleanExit:
Exit Sub
cleanFail:
logError loggerSourceName, Err.Number, Err.Description
If terminateOnUnhandledError Then Set TickerAPI = Nothing 'kill all timers
Resume cleanExit
End Sub
</code></pre>
<h3>Interface Class: <code>ITimerManager</code></h3>
<pre><code>'@Folder("FirstLevelAPI")
'@Interface
Option Explicit
Public Enum InternalTimerError
[_ErrBase] = 6 'just in case of clashes, let's offset the errors
[_Start] = vbObjectError + [_ErrBase] 'TimerError.[_End] - 1
CreateMessageWindowError
APIKillTimerError
CastKeyToWrapperError
APIStartTimerError
APIPostMessageError
End Enum
Public Sub KillTimer(ByVal data As TimerData)
End Sub
Public Sub StartTimer(ByVal data As TimerData, ByVal delayMillis As Long)
End Sub
Public Sub UpdateTimer(ByVal data As TimerData, ByVal delayMillis As Long)
End Sub
Public Function tryTriggerTimer(ByVal data As TimerData) As Boolean
End Function
Public Sub KillAllTimers(ByVal dataArray As Variant)
End Sub
</code></pre>
<p>The default (and currently only) <code>ITimerManager</code> is the <code>WindowsTimerManager</code>. This is the only class which actually sees WinAPI, and so it handles implementation details. One such implementation detail is creating a <code>ModelessMessageWindow</code>; this provides an <code>hwnd</code> to pass to the <code>SetTimer</code> API (the reason it's done this way is explained in the Github README, essentially a <code>UserForm</code> is easy to destroy and takes down all the timers with it)</p>
<h3>Class: <code>WindowsTimerManager</code></h3>
<pre><code>'@Folder("FirstLevelAPI")
Option Explicit
Implements ITimerManager
Private Type windowsTimerManagerData
messageWindow As New ModelessMessageWindow
End Type
Private this As windowsTimerManagerData
Private Sub ITimerManager_KillTimer(ByVal data As TimerData)
'NOTE no need to clear messages as killing the timer invalidates any which have a TIMERPROC argument (which they all do)
On Error GoTo cleanFail
'0 indicates some failure
If WinAPI.KillTimer(this.messageWindow.handle, data.ID) = 0 Then
throwDllError Err.LastDllError, "Call returned zero, probably tried to kill non-existent timer"
End If
cleanExit:
Exit Sub
cleanFail:
logError "WinAPI.KillTimer", Err.Number, Err.Description
raiseInternalError APIKillTimerError, "KillTimer"
Resume cleanExit
End Sub
Private Sub ITimerManager_StartTimer(ByVal data As TimerData, ByVal delayMillis As Long)
Const loggerSourceName As String = "StartTimer"
'Custom handler so we can log precise dll errors and condense error messages + clear up any timer which may have been made
On Error GoTo setTimerFail
Dim newTimerID As LongPtr
newTimerID = WinAPI.SetTimer(this.messageWindow.handle, data.callbackWrapperPointer, delayMillis, data.timerProc)
If newTimerID = 0 Then
throwDllError Err.LastDllError
ElseIf newTimerID <> data.ID Then
Err.Raise 5, Description:="timerID does not have expected value" 'REVIEW is there a better assertion error to raise?
End If
Exit Sub
setTimerFail:
logError "WinAPI.SetTimer", Err.Number, Err.Description
ITimerManager_KillTimer data
raiseInternalError APIStartTimerError, loggerSourceName
Resume 'for debugging - break above and jump to the error-raising statement
End Sub
'TODO never used
Private Sub ITimerManager_UpdateTimer(ByVal data As TimerData, ByVal delayMillis As Long)
'NOTE just an alias for windows timers, maybe not for others
ITimerManager_StartTimer data, delayMillis
End Sub
Private Function ITimerManager_tryTriggerTimer(ByVal data As TimerData) As Boolean
Const loggerSourceName As String = "tryTriggerTimer"
On Error GoTo catchError
'Post fake message to queue to act as an already elapsed timer
If WinAPI.PostMessage(this.messageWindow.handle, WM_TIMER, data.ID, data.timerProc) = 0 Then
throwDllError Err.LastDllError
Else
ITimerManager_tryTriggerTimer = True
End If
cleanExit:
Exit Function
catchError:
If Err.Number = systemErrorCodes.ERROR_NOT_ENOUGH_QUOTA Then
ITimerManager_tryTriggerTimer = False
Resume cleanExit
Else
logError "WinAPI.PostMessage", Err.Number, Err.Description
raiseInternalError APIPostMessageError, loggerSourceName
Resume 'for debugging - break above and jump to the error-raising statement
End If
End Function
Private Sub ITimerManager_KillAllTimers(ByVal dataArray As Variant)
Const loggerSourceName As String = "KillAllTimers"
'NOTE this procedure is called when raising errors so must not raise any itself
On Error Resume Next
log InfoLevel, loggerSourceName, printf("{0} registered timer(s)", UBound(dataArray) - LBound(dataArray)) 'TODO move this elswhere
Set this.messageWindow = Nothing 'terminateMessageWindow - it's autoinstantiated so no tests
If Err.Number <> 0 Then logError loggerSourceName, Err.Number, Err.Description
On Error GoTo 0
End Sub
Private Sub raiseInternalError(ByVal errorCode As InternalTimerError, Optional ByVal Source As String = "raiseInternalError")
Select Case errorCode
Case InternalTimerError.CreateMessageWindowError
Err.Description = "Unable to obtain message window"
Case InternalTimerError.APIKillTimerError
Err.Description = "Error when calling API to destroy timer"
Case InternalTimerError.APIStartTimerError
Err.Description = "Error when calling API to create timer"
Case InternalTimerError.CastKeyToWrapperError
Err.Description = "Failed to cast key object to expected interface"
Case InternalTimerError.APIPostMessageError
Err.Description = "Failed to manually post a message to the queue"
Case Else
'Rethrow error
On Error Resume Next
Err.Raise errorCode 'fake raise to grab text for logging
Dim errDescription As String
errDescription = Err.Description
On Error GoTo 0
Err.Description = errDescription
End Select
'NOTE only log external errors as you can't rely on external loggers
Err.Raise errorCode, Source
End Sub
'For testing
Friend Property Get messageWindowHandle() As LongPtr
messageWindowHandle = this.messageWindow.handle
End Property
</code></pre>
<h3>UserForm: <code>ModelessMessageWindow</code> (<code>showModal = False</code>)</h3>
<pre><code>'@Folder("FirstLevelAPI")
'@ModuleDescription("Lightweight window to provide an hWnd that will be destroyed after a state loss - disconnecting any timers and subclasses which may be attached to it")
'@NoIndent: Conditional compilation doesn't seem to work nicely
Option Explicit
'See https://www.mrexcel.com/forum/excel-questions/967334-much-simpler-alternative-findwindow-api-retrieving-hwnd-userforms.html
#If VBA7 Then
Private Declare PtrSafe Function IUnknown_GetWindow Lib "shlwapi" Alias "#172" (ByVal pIUnk As IUnknown, ByRef outHwnd As LongPtr) As Long
#Else
Private Declare PtrSafe Function IUnknown_GetWindow Lib "shlwapi" Alias "#172" (ByVal pIUnk As IUnknown, ByRef outHwnd As Long) As Long
#End If
#If VBA7 Then
Public Property Get handle() As LongPtr
IUnknown_GetWindow Me, handle
End Property
#Else
Public Property Get handle() As Long
IUnknown_GetWindow Me, handle
End Property
#End If
</code></pre>
<p>And of course the WinAPI functions</p>
<h3>Module: <code>WinAPI</code></h3>
<p>This has a bit of excess (unused) code because I went through many iterations. However it might be helpful to keep for debugging.</p>
<pre><code>'@Folder("WinAPI")
'@IgnoreModule HungarianNotation: For consistency with the docs
'@NoIndent: Indenter doesn't handle PtrSafe very well
Option Explicit
Option Private Module
Public Type tagPOINT
X As Long
Y As Long
End Type
Public Type DWORD 'same size as Long, but intellisense on members is nice
'@Ignore IntegerDataType: https://stackoverflow.com/q/57891281/6609896
LoWord As Integer
'@Ignore IntegerDataType
HiWord As Integer
End Type
Public Type tagMSG
hWnd As LongPtr
message As WindowsMessage
wParam As LongPtr
lParam As LongPtr
time As Long
cursor As tagPOINT
#If Mac Then
lPrivate As Long
#End If
End Type
Public Type timerMessage
windowHandle As LongPtr
messageEnum As WindowsMessage
timerID As LongPtr
timerProc As LongPtr
tickCountTime As Long
cursor As tagPOINT
#If Mac Then
lPrivate As Long
#End If
End Type
Public Type WNDCLASSEX
cbSize As Long
style As Long ' See CS_* constants
lpfnwndproc As LongPtr
' lpfnwndproc As Long
cbClsextra As Long
cbWndExtra As Long
hInstance As LongPtr
hIcon As LongPtr
hCursor As LongPtr
hbrBackground As LongPtr
' hInstance as long
' hIcon as long
' hCursor as long
' hbrBackground as long
lpszMenuName As String
lpszClassName As String
hIconSm As LongPtr
' hIconSm as long
End Type
Public Enum TimerDelay
USER_TIMER_MINIMUM = &HA
USER_TIMER_MAXIMUM = &H7FFFFFFF
End Enum
Public Enum WindowStyle
HWND_MESSAGE = (-3&)
End Enum
Public Enum QueueStatusFlag
QS_TIMER = &H10
QS_ALLINPUT = &H4FF
End Enum
Public Enum PeekMessageFlag
PM_REMOVE = &H1
PM_NOREMOVE = &H0
End Enum
''@Description("Windows Timer Message https://docs.microsoft.com/windows/desktop/winmsg/wm-timer")
Public Enum WindowsMessage
WM_TIMER = &H113
WM_NOTIFY = &H4E 'arbitrary, sounds nice though
End Enum
Public Enum systemErrorCodes
ERROR_NOT_ENOUGH_QUOTA = 1816
End Enum
'Messages
Public Declare Function GetQueueStatus Lib "user32" ( _
ByVal flags As QueueStatusFlag) As DWORD
Public Declare Function PeekMessage Lib "user32" Alias "PeekMessageA" ( _
ByRef lpMsg As tagMSG, _
ByVal hWnd As LongPtr, _
ByVal wMsgFilterMin As WindowsMessage, _
ByVal wMsgFilterMax As WindowsMessage, _
ByVal wRemoveMsg As PeekMessageFlag) As Long
Public Declare Function PeekTimerMessage Lib "user32" Alias "PeekMessageA" ( _
ByRef outMessage As timerMessage, _
ByVal hWnd As LongPtr, _
Optional ByVal wMsgFilterMin As WindowsMessage = WM_TIMER, _
Optional ByVal wMsgFilterMax As WindowsMessage = WM_TIMER, _
Optional ByVal wRemoveMsg As PeekMessageFlag = PM_REMOVE) As Long
Public Declare Function PostMessage Lib "user32" Alias "PostMessageA" ( _
ByVal hWnd As LongPtr, _
ByVal msg As WindowsMessage, _
ByVal wParam As LongPtr, _
ByVal lParam As LongPtr) As Long
Public Declare Function DispatchMessage Lib "user32" Alias "DispatchMessageA" ( _
ByVal lpMsg As LongPtr) As LongPtr
Public Declare Function DispatchTimerMessage Lib "user32" Alias "DispatchMessageA" ( _
ByRef message As timerMessage) As LongPtr
'Windows
Public Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" ( _
ByVal dwExStyle As Long, ByVal className As String, ByVal windowName As String, _
ByVal dwStyle As Long, ByVal X As Long, ByVal Y As Long, _
ByVal nWidth As Long, ByVal nHeight As Long, _
ByVal hWndParent As LongPtr, ByVal hMenu As LongPtr, _
ByVal hInstance As LongPtr, ByVal lpParam As LongPtr) As LongPtr
Public Declare Function DestroyWindow Lib "user32" ( _
ByVal hWnd As LongPtr) As Long
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As LongPtr
'Registering
Public Declare Function RegisterClassEx Lib "user32" Alias "RegisterClassExA" ( _
ByRef pcWndClassEx As WNDCLASSEX) As Long
Public Declare Function UnregisterClass Lib "user32" Alias "UnregisterClassA" ( _
ByVal lpClassName As String, ByVal hInstance As LongPtr) As Long
Public Declare Function DefWindowProc Lib "user32" Alias "DefWindowProcA" ( _
ByVal lhwnd As LongPtr, _
ByVal wMsg As Long, _
ByVal wParam As LongPtr, _
ByVal lParam As LongPtr) As Long
Public Declare Function DefSubclassProc Lib "comctl32.dll" Alias "#413" ( _
ByVal hWnd As LongPtr, _
ByVal uMsg As WindowsMessage, _
ByVal wParam As LongPtr, _
ByVal lParam As LongPtr) As LongPtr
Public Declare Function SetWindowSubclass Lib "comctl32.dll" Alias "#410" ( _
ByVal hWnd As LongPtr, _
ByVal pfnSubclass As LongPtr, _
ByVal uIdSubclass As LongPtr, _
Optional ByVal dwRefData As LongPtr) As Long
Public Declare Function RemoveWindowSubclass Lib "comctl32.dll" Alias "#412" ( _
ByVal hWnd As LongPtr, _
ByVal pfnSubclass As LongPtr, _
ByVal uIdSubclass As LongPtr) As Long
'Timers
Public Declare Function SetTimer Lib "user32" ( _
ByVal hWnd As LongPtr, _
ByVal nIDEvent As LongPtr, _
ByVal uElapse As TimerDelay, _
ByVal lpTimerFunc As LongPtr) As LongPtr
Public Declare Function KillTimer Lib "user32" ( _
ByVal hWnd As LongPtr, ByVal nIDEvent As LongPtr) As Long
Public Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" ( _
ByVal lpPrevWndFunc As LongPtr, _
ByRef params As UnmanagedCallbackWrapper, _
Optional ByVal message As WindowsMessage = WM_NOTIFY, _
Optional ByVal timerID As Long = 0, _
Optional ByVal unused3 As Long) As LongPtr
Private Type GUID
Data1 As Long
'@Ignore IntegerDataType
Data2 As Integer
'@Ignore IntegerDataType
Data3 As Integer
Data4(7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "OLE32.DLL" (ByRef pGuid As GUID) As Long
'@IgnoreModule EmptyStringLiteral
Public Function GetGUID() As String
'(c) 2000 Gus Molina
Dim udtGUID As GUID
If (CoCreateGuid(udtGUID) = 0) Then
GetGUID = _
String(8 - Len(Hex$(udtGUID.Data1)), "0") & Hex$(udtGUID.Data1) _
& String(4 - Len(Hex$(udtGUID.Data2)), "0") & Hex$(udtGUID.Data2) _
& String(4 - Len(Hex$(udtGUID.Data3)), "0") & Hex$(udtGUID.Data3) _
& IIf((udtGUID.Data4(0) < &H10), "0", "") & Hex$(udtGUID.Data4(0)) _
& IIf((udtGUID.Data4(1) < &H10), "0", "") & Hex$(udtGUID.Data4(1)) _
& IIf((udtGUID.Data4(2) < &H10), "0", "") & Hex$(udtGUID.Data4(2)) _
& IIf((udtGUID.Data4(3) < &H10), "0", "") & Hex$(udtGUID.Data4(3)) _
& IIf((udtGUID.Data4(4) < &H10), "0", "") & Hex$(udtGUID.Data4(4)) _
& IIf((udtGUID.Data4(5) < &H10), "0", "") & Hex$(udtGUID.Data4(5)) _
& IIf((udtGUID.Data4(6) < &H10), "0", "") & Hex$(udtGUID.Data4(6)) _
& IIf((udtGUID.Data4(7) < &H10), "0", "") & Hex$(udtGUID.Data4(7))
End If
End Function
Public Sub PrintMessageQueue(ByVal windowHandle As LongPtr, Optional ByVal filterLow As WindowsMessage = 0, Optional ByVal filterHigh As WindowsMessage = 0)
Dim msg As tagMSG
Dim results As New Dictionary
Do While PeekMessage(msg, windowHandle, filterLow, filterHigh, PM_REMOVE) <> 0
If results.Exists(msg.message) Then
results(msg.message) = results(msg.message) + 1
Else
results(msg.message) = 1
End If
Loop
'put them back?
If results.Count = 0 Then
Debug.Print "No Messages"
Else
Dim key As Variant
For Each key In results.Keys
Debug.Print "#"; key; ":", results(key)
Next key
End If
End Sub
</code></pre>
<hr>
<p>This diagram illustrates how everything fits together (click to enlarge)
<a href="https://i.stack.imgur.com/jMLJB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jMLJB.png" alt="Project layout diagram"></a></p>
<hr>
<h1>Usage</h1>
<p>Users don't have to care about any of that though, they just need to decide whether they want to use an Unmanaged or Managed timer:</p>
<ul>
<li>Unmanaged timers call TIMERPROCs directly; there is no error guard, so Unmanaged TimerProcs must not raise errors to the caller (the caller is the OS itself so they really musn't, or Excel will crash)</li>
<li>Managed timers call a default <code>ManagedTimerCallbackInvoker</code> TimerProc, passing in an <code>ITimerProc</code> function object. The <code>.Exec</code> method of the <code>ITimerProc</code> is called within VBA OERN guards so Managed timers don't need to worry about raising errors.</li>
</ul>
<p>Unmanaged timers therefore require a pointer to a function whose signature is a variant on the <a href="https://msdn.microsoft.com/en-us/windows/desktop/ms644907" rel="nofollow noreferrer"><code>TIMERPROC</code> signature</a>. Remember the <code>UINT_PTR idEvent</code> is set to the <code>ObjPtr()</code> of the Callback wrapper, meaning it can be dereferenced in place:</p>
<pre><code>Public Sub ExampleUnmanagedTimerProc(ByVal windowHandle As LongPtr, ByVal message As WindowsMessage, ByVal timerParams As UnmanagedCallbackWrapper, ByVal tickCount As Long)
'Do stuff but DON'T RAISE ERRORS!!
End Sub
</code></pre>
<p>Called with</p>
<pre><code>Dim timerID As LongPtr
timerID = TickerAPI.StartUnmanagedTimer(AddressOf ExampleUnmanagedTimerProc, delayMillis:=1000, data:="This gets passed to ExampleUnmanagedTimerProc via timerParams.userData")
</code></pre>
<p>Managed timers meanwhile require an <code>ITimerProc</code></p>
<h3>Interface Class: <code>ITimerProc</code></h3>
<pre><code>'@Folder("FirstLevelAPI.Utils.Wrappers")
'@Exposed
'@Interface
Option Explicit
Public Sub Exec(ByVal timerID As LongPtr, ByVal userData As Variant, ByVal tickCount As Long)
Err.Raise 5 'not implemented
End Sub
</code></pre>
<p>Called with</p>
<pre><code>Dim timerID As LongPtr
timerID = TickerAPI.StartManagedTimer(New HelloWorldProc, delayMillis:=1000, data:=New Collection)
</code></pre>
<hr>
<h2>Helpers</h2>
<p>A few helper functions are shared in the project:</p>
<h3>Module: <code>ProjectUtils</code></h3>
<pre><code>'@Folder("Common")
'@NoIndent: #If isn't handled well
Option Explicit
Option Private Module
Public Const INFINITE_DELAY As Long = &H7FFFFFFF
#If VBA7 Then
Private Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef Source As Any, ByVal length As Long)
Private Declare PtrSafe Sub ZeroMemory Lib "kernel32.dll" Alias "RtlZeroMemory" (ByRef destination As Any, ByVal length As Long)
#Else
Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef Source As Any, ByVal length As Long)
Private Declare Sub ZeroMemory Lib "kernel32.dll" Alias "RtlZeroMemory" (ByRef destination As Any, ByVal length As Long)
#End If
#If VBA7 Then
Public Function FromPtr(ByVal pData As LongPtr) As Object
#Else
Public Function FromPtr(ByVal pData As Long) As Object
#End If
Dim result As Object
CopyMemory result, pData, LenB(pData)
Set FromPtr = result 'don't copy directly as then reference count won't be managed (I think)
ZeroMemory result, LenB(pData) ' free up memory, equiv: CopyMemory result, 0&, LenB(pData)
End Function
'@Ignore ProcedureCanBeWrittenAsFunction: this should become redundant at some point once RD can understand byRef
Public Sub LetSet(ByRef variable As Variant, ByVal value As Variant)
If IsObject(value) Then
Set variable = value
Else
variable = value
End If
End Sub
Public Sub throwDllError(ByVal ErrorNumber As Long, Optional ByVal onZeroText As String = "DLL error = 0, i.e. no error")
If ErrorNumber = 0 Then
Err.Raise 5, Description:=onZeroText
Else
Err.Raise ErrorNumber, Description:=GetSystemErrorMessageText(ErrorNumber)
End If
End Sub
Public Sub logError(ByVal Source As String, ByVal errNum As Long, ByVal errDescription As String)
If Not LogManager.IsEnabled(ErrorLevel) Then 'check a logger is registered
LogManager.Register DebugLogger.Create("Timing-E", ErrorLevel)
End If
LogManager.log ErrorLevel, Toolbox.Strings.Format("{0} raised an error: #{1} - {2}", Source, errNum, errDescription)
End Sub
Public Sub log(ByVal loggerLevel As LogLevel, ByVal Source As String, ByVal message As String)
If Not LogManager.IsEnabled(TraceLevel) Then 'check a logger is registered
LogManager.Register DebugLogger.Create("Timing", TraceLevel)
End If
LogManager.log loggerLevel, Toolbox.Strings.Format("{0} - {1}", Source, message)
End Sub
</code></pre>
<p>And Chip Pearson's <a href="http://www.cpearson.com/Excel/FormatMessage.aspx" rel="nofollow noreferrer">error printing module</a> for dll errors</p>
<hr>
<h1>Example</h1>
<p><a href="https://github.com/Greedquest/VBA-Timing-Methods/blob/master/TimerAPI.xlam?raw=true" rel="nofollow noreferrer">The Timing addin</a> requires a reference to my <a href="https://github.com/Greedquest/VBA-Toolbox/blob/master/Toolbox.xlam?raw=true" rel="nofollow noreferrer">Toolbox addin</a> for:</p>
<ul>
<li>The logger</li>
<li>Printf / String formatting</li>
</ul>
<p>The addin code has a password which is <strong>1</strong> to hide it in RD's code explorer.</p>
<p>I've created <a href="https://github.com/Greedquest/VBA-Timing-Methods/blob/master/CodeReview%20Example.xlsm?raw=true" rel="nofollow noreferrer">an example project</a> which references the <code>Timing</code> addin. To use it (until I find a better way of sharing code), you must download the two addins and the example file, open the <code>Timing</code> addin and set a reference to the <code>Toolbox</code> addin, then open the example project and set a reference to the <code>Timing</code> addin.</p>
<p>Here's what's in the example project:</p>
<h3>Module: <code>Experiments</code></h3>
<pre><code>Option Explicit
Sub CreateNewTimer()
Dim outputRange As Range
Set outputRange = GUISheet.Range("OutputArea")
TickerAPI.StartManagedTimer New IncrementingTimerProc, delaymillis:=10 ^ (Rnd + 1), Data:=SelectRandomCellFromRange(outputRange)
End Sub
Private Function SelectRandomCellFromRange(ByVal cellRange As Range) As Range
Dim colOffset As Long
colOffset = Application.WorksheetFunction.RandBetween(1, cellRange.Columns.Count)
Dim rowOffset As Long
rowOffset = Application.WorksheetFunction.RandBetween(1, cellRange.Rows.Count)
Set SelectRandomCellFromRange = cellRange.Cells(rowOffset, colOffset)
End Function
</code></pre>
<h3>Class: <code>IncrementingTimerProc</code></h3>
<pre><code>Option Explicit
Implements Timing.ITimerProc
Private Sub ITimerProc_Exec(ByVal timerID As LongPtr, ByVal userData As Variant, ByVal tickCount As Long)
'Doesn't matter if we raise errors here as this is a managed timer proc, error details are logged
'Can even set breakpoints as long as we don't click `End` during a callback, that will crash Excel
With userData 'assume it's the range we're expecting
If .Value2 >= 10 Then
TickerAPI.KillTimerByID timerID
.Value2 = 0
Else
.Value2 = .Value2 + 1
End If
End With
End Sub
</code></pre>
<hr>
<h1>Review Notes:</h1>
<p>There are some areas where I'd particularly like feedback if you have any (or don't do any of these, review what you want!)</p>
<h2>Errors</h2>
<p>I've tried to stick to a pretty rigorous error raising and handling ethos, perhaps I've been a bit overzealous at times. The approach I've taken follows 2 main guidelines:</p>
<ol>
<li>Errors raised by a procedure should be of the same degree of abstraction as the procedure itself
<ul>
<li>As I understand it, a good procedure tends to do one well defined thing (single responsibility principle?), in a few abstract steps. The caller will know roughly what steps take place in a procedure, even if it doesn't know precisely how they are implemented. </li>
<li>Therefore I've tried to make procedures which raise a different, unique error <em>for each step</em>. Since each step may raise a number of different errors during its execution, I condense all these implementation level errors into a single step level error, if that makes sense. Some logging takes place with <a href="https://codereview.stackexchange.com/q/64109/146810">@Mathieu's extensible logging framework</a> to provide a traceback</li>
</ul></li>
<li>Errors can sometimes be interpreted as exceptions (i.e exceptional/special cases which need slightly altered execution pathways, as opposed to bugs/problems that the user needs to know about). However VBA doesn't really have any control structures for handling errors in this way (see trying to <a href="https://codereview.stackexchange.com/q/94415/146810">implement <code>try...catch</code> in VBA</a> - it's messy). So errors that I want to interpret as <a href="https://stackoverflow.com/a/5813695/6609896"><em>checked Exceptions</em></a> - expected problems that I know how to deal with - are caught within the procedure that raised them and then reported to the caller as a return value either as a <code>True</code>/<code>False</code>, or an error Enum
<ul>
<li>Encoding exceptions as the return value of functions enables use of control structures like <code>If...Else</code> or <code>Select Case</code>, and (hopefully) avoids GOTOs and spaghetti logic (see the <a href="https://rubberduckvba.wordpress.com/2019/05/09/pattern-tryparse" rel="nofollow noreferrer">TryParse pattern</a>).</li>
<li>As per the <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern" rel="nofollow noreferrer">msdn docs on try-parse</a>, unchecked exceptions should still be raised to the caller</li>
<li>Actual Errors meanwhile don't tend to exist in VBA, but where they do they are either untrappable (Out of stack space) or cause VBA to crash (MoveMemory with bad pointer), so no need to worry about re-raising those.</li>
</ul></li>
</ol>
<p>As I say, I may have been a bit heavy handed in my application of those principles, and maybe you disagree with the approach entirely, so some reviews on error raising in particular would be really helpful. It all forms part of the API and user experience. Also I've tried to be as succinct as I could in the description of error handling there, but if it's unclear then I can add more - I just thought that even though it's new to me, it's probably not new and pretty obvious to a lot of the people here!</p>
<h2>Add-ins</h2>
<p>As this is intended for use as an add-in, I've used the <code>Friend</code> modifier as well as <code>Option Private Module</code>. Am I using these appropriately? <code>Option Private Module</code> doesn't seem to stop Public Subs appearing in intellisense for projects which reference the addin.</p>
<h2>Unit-Tests</h2>
<p>I've written a small number of tests which can be found in the downloadable file - probably too much to review here. However I've been finding it tricky to test this code, partly because everything is asynchronous and that doesn't mesh well with synchronous unit tests. Also I feel like using <code>Friend</code> for exposing internals to unit testing is a bit hacky, so I'm wondering if there's a better way of organising my project to make it more readily test-able.</p>
<h2>API</h2>
<p>How can I make this more user-friendly? I want people to be able to use this code themselves - is Github + Addin a good way of sharing VBA? Are the TickerAPI public methods useful/ is there anything I should add?</p>
<h2>64-Bit & VBA6 compatibility</h2>
<p>Ultimately I want to make all the WinAPI declarations 64 bit compatible. Mostly that just means adding <code>PtrSafe</code>, as I always use <code>LongPtr</code> for pointer types. If I want to make this VBA6 safe, then you can see an example of the kind of thing I'd be doing in the <code>Helper</code> module (basically check if <code>LongPtr</code> exists - see <a href="https://stackoverflow.com/a/56940710/6609896">here</a>). Does this look correct? I'm not sure if that's the only change though; I don't think <code>.xlam</code> files are compatible with any VBA6 hosts, and maybe a few other issues exist - maybe I won't bother, do you think it's worth it?</p>
<h2>Part 2</h2>
<p>I'm going to make a second level API which uses events and <code>Metronome</code> objects to provide a source of ticks. That will probably be implemented as a managed timer whose <code>Exec</code> method raises events.</p>
<p><em>PS; Thanks Rubberduck team, the annotations and code explorer have been life savers!</em></p>
|
[] |
[
{
"body": "<p>First I'd like to say that this is impressive work, overall pretty squeaky clean... despite the adjustments needed to make it build on x64 :)</p>\n\n<p>One enhancement I can see in terms of readability, would be to use <code>PascalCase</code> rather than <code>camelCase</code> for member names: inconsistent casing is distracting, because parameters and locals are usually <code>camelCase</code>, so a camel-cased procedure name tends to register as such on first read.</p>\n\n<p><code>Start[Unm|M]anagedTimer</code> is doing too many things, as hinted by the 3 error-handling subroutines:</p>\n\n<pre><code>On Error GoTo generateTimerDataFail\n' do stuff...\n\nOn Error GoTo createTimerFail\n' do stuff...\n\nOn Error GoTo scheduleProcFail\n' do more stuff...\n</code></pre>\n\n<p>The first two really feel like they belong in their own private scope/function; this would help remove some of the duplication between the two functions.</p>\n\n<p>This is a bit dangerous:</p>\n\n<pre><code> Exit Function\n\ngenerateTimerDataFail:\n logError \"timerSet.Add\", Err.Number, Err.Description\n raisePublicError GenerateTimerDataError, loggerSourceName\n Resume 'for debugging - break above and jump to the error-raising statement\n</code></pre>\n\n<p>A <code>Resume</code> statement jumps right back to the statement that caused the problem in the first place: if that statement throws the same error again, we're very likely stuck in an infinite loop. Breakpoints aren't necessarily going to be there next time. An unreachable <code>Stop</code> statement that can only run if the \"prod path\" <code>Resume</code> statement is commented-out to make the debugger hit a programmatic breakpoint that effectively halts the \"debug path\" infinite loop:</p>\n\n<pre><code> log InfoLevel, loggerSourceName, printf(\"ManagedTimer with id {0} created\", timerInfo.ID)\nCleanExit:\n Exit Function\n\ngenerateTimerDataFail:\n logError \"timerSet.Add\", Err.Number, Err.Description\n raisePublicError GenerateTimerDataError, loggerSourceName\n Resume CleanExit ' DEBUG: comment-out this statement\n Stop\n Resume\n</code></pre>\n\n<p>Rubberduck will warn about the <code>Stop</code> statement, but only until (soon) it's able to determine that the execution path jumps out at <code>Resume</code> and the <code>Stop</code> statement is actually unreachable.</p>\n\n<hr>\n\n<p><code>TimerData.ID</code> aliasing <code>TimerData.CallbackWrapperPointer</code> makes the API needlessly confusing: in general the fewer different ways there are to do something or get a value, the better. The two members being on the same default interface (<code>TimerData</code>) feels like one of the two is redundant.</p>\n\n<hr>\n\n<p>Watch out for <code>As New</code> declarations; often, they aren't necessary and would be better off initialized in the <code>Class_Initialize</code> handler.</p>\n\n<p>Some enum members are hard to explain, too:</p>\n\n<blockquote>\n<pre><code>Public Enum TimerError\n [_Start]\n CreateTimerError = vbObjectError + 1\n '...\n [_End]\nEnd Enum\n</code></pre>\n</blockquote>\n\n<p><code>[_Start]</code> should really be <code>[_Undefined]</code> or <code>[_NoError]</code> with an explicit value of <code>0</code>, and then a hidden <code>[_BaseError]</code> set to <code>vbObjectError</code>, and then let the VBA compiler deal with the <code>+1</code> offsets for the visible members: that way none of the visible members have an explicit value, and you can freely reorder them on a whim.</p>\n\n<hr>\n\n<p>I'm not sure I like the coupling between the lower-level API classes - for example why does <code>TimerRepository.Add</code> take an <code>Object</code>, when it could take a <code>TimerData</code> reference and not need to <code>Set newData = TimerData.Create(callbackWrapper)</code>.</p>\n\n<p>That said, the <code>TickerAPI</code> default instance is stateful - while that makes a friendly-looking client code that doesn't need to worry about holding on to an instance of the class, it breaks the object-orientedness of the API... much like <code>UserForm1.Show</code>, you get client code working with objects without realizing - and global state resetting behind your back. I think the public API should just be a standard module, that way there's no implicit global <code>TickerAPI</code> object instance, and the calling code can remain identical:</p>\n\n<pre><code>TickerAPI.StartManagedTimer New SafeTerminatingTimerProc, True, data:=\"User data!!\"\n</code></pre>\n\n<hr>\n\n<p>So far so good, I've peeked at the <code>Metronome</code> API and can't wait to review it!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T01:32:13.473",
"Id": "235144",
"ParentId": "229656",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:21:47.407",
"Id": "229656",
"Score": "13",
"Tags": [
"vba",
"excel",
"api",
"timer",
"rubberduck"
],
"Title": "Tick. Tick. *breathe* BOOM! - Setting up real, stable asynchronous callbacks with WinAPI Timers in VBA"
}
|
229656
|
<p>The program is supposed to get one number <em>n</em> as input, and output the max value of gcd + lcm of two numbers that range from 1 to <em>n</em>.</p>
<p>For example, if n == 3, the answer is 7 because gcd(3,2) == 1 and lcm(3,2) == 6.</p>
<p>The issue is that the code works really slowly and the double loop makes it so numbers above basically 1000 take forever to run. How do I make it run faster?</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int highest_value = 0,equation;
int gcd,smaller;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i > j){smaller=j;}
else{smaller=i;}
for(int y = 1; y <= smaller; y++)
{
if(i%y==0 && j%y==0) gcd = y;
}
equation = gcd+((i*j)/gcd);
if(equation > highest_value) highest_value = equation;
}
}
cout << highest_value;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:12:13.457",
"Id": "446866",
"Score": "3",
"body": "Welcome to CR! This was migrated from SO, but please take the [tour] and see [ask]. It'd be helpful if you'd use the explanation you used on SO, namely, that the code isn't performant enough. Otherwise, this just feels like a code dump. Thanks for clarifying and explaining."
}
] |
[
{
"body": "<p>I decided to take a stab at this, and I ended up reducing your algorithm down to one line (tested for equality with the original algorithm from n = [0,500] :</p>\n\n<pre><code>highest_value = (n > 2) ? ( 1+n*(n-1) ) : ( 2*n );\n</code></pre>\n\n<p>If you would like to see the steps I took, then please see my steps below...</p>\n\n<p>Let's start by removing the comparison in the 2nd loop by splitting up the 2nd loop into 2 parts:</p>\n\n<pre><code>for(int i = 1; i <= n; i++) {\n // smaller = j\n for(int j = 1; j < i; j++) {\n for(int y = 1; y <= j/*smaller*/; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)\n if(equation > highest_value) highest_value = equation;\n }\n // smaller = i\n for(int j = i; j <= n; j++) {\n for(int y = 1; y <= i/*smaller*/; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)\n if(equation > highest_value) highest_value = equation;\n }\n}\n</code></pre>\n\n<p>Now let's extract the simple case where <code>i == j</code> by adding</p>\n\n<pre><code>// i == j\n// gcd = i;\n// equation = gcd+((i*j)/gcd);\n// equation = i + (i*i)/i\nequation = 2 * i;\nif(equation > highest_value) highest_value = equation;\n</code></pre>\n\n<p>and changing the limits of the second loop to exclude <code>i == j</code></p>\n\n<pre><code>for(int j = i+1; j <= n; j++) {\n</code></pre>\n\n<p>we now have</p>\n\n<pre><code>for(int i = 1; i <= n; i++) {\n // i == j\n equation = 2 * i;\n if(equation > highest_value) highest_value = equation;\n // smaller = j\n for(int j = 1; j < i; j++) {\n for(int y = 1; y <= j/*smaller*/; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)\n if(equation > highest_value) highest_value = equation;\n }\n // smaller = i\n for(int j = i+1; j <= n; j++) {\n for(int y = 1; y <= i/*smaller*/; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)\n if(equation > highest_value) highest_value = equation;\n }\n}\n</code></pre>\n\n<p>we can observe that the second loop checks the same values (just mirrored with i and j), so we can get rid of the second loop entirely giving us:</p>\n\n<pre><code>for(int i = 1; i <= n; i++) {\n // i == j\n equation = 2 * i;\n if(equation > highest_value) highest_value = equation;\n // smaller = j\n for(int j = 1; j < i; j++) {\n for(int y = 1; y <= j/*smaller*/; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)\n if(equation > highest_value) highest_value = equation;\n }\n}\n</code></pre>\n\n<p>we can also observe that the maximum value for the i == j case will be where <code>i == n</code>, so we can get rid of that section and start our highest_value at 2*n :</p>\n\n<pre><code>int highest_value = 2*n;\nint equation, gcd;\n\nfor(int i = 1; i <= n; i++) {\n // smaller = j\n for(int j = 1; j < i; j++) {\n for(int y = 1; y <= j; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)\n if(equation > highest_value) highest_value = equation;\n }\n}\n\nreturn highest_value;\n</code></pre>\n\n<p>Now let's look at the inner-most loop</p>\n\n<pre><code>for(int y = 1; y <= j; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n}\n</code></pre>\n\n<p>we know that y == 1 is a simple case where <code>gcd = 1</code> and <code>equation = 1 + i*j</code>, so we can extract that from the loop:</p>\n\n<pre><code>equation = 1 + i*j;\nif(equation > highest_value) highest_value = equation;\n\nfor(int y = 2; y <= j; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n}\n</code></pre>\n\n<p>let's also notice that the equation <code>1 + i*j</code> has a maximum consistent with the maximum values of i and j where <code>i = n</code> and <code>j = n-1</code> which gives us <code>1 + n*(n-1)</code> or <code>1 + n*n - n</code>. Now we can move this equation to the beginning of the function and check it against our initial highest_value of <code>2 * n</code>. Don't forget to exclude the case where <code>n == 0</code>, because it is impossible to achieve a value of <code>i</code> or <code>j == 0</code> inside the loop.</p>\n\n<pre><code>int highest_value = 2*n;\nint gcd, equation;\n\nif ( n > 0 ) {\n equation = 1 + n*(n-1);\n if(equation > highest_value) highest_value = equation;\n}\n</code></pre>\n\n<p>We can notice that our new equation exceed our initial equation at a value of <code>n >= 3</code></p>\n\n<pre><code>int highest_value, gcd, equation;\n\nif ( n > 2 ) {\n highest_value = 1 + n*(n-1);\n} else {\n highest_value = 2 * n;\n}\n</code></pre>\n\n<p>We can notice that <code>i == 1</code> and <code>j == 1</code> will never be divisible by the initial value of <code>y</code>, so we can start them at 2. Then notice that the j loop never happens if <code>i == 2</code>, so we can start i at 3.</p>\n\n<pre><code>int highest_value, gcd, equation;\n\nif ( n > 2 ) {\n highest_value = 1 + n*(n-1);\n} else {\n highest_value = 2 * n;\n}\n\nfor(int i = 3; i <= n; i++) {\n for(int j = 2; j < i; j++) {\n for(int y = 2; y <= j; y++) {\n if(i%y==0 && j%y==0) gcd = y;\n }\n equation = gcd+((i*j)/gcd);\n if(equation > highest_value) highest_value = equation;\n\n }\n}\n\nreturn highest_value;\n</code></pre>\n\n<p>Finally... We can notice a pattern where we can take this approach indefinitely where we can continue to factor our i and j, so I noticed a pattern where the initial highest_value is true for every i and j, so the final function is :</p>\n\n<pre><code>highest_value = (n > 2) ? ( 1+n*(n-1) ) : ( 2*n );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:51:20.033",
"Id": "229659",
"ParentId": "229657",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229659",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:09:44.530",
"Id": "229657",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"time-limit-exceeded"
],
"Title": "Find the largest sum of the GCD and LCM of two numbers in a range"
}
|
229657
|
<p>In my code I need a function to traverse an arbitrary JSON-like data structure with a path definition. E.g., given the structure</p>
<pre><code>{"root": {"inner": [{"name": "obj1"}, {"name": "obj2"}]}}
</code></pre>
<p>and the path <code>("root", "inner", "0", "name"}</code> I would obtain <code>"obj1"</code>. I just started learning Go and to be honest I found it quite hard to write it given the constraints imposed by Go's type system. Now it compiles and it seems to be working. To use it in my code, I needed additional helper functions with specific return types. All in all it seems to be a ugly hack with a lot of repetition. I'd like to see if this is the best one can do in Go.</p>
<p>Note: especially terrible is the distinction between <code>map[string]string</code> and <code>map[string]interface{}</code>. I though that <code>interface{}</code> would represent every type, but apparently not in this case. If I remove that part from the <code>switch</code> statement, the program does not work because <code>map[string]string</code> is not handled by the <code>map[string]interface{}</code> branch.</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"fmt"
"strconv"
)
func main() {
test := map[string]interface{}{
"root": map[string]interface{}{
"inner": []interface{}{
map[string]string{"name": "obj1"},
map[string]string{"name": "obj2"},
},
},
}
fmt.Println(TraverseToStr(test, []string{"root", "inner", "0", "name"}))
}
func TraverseToUint64(data interface{}, path []string) uint64 {
val, err := Traverse(data, path)
if err != nil {
return 0
} else {
return val.(uint64)
}
}
func TraverseToStr(data interface{}, path []string) string {
val, err := Traverse(data, path)
if err != nil {
return ""
} else {
return val.(string)
}
}
func TraverseToMap(data interface{}, path []string) map[string]interface{} {
val, err := Traverse(data, path)
if err != nil {
return make(map[string]interface{})
} else {
return val.(map[string]interface{})
}
}
func TraverseToArray(data interface{}, path []string) []interface{} {
val, err := Traverse(data, path)
if err != nil {
return make([]interface{}, 0)
} else {
return val.([]interface{})
}
}
func Traverse(data interface{}, path []string) (interface{}, error) {
var ok bool
current := data
for _, p := range path {
switch current.(type) {
case map[string]string:
if current, ok = current.(map[string]string)[p]; !ok {
return nil, fmt.Errorf("key not found in map: %s", p)
}
case map[string]interface{}:
if current, ok = current.(map[string]interface{})[p]; !ok {
return nil, fmt.Errorf("key not found in map: %s", p)
}
case []interface{}:
if i, err := strconv.ParseInt(p, 10, 64); err == nil {
array := current.([]interface{})
if int(i) < len(array) {
current = array[i]
} else {
return nil, fmt.Errorf("index %d out of bounds for %v", i, array)
}
} else {
return nil, fmt.Errorf("integer required, got: %s", p)
}
default:
return nil, fmt.Errorf("cannot traverse %T\n", current)
}
}
return current, nil
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Readability is essential for correct and maintainable programs.</p>\n\n<hr>\n\n<p>For example,</p>\n\n<p><code>traverse.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc main() {\n test := map[string]interface{}{\n \"root\": map[string]interface{}{\n \"inner\": []interface{}{\n map[string]string{\"name\": \"obj1\"},\n map[string]string{\"name\": \"obj2\"},\n },\n },\n }\n fmt.Println(\n TraverseToStr(test, []string{\"root\", \"inner\", \"0\", \"name\"}),\n )\n}\n\nfunc TraverseToUint64(data interface{}, path []string) (uint64, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return 0, err\n }\n return val.(uint64), nil\n}\n\nfunc TraverseToStr(data interface{}, path []string) (string, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return \"\", err\n }\n return val.(string), nil\n}\n\nfunc TraverseToMap(data interface{}, path []string) (map[string]interface{}, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return nil, err\n }\n return val.(map[string]interface{}), nil\n}\n\nfunc TraverseToArray(data interface{}, path []string) ([]interface{}, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return nil, err\n }\n return val.([]interface{}), nil\n}\n\nfunc Traverse(data interface{}, path []string) (interface{}, error) {\n var ok bool\n current := data\n for _, p := range path {\n switch current.(type) {\n case map[string]string:\n if current, ok = current.(map[string]string)[p]; !ok {\n return nil, fmt.Errorf(\"key not found in map: %s\", p)\n }\n case map[string]interface{}:\n if current, ok = current.(map[string]interface{})[p]; !ok {\n return nil, fmt.Errorf(\"key not found in map: %s\", p)\n }\n case []interface{}:\n i, err := strconv.ParseInt(p, 10, 64)\n if err != nil {\n return nil, fmt.Errorf(\"integer required, got: %s\", p)\n }\n array := current.([]interface{})\n if i < 0 || i >= int64(len(array)) {\n return nil, fmt.Errorf(\"index %d out of bounds for %v\", i, array)\n }\n current = array[i]\n default:\n return nil, fmt.Errorf(\"cannot traverse %T\\n\", current)\n }\n }\n return current, nil\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/fMcDZr1AZy_X\" rel=\"nofollow noreferrer\">https://play.golang.org/p/fMcDZr1AZy_X</a></p>\n\n<hr>\n\n<p><strong>Commentary:</strong></p>\n\n<p>Readability is essential for correct and maintainable programs.</p>\n\n<hr>\n\n<pre><code>fmt.Println(\n TraverseToStr(test, []string{\"root\", \"inner\", \"0\", \"name\"}),\n)\n</code></pre>\n\n<p>The primary line of code should be obvious. The first read through, we focus on the primary line, returning later to read error handling and other secondary details.</p>\n\n<p><code>TraverseToStr</code> is the primary code, fmt.Println is a secondary detail. We highlight the primary code on a separate line.</p>\n\n<hr>\n\n<pre><code>func TraverseToUint64(data interface{}, path []string) (uint64, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return 0, err\n }\n return val.(uint64), nil\n}\n</code></pre>\n\n<p>In Go, don't ignore errors.</p>\n\n<p>Unnecessary conditional indentation is hard to read. An idiosyncratic coding style is extrememly hard to read. Return immediately on error. <a href=\"https://github.com/golang/go/wiki/CodeReviewComments#indent-error-flow\" rel=\"nofollow noreferrer\">CodeReviewComments: Indent Error Flow</a></p>\n\n<hr>\n\n<pre><code>func TraverseToMap(data interface{}, path []string) (map[string]interface{}, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return map[string]interface{}{}, err\n }\n return val.(map[string]interface{}), nil\n}\n</code></pre>\n\n<p>Replace <code>make(map[string]interface{})</code>, a built-in function call, with <code>map[string]interface{}{}</code>, a composite literal value. </p>\n\n<pre><code>func TraverseToMap(data interface{}, path []string) (map[string]interface{}, error) {\n val, err := Traverse(data, path)\n if err != nil {\n return nil, err\n }\n return val.(map[string]interface{}), nil\n}\n</code></pre>\n\n<p>However, on error, return the zero value, <code>nil</code> for a map.</p>\n\n<hr>\n\n<pre><code>i, err := strconv.ParseInt(p, 10, 64)\nif err != nil {\n return nil, fmt.Errorf(\"integer required, got: %s\", p)\n}\narray := current.([]interface{})\nif i < 0 || i >= int64(len(array)) {\n return nil, fmt.Errorf(\"index %d out of bounds for %v\", i, array)\n}\ncurrent = array[i]\n</code></pre>\n\n<p>Replace a stream of code with the basic Go error pattern.</p>\n\n<p>Don't overuse the \"if expression; simple-statement statement\" form. </p>\n\n<hr>\n\n<pre><code>if i < 0 || i >= int64(len(array)) {\n return nil, fmt.Errorf(\"index %d out of bounds for %v\", i, array)\n}\n</code></pre>\n\n<p>When you see this error message,</p>\n\n<pre><code>invalid operation: i < len(array) (mismatched types int64 and int)\n</code></pre>\n\n<p>and this fix,</p>\n\n<pre><code>if int(i) < len(array) {\n}\n</code></pre>\n\n<p>stop and think. <code>i</code> may be negative. <code>i</code> is <code>int64</code>, <code>int(i)</code> will discard high-order bits when <code>int</code> is implemented as 32-bits.</p>\n\n<hr>\n\n<p><a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language Specification</a></p>\n\n<p><a href=\"http://www.gopl.io/\" rel=\"nofollow noreferrer\">The Go Programming Language</a></p>\n\n<p>\"I though that\" is not sufficient justification. Use authoritative sources.</p>\n\n<p>Go is strongly typed. Types <code>interface{}</code>, <code>map[string]string</code>, and map[string]interface{} are distinct and have different memory layouts.</p>\n\n<hr>\n\n<p>When the code is readable, it's possible to read much of the code and prove it correct.</p>\n\n<p>Sometimes it can be hard to establish invariants for maps. \"The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.\" <a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language Specification</a>. Also, since the <a href=\"https://golang.org/doc/go1.12\" rel=\"nofollow noreferrer\">Go 1.12 release</a>, \"fmt: Maps are now printed in key-sorted order to ease testing.\" Which leads some to believe, incorrectly, that maps are sorted.</p>\n\n<p>For this code, it's important to note that maps are not read iteratively in a for loop in random order. All map accesses are deterministic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:09:40.837",
"Id": "447272",
"Score": "0",
"body": "Thanks! Lots of useful points!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:20:12.443",
"Id": "229716",
"ParentId": "229658",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229716",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T19:15:25.113",
"Id": "229658",
"Score": "0",
"Tags": [
"go"
],
"Title": "Traversing a JSON-like data structure in Go"
}
|
229658
|
<p>I wrote this BrainFuck interpreter in ANSI C89:</p>
<pre><code>/*
* Copyright © 2019 James Larrowe
*
* This file is part of bf.
*
* bf is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* bf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bf. If not, see <https://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define DEF_MEM_SIZE 32768
#define ezs(x) (x)
#define exit_if_true(x, y) if(x) exit_perr(y)
void bf_interp(unsigned char *, const unsigned char *, size_t, size_t);
void exit_perr(const char *);
unsigned char *read_file(const char *, size_t *);
int main(int argc, char **argv)
{
size_t file_size,
mem_size = DEF_MEM_SIZE;
unsigned char *file, *mem;
if(argc != 2)
{
fprintf(stderr, "Error: Incorrect number of arguments\n"
" Usage: %s [file] (args...)\n", argv[0]);
return 1;
}
file = read_file(argv[1], &file_size);
mem = calloc(sizeof(*mem), mem_size);
exit_if_true(mem == NULL, "calloc()");
bf_interp(mem, file, mem_size, file_size);
free(mem);
free(file);
return 0;
}
void bf_interp(unsigned char *sp, const unsigned char *ip, size_t sp_size, size_t ip_size)
{
long spc = 0, ipc = 0;
while(ezs(size_t)ipc < ip_size)
{
/* I would put this inside the switch
* but clang warns about "unreachable code".
*/
int nest;
switch(ip[ipc])
{
case '>':
{
spc++;
if(ezs(size_t)spc >= sp_size)
{
unsigned char *tmp;
tmp = realloc(sp, sp_size + DEF_MEM_SIZE);
exit_if_true(tmp == NULL, "realloc()");
memset(tmp+sp_size, 0, DEF_MEM_SIZE);
memcpy(tmp, sp, sp_size);
sp_size += DEF_MEM_SIZE;
free(sp);
sp = tmp;
}
break;
}
case '<':
{
spc--;
if(spc < 0)
{
fputs("Error: spc < 0\n", stderr);
exit(1);
}
break;
}
case '+':
{
sp[spc]++;
break;
}
case '-':
{
sp[spc]--;
break;
}
case '.':
{
putchar(sp[spc]);
break;
}
case ',':
{
int c = getchar();
if(c != EOF)
sp[spc] = ezs(unsigned char)c;
break;
}
case '[':
{
if(sp[spc] == 0)
{
for( nest = 1; nest; )
{
ipc++;
if(ezs(size_t)ipc >= ip_size)
{
fputs("Error: ipc >= ip_size\n", stderr);
exit(1);
}
nest += (ip[ipc] == '[');
nest -= (ip[ipc] == ']');
}
}
break;
}
case ']':
{
if(sp[spc])
{
for( nest = 1; nest; )
{
ipc--;
if(ipc < 0)
{
fputs("Error: ipc < 0\n", stderr);
exit(1);
}
nest -= (ip[ipc] == '[');
nest += (ip[ipc] == ']');
}
}
break;
}
default:
break;
}
ipc++;
}
}
unsigned char *read_file(const char *argv1, size_t *size)
{
unsigned char *file;
size_t was_read, sz;
FILE *fp;
fp = fopen(argv1, "r");
exit_if_true(fp == NULL, "fopen()");
exit_if_true(fseek(fp, 0L, SEEK_END) == -1, "fseek()");
sz = ezs(size_t)ftell(fp);
exit_if_true(sz == ezs(size_t)-1, "ftell()");
*size = sz;
file = malloc(sz);
exit_if_true(file == NULL, "malloc()");
exit_if_true(fseek(fp, 0L, SEEK_SET) == -1, "fseek()");
was_read = fread(file, 1, sz, fp);
if(was_read != sz)
{
fprintf(stderr, "Unable to read file.\n"
"Read %zu bytes when %zu bytes were expected\n",
was_read, sz);
exit(1);
}
exit_if_true(fclose(fp) == EOF, "fclose()");
return file;
}
void exit_perr(const char *str)
{
perror(str);
exit(1);
}
</code></pre>
<p>It's been tested and it works properly, but there are some design issues I'm worried about. In particular:</p>
<ul>
<li><p>Have I split the code up into functions enough?</p></li>
<li><p>Do I have variable names that describe the code well?</p></li>
<li><p>How can I make it more efficient around the nesting code (<code>case '[':</code> and <code>case ']':</code>)?</p></li>
<li><p>Is it portable?</p></li>
<li><p>Are there any issues with it that I may have overlooked?</p></li>
</ul>
<p>This runs and produces results identical to many other BrainFuck interpreters that I've tried.</p>
<p>This is available under the GPLv3 in my GitHub repository <a href="https://github.com/JL2210/bf" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:24:49.950",
"Id": "449253",
"Score": "2",
"body": "Uff, this is horribly complicated code (hard to maintain, hard to find a bug). Keep it simple. Take a look at [this one](https://github.com/xbarin02/bf/blob/master/bf.c) :)"
}
] |
[
{
"body": "<p>Okay, what's the deal with <code>#define ezs(x) (x)</code>? Is it some kind of trick to either hide C-style casts, or make them more greppable? If the latter, why such a short name? How about <code>#define CAST_TO(x) (x)</code>?</p>\n\n<hr>\n\n<p>Other naming comments:</p>\n\n<ul>\n<li><p><code>was_read</code> sounds like a boolean. I think you mean <code>bytes_read</code> or even <code>num_bytes_read</code>.</p></li>\n<li><p>Your function names are all tersified according to different conventions. You've got <code>interpret_brainfuck</code> (verb-noun), <code>perror_and_exit</code> (verb-and-verb), and <code>read_file</code> (verb-noun) — but you've tersified them as <code>bf_interp</code> (noun-abbrverb), <code>exit_perr</code> (reversed the order of the verbs for some reason), and... okay, <code>read_file</code> is a good name. :)</p></li>\n</ul>\n\n<hr>\n\n<pre><code>#define exit_if_true(x, y) if(x) exit_perr(y)\n</code></pre>\n\n<p>(A) Why is this not a (<code>static</code>) <code>inline</code> function? I don't think the macro is buying you anything.</p>\n\n<p>(B) Consider:</p>\n\n<pre><code>if (cond1)\n exit_if_true(cond2, \"message\");\nelse\n puts(\"cond1 was false\"); // LIES!\n</code></pre>\n\n<p>Always, always, always use proper macro hygiene in C and C++! It costs nothing, and it shows the reader that you know what you're doing, and every so often it avoids a really sneaky bug.\nWhat you should have written was:</p>\n\n<pre><code>#define exit_if_true(x, y) do { if (x) exit_perr(y); } while (0)\n</code></pre>\n\n<p>or, even better,</p>\n\n<pre><code>static inline void exit_if_true(bool b, const char *message) {\n if (b) {\n exit_perr(message);\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>size_t file_size,\n mem_size = DEF_MEM_SIZE;\nunsigned char *file, *mem;\n</code></pre>\n\n<p>Please, for the sake of your readers, write each declaration on its own line. I mean, it costs literally <em>one</em> more line of source code to write</p>\n\n<pre><code>size_t file_size;\nsize_t mem_size = DEF_MEM_SIZE;\nunsigned char *file;\nunsigned char *mem;\n</code></pre>\n\n<p>This also calls attention to the fact that you failed to initialize three of these variables. That smells like a bug. Let's see...</p>\n\n<pre><code>file = read_file(argv[1], &file_size);\nmem = calloc(sizeof(*mem), mem_size);\n</code></pre>\n\n<p>Ah. So it actually would have <em>saved</em> you several lines of code to write simply</p>\n\n<pre><code>if (argc != 2) {\n fprintf(stderr, \"Error: Incorrect number of arguments\\n\"\n \" Usage: %s [file] (args...)\\n\", argv[0]);\n return 1;\n}\nsize_t file_size;\nunsigned char *file = read_file(argv[1], &file_size);\n\nsize_t mem_size = DEF_MEM_SIZE;\nunsigned char *mem = calloc(mem_size, 1);\nexit_if_true(mem == NULL, \"calloc()\");\n</code></pre>\n\n<p>I notice in passing that <code>return 1;</code> is quite natural and correct and POSIX-compliant — it's a really good idea to specify exactly what integral value your process returns on error — but <em>technically</em> it's not \"ANSI C\" to do that. ANSI C wants you to use <code>return EXIT_FAILURE;</code>, which returns an implementation-defined \"failure\" result.</p>\n\n<p>More importantly, you accidentally swapped the arguments to <code>calloc</code>. <a href=\"https://linux.die.net/man/3/calloc\" rel=\"noreferrer\">They go <code>nmemb, size</code>.</a> And yes, I had to look it up. I know that I <em>always</em> have to look it up. This, IMVHO, is a reason never to use <code>calloc</code> — I'd use <code>malloc</code> and then do an explicit <code>memset</code> if for some reason I <em>needed</em> zero-initialization.</p>\n\n<p>Notice that <code>sizeof(char)</code> is <code>1</code> by definition.</p>\n\n<hr>\n\n<pre><code>long spc = 0, ipc = 0;\n</code></pre>\n\n<p>Again, I strongly recommend one declaration per line.</p>\n\n<p>What's weird here is that you're carefully defining these variables as <code>long</code>... but then casting them to <code>size_t</code> everywhere they're used! Why not just define them as <code>size_t</code>?</p>\n\n<p>I also personally dislike seeing <code>long</code> because its size varies from platform to platform. \"Everyone knows\" that on common desktop systems <code>int</code> is 32 bits and <code>long long</code> is 64, but the size of <code>long</code> might be one or the other, depending on architecture and operating system. Using <code>long</code> is like saying, \"I <em>want</em> to have portability problems a year from now.\"</p>\n\n<hr>\n\n<pre><code>free(mem);\n</code></pre>\n\n<p>This is a double-free and crash bug. <code>bf_interp</code> will have freed the <em>original</em> value of <code>mem</code> the very first time it does a <code>realloc</code>. Either</p>\n\n<ul>\n<li>pass <code>mem</code> by address to <code>bf_interp</code> so that <code>bf_interp</code> can modify it, or</li>\n<li>transfer the responsibility for freeing <code>mem</code> into <code>bf_interp</code> — turn <code>bf_interp</code> into a \"sink.\"</li>\n</ul>\n\n<p>Since <code>bf_interp</code> uses <code>mem</code> as scratch space, trashing its semantic <em>contents</em> as well as its physical pointer value, I think the second option above makes quite a bit of sense.</p>\n\n<p>The one thing that might change my mind is if you could demonstrate that <code>bf_interp</code> does not \"trash\" <code>mem</code>'s contents, but rather updates them in a meaningful way. For example, if <code>bf_interp</code> took a parameter <code>num_steps</code>, and ran the program for that many steps, and then returned, so that you could \"resume\" the interpretation later — well, then it would make sense that <code>bf_interp</code> needs a way to pass <code>mem</code> back out to its caller. (But then <code>bf_interp</code> would also need a way to pass the rest of its state — <code>ipc</code> and <code>spc</code>. And now you're halfway to inventing object-oriented programming.)</p>\n\n<hr>\n\n<p>Oh hey — your entire use of <code>realloc</code> is wrong!</p>\n\n<pre><code> tmp = realloc(sp, sp_size + DEF_MEM_SIZE);\n exit_if_true(tmp == NULL, \"realloc()\");\n\n memset(tmp+sp_size, 0, DEF_MEM_SIZE);\n memcpy(tmp, sp, sp_size);\n\n sp_size += DEF_MEM_SIZE;\n\n free(sp);\n sp = tmp;\n</code></pre>\n\n<p>This should be simply</p>\n\n<pre><code> sp = realloc(sp, sp_size + DEF_MEM_SIZE);\n exit_if_true(sp == NULL, \"realloc()\");\n\n memset(sp + sp_size, 0, DEF_MEM_SIZE);\n sp_size += DEF_MEM_SIZE;\n</code></pre>\n\n<p>Your version would become correct (but still inefficient) if you replaced <code>realloc</code> with simply <code>malloc</code>. The point of <code>realloc</code> is that it does the <em>re</em>-allocation for you; you don't have to manually free the old buffer or copy over the data.</p>\n\n<p>If you used something like <code>gcov</code> to look at your code coverage, you'd see that your test cases (you have test cases, right?) never hit this codepath. That's why you didn't find the bug. If you had hit this codepath, the program definitely would have crashed.</p>\n\n<hr>\n\n<pre><code> /* I would put this inside the switch\n * but clang warns about \"unreachable code\".\n */\n int nest;\n</code></pre>\n\n<p>The declaration of this variable should go at the variable's point of use. Like this:</p>\n\n<pre><code> for (int nest = 1; nest != 0; )\n</code></pre>\n\n<hr>\n\n<p>Your usage message says:</p>\n\n<pre><code>Usage: ./a.out [file] (args...)\n</code></pre>\n\n<p>This isn't right, is it? I mean, <code>file</code> is not optional, and there is no such thing as <code>args...</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:14:04.763",
"Id": "449263",
"Score": "0",
"body": "Your point about defining the variables after the `if` is invalid. Note the title, which says \"in ANSI C\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:15:59.907",
"Id": "449264",
"Score": "0",
"body": "Same for the inline functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:25:53.587",
"Id": "449268",
"Score": "0",
"body": "Nice note about the `calloc`, but the order of the arguments doesn't matter. It's really just a simple multiplication and a check for overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:27:02.337",
"Id": "449269",
"Score": "0",
"body": "`spc` and `ipc` can't be `size_t` because then the checks for `< 0` on them wouldn't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:33:52.043",
"Id": "449270",
"Score": "0",
"body": "About `realloc` and the double free -- extremely good catch. I wrote this at 9:00 last Friday, so I guess that's why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:34:40.697",
"Id": "449271",
"Score": "0",
"body": "I wish I had test cases but they'd be 32KB long to test this. Sadly, `gcov` doesn't work well for me. I tried it once but it just didn't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:36:22.090",
"Id": "449272",
"Score": "0",
"body": "I can't have the declaration of `nest` inside the `for` loop because would not be ANSI C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:36:41.760",
"Id": "449273",
"Score": "0",
"body": "I'll fix the usage, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:32:50.857",
"Id": "449285",
"Score": "1",
"body": "@JL2210: As far as I know, ANSI C tracks ISO C, so the current standard is 2018. Admittedly my close knowledge of C stops circa 1999 (20 years ago), but if you're saying that you can't use `inline` functions because you're stuck on 19*89* (30 years ago)... *and* without GNU C extensions... well, I don't think you have any valid engineering reason for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:33:45.253",
"Id": "449286",
"Score": "1",
"body": "You can definitely test the `spc`-realloc bug with a short test case. Use nested loops."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:34:03.837",
"Id": "449287",
"Score": "0",
"body": "I completely forgot about the current version of ANSI C. I was referring to ANSI C89. I'll clarify that in the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:35:29.357",
"Id": "449288",
"Score": "0",
"body": "I was mainly concerned with Windows-compatibility."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:41:10.360",
"Id": "449424",
"Score": "0",
"body": "Any note on how to make the nesting faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:35:58.057",
"Id": "449507",
"Score": "1",
"body": "If you're asking whether Windows (MSVC) supports `for (int i=0; i < n; ++i)`, the answer is \"yes, since sometime in the '90s.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:30:52.440",
"Id": "449609",
"Score": "0",
"body": "Could you please go over performance in this answer?"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T16:50:56.113",
"Id": "230557",
"ParentId": "229664",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "230557",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T21:37:39.433",
"Id": "229664",
"Score": "11",
"Tags": [
"c",
"reinventing-the-wheel",
"interpreter",
"brainfuck",
"c89"
],
"Title": "Portable BrainFuck Interpreter in ANSI C89"
}
|
229664
|
<p>This was <strong>the task</strong> (I don't know the exact wordings anymore):</p>
<blockquote>
<p>You get a string with operation as input:</p>
<ol>
<li>if it is a number push it to stack</li>
<li>if it is "DUP", then duplicate the one one top and push it to the
stack</li>
<li>if it is "POP" then remove the one on top</li>
<li>if it is "+" add the two numbers on top of the stack and replace
both with the result of the addition</li>
<li>if it is "-" then minus the two numbers on top (the second minus
the first) of the stack and replace both with the result of the
subtraction</li>
<li>if an error occurs, e.g. not enough numbers to add/subtract/pop,
then return -1</li>
</ol>
</blockquote>
<p><strong>Examples</strong>:</p>
<pre><code>Input: "3 DUP 5 - -"
Output: -1
Input: "13 DUP 4 POP 5 DUP + DUP + -"
Output: 7
Input: "5 6 + -"
Output: -1
</code></pre>
<p><strong>My approach</strong> is quite simple. I differentiate between numbers and operations. If it is a number I simply push it to the stack. Otherwise Ill check what kind of operation it is. If a valid operation is recognized, then the mapped function will be executed.</p>
<p>If an error occurs, e.g. no more numbers in the stack to be popped, invalid operation, etc. it will return <code>-1</code>.</p>
<p><strong>My solution</strong> </p>
<pre><code>function solution(S) {
if (!S.length) {
return -1;
}
const stack = new Array();
const push = n => stack.push(Number(n));
const pop = () => {
if (!stack.length) {
throw new Error('empty');
}
return stack.pop();
}
const duplicate = () => {
try {
const dup = pop();
push(dup);
push(dup);
} catch(e) {
throw new Error(e);
}
};
const add = () => {
try {
const sum1 = pop();
const sum2 = pop();
push(sum1 + sum2);
} catch(e) {
throw new Error(e);
}
};
const minus = () => {
try {
const min1 = pop();
const min2 = pop();
push(min1 - min2);
} catch(e) {
throw new Error(e);
}
};
const ops = {
"DUP": duplicate,
"POP": pop,
"+": add,
"-": minus,
};
const input = S.split(' ');
input.forEach(x => {
if (!isNaN(x)) {
push(x);
} else {
try {
const sanitzedX = x.toUpperCase();
if (!ops[sanitzedX]) {
return -1;
}
ops[sanitzedX]();
} catch(e) {
return -1;
}
}
});
try {
return pop();
} catch(e) {
return -1;
}
}
console.log(solution("3 DUP 5 - -"));
console.log(solution("13 DUP 4 POP 5 DUP + DUP + -"));
console.log(solution("5 6 + -"));
</code></pre>
|
[] |
[
{
"body": "<pre><code>const stack = new Array()\n</code></pre>\n\n<p>Use the literal notation (<code>[]</code>) instead. Here's <a href=\"https://stackoverflow.com/q/931872/575527\">an answer on Stack Overflow</a> that elaborates why you should do that instead of <code>new Array()</code>.</p>\n\n<pre><code>const duplicate = () => {\n try {\n const dup = pop();\n push(dup);\n push(dup); \n } catch(e) {\n throw new Error(e); \n }\n};\n</code></pre>\n\n<p>The rule of thumb when it comes to using exceptions is to <em>never use them where you can use an <code>if</code></em>. That is, don't use exceptions as a flow control mechanism. You should only use it if you want to bail out and do no further.</p>\n\n<p>Also, <code>e</code> is already an instance of <code>Error</code>. You only need to do <code>throw e</code>, not <code>throw new Error(e)</code>.</p>\n\n<p>Now if you look closely, all the operations are distinct to each other. They also only operate on the stack only. You can easily implement them as pure functions, taking in the current stack, and returning a new representation of the stack.</p>\n\n<p>For example, <code>duplicate</code> can be implemented as a function that takes an array, and returns a new array, with the last item repeated once more:</p>\n\n<pre><code>const duplicate = stack =>\n stack.length < 1 ? -1 \n : [...stack, stack[stack.length - 1]]\n</code></pre>\n\n<p><code>add</code> can be implemented as a function that takes an array, and return an new array which replaces the last two items with their sum:</p>\n\n<pre><code>const add = stack =>\n stack.length < 2 ? -1 \n : [...stack.slice(0, -2), stack[stack.length - 1] + stack[stack.length - 2]]\n</code></pre>\n\n<p>Doing it this way makes it easier to implement each operation without having them becoming dependent on some common state object, or each other.</p>\n\n<p>Here's how I would implement it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Implement each operation as distinct, pure functions.\nconst push = (stack, v) => [...stack, v]\n\nconst pop = stack => \n stack.length < 1 ? -1\n : stack.slice(0, -1)\n\nconst duplicate = stack =>\n stack.length < 1 ? -1 \n : [...stack, stack[stack.length - 1]]\n\nconst add = stack =>\n stack.length < 2 ? -1 \n : [...stack.slice(0, -2), stack[stack.length - 1] + stack[stack.length - 2]]\n\nconst subtract = stack =>\n stack.length < 2 ? -1\n : [...stack.slice(0, -2), stack[stack.length - 1] - stack[stack.length - 2]]\n\n// Map operation tokens to their implementation.\n// Should we add more operations, we simply add the implementation and reference\n// its token in this map\nconst operations = {\n 'DUP': duplicate,\n 'POP': pop,\n '+': add,\n '-': subtract\n}\n\nconst solution = s => {\n\n // For each token, parse and process.\n // You can implement this piece using iteration functions, loops, or even recursion.\n // I'm just more accustomed to reduce because it can carry a value across iterations\n // which, in this case, holds the stack for me.\n const result = s.split(' ').reduce((stack, token) => {\n \n // If any operation returned -1, we return -1 all the way.\n return stack === -1 ? -1\n // If token is a number, push it to the stack.\n : !isNaN(parseFloat(token)) && isFinite(token) ? push(stack, Number(token))\n // If token is an operation, apply operation.\n : operations[token.toUpperCase()] ? operations[token.toUpperCase()](stack)\n // Unknown token.\n : -1\n\n // Our stack as initial reduce value, an empty array.\n }, [])\n\n // If the result is -1, then so be it. Otherwise, return the top of the stack.\n return result === -1 ? -1 : result[result.length - 1]\n}\n\nconsole.log(solution(\"3 DUP 5 - -\"));\nconsole.log(solution(\"13 DUP 4 POP 5 DUP + DUP + -\"));\nconsole.log(solution(\"5 6 + -\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T04:44:26.150",
"Id": "446927",
"Score": "0",
"body": "Isn't it ineffecient to use reduce?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T12:30:56.453",
"Id": "446990",
"Score": "0",
"body": "@thadeuszlay Sure, returning new arrays every time and `array.reduce()` may not be the most efficient way to do this. But this example is so small, any cons brought about by these approaches is practically negligible. Pre-mature optimization is bad. I'd optimize for readability and reducing cognitive overhead first before anything else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:23:56.083",
"Id": "447040",
"Score": "0",
"body": "How would you solve it if you have a huge set of input data, i.e. how would your solution look like, if the task would ask you to find not the most readable but most efficient algorithm?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T04:19:32.810",
"Id": "229676",
"ParentId": "229666",
"Score": "3"
}
},
{
"body": "<p>In JavaScript using exceptions to communicate standard logic information is rather bad. Exceptions are bulky and slow (some browsers can not optimise code containing try blocks).\nYour handling of errors will also mask real errors and thus let serious problems slip by while developing the code.</p>\n\n<p>When you use exceptions always check the error in the catch to see if it is part of the functions proper execution, all other errors you should re throw.</p>\n\n<p>Also use one try catch, there is no need to add try catches in every function.</p>\n\n<h2>Using exceptions</h2>\n\n<p>The rewrite cleans up your exception handling and adds a custom error <code>StackError</code> The one <code>catch</code> first checks the error and passes on all unrelated errors to a higher level.</p>\n\n<pre><code>function problem(S) {\n function StackError() { }\n if (!S.length) { return -1 }\n const stack = [];\n const push = n => stack.push(Number(n));\n const pop = () => {\n if (stack.length) { return stack.pop() }\n throw new StackError();\n }\n const duplicate = () => {\n const dup = pop();\n push(dup);\n push(dup); \n };\n const add = () => {\n const sum1 = pop();\n const sum2 = pop();\n push(sum1 + sum2); \n };\n const minus = () => {\n const min1 = pop();\n const min2 = pop();\n push(min1 - min2);\n };\n const ops = {\n \"DUP\": duplicate,\n \"POP\": pop,\n \"+\": add,\n \"-\": minus,\n };\n\n const input = S.split(' ');\n try { \n input.forEach(x => {\n if (!isNaN(x)) {\n push(x);\n } else {\n const op = ops[x.toUpperCase()];\n if (op) { op() } else { throw new StackError() }\n }\n });\n return pop();\n } catch(error) {\n if (!(error instanceof StackError)) { throw error }\n return -1;\n }\n}\n</code></pre>\n\n<h2>Without the error handling</h2>\n\n<p>The next rewrite handles the error state via a semaphore that when true is used to exit the function. This also shows why using <code>for of</code> loops makes the code less complex. (You can only exit early from a iteration function via an exception (or other hacks)</p>\n\n<pre><code>function problem(S) {\n if (!S.length) { return -1 }\n const stack = [];\n const push = n => stack.push(Number(n));\n var error = false;\n const pop = () => {\n if (stack.length) { return stack.pop() }\n return (error = true, -1);\n }\n const ops = {\n POP: pop,\n DUP() {\n const dup = pop();\n push(dup);\n push(dup); \n },\n \"+\"() { push(pop() + pop()) },\n \"-\"() { push(pop() - pop()) }\n };\n for (const item of S.split(\" \")) {\n if (!isNaN(item)) {\n push(item);\n } else {\n const op = ops[item];\n if (op) { op() }\n if (error) { return - 1 }\n }\n }\n return pop();\n}\n</code></pre>\n\n<p>I removed some repeated code defining functions and then adding them to <code>ops</code> was just repeated definitions.</p>\n\n<h2>Performance</h2>\n\n<p>Pushing and popping from a stack is fast but will still incur memory allocation and release (GC) overheads. If the stack grows and shrinks a lot then this overhead becomes significant.</p>\n\n<p>To avoid most of the allocation / de allocation overhead only grow the array and keep a pointer to the top of the stack.</p>\n\n<p>The stack will never use more memory than it already does (well in fact using the pointer method uses less memory as de/allocation can result in duplicated arrays in RAM waiting for GC and the pointer method reduces the number of GC tasks) </p>\n\n<pre><code>function problem(instructionStr) {\n var err = false, len = 0, item;\n if (instructionStr.trim() === \"\") { return -1 }\n const defaultOp = () => isNaN(item) ? err = true : stack[len++] = Number(item);\n const stack = [], ops = {\n DUP() { len ? stack[len] = stack[len++ - 1] : err = true },\n POP() { len ? len-- : err = true },\n \"+\"() { --len ? stack[len - 1] = stack[len] + stack[len - 1] : err = true },\n \"-\"() { --len ? stack[len - 1] = stack[len] - stack[len - 1] : err = true }\n };\n for (item of instructionStr.split(\" \")) {\n ops[item] ? ops[item]() : defaultOp();\n if (err) { return -1 }\n }\n return len ? stack[len - 1] : -1;\n}\n</code></pre>\n\n<h2>Re Optimization</h2>\n\n<p>I totally disagree with Joseph comment under his answer</p>\n\n<blockquote>\n <p><em>\"Pre-mature optimization is bad. I'd optimize for readability and reducing cognitive overhead first before anything else\"</em></p>\n</blockquote>\n\n<p>Optimization does not mean that the code is any less readable. Micro optimizations sum up and should be habit, not the exception. Readability is what people are accustomed to, and I think this is where such comments as Joseph's stem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:11:37.473",
"Id": "447122",
"Score": "0",
"body": "Why did you use `var`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:21:06.173",
"Id": "447124",
"Score": "0",
"body": "@thadeuszlay to match the scope of the variable (function wide). I only use `let` for block scoped variables and then only under very specific use cases such as naming conflicts. ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T18:54:22.670",
"Id": "447163",
"Score": "2",
"body": "Doesn't this add additional cognitive load if you add more concepts than neccessary? If you only had `let` and `const` than you only need to reason about these 2. Also what if I want to move the variable from function wide to a more narrow scope? Then I need to change it from `var` to `let`. Can you please explain to me the advantage of your approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:33:44.640",
"Id": "447278",
"Score": "0",
"body": "The problem I have with _var_ is that it's subjunctive. It allows for many possible declarations, depending on which branch the code took earlier in the function. It's much easier to abuse this concept than to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T00:37:22.267",
"Id": "447315",
"Score": "0",
"body": "@dfhwze i must disagree. A function should not be longer than a page (or two at the most) and its cyclomatic complexity should be kept as low as possible if you find that your use of a variable is \"subjunctive\" the cause is not the declaration type but rather the cause is the design of the function. `let` and `const` can have the same scope as `var` function args are `vars`. Vars should be hoisted. `let` by your reasoning encourages long complex function design. let is \"subjunctive\" in a way var can never be. Example `for(let i=0;i<9;i++){ let r=d[i]; for(let i=0;i<9; i++){ rw[i]++ }}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T02:29:37.460",
"Id": "447317",
"Score": "0",
"body": "@thadeuszlay Block scopes behavior is not always intuitive..A loop `for(let i=0;i<1;i++) {let i= 0}` Will the loop end? how many variables are defined? how many lexical scopes are there? is the following single statement loop the same? `for(let i=0; i<2; i++) let i=0;` Now 2 similar loops `for(let i=0;i<1e6;i++){ let p=[1,2,3,i];setTimeout(()=>{p})}` and `var i,p; for(i=0;i<1e6;i++){ p=[1,2,3,i];setTimeout(()=>{p})}`Which is most performant? How much do they differ (CPU/RAM), why? What would happen if you used `setInterval`? Answers are easy if using `var` very few get it correct with `let`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T19:24:18.497",
"Id": "229719",
"ParentId": "229666",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T22:00:40.810",
"Id": "229666",
"Score": "4",
"Tags": [
"javascript",
"programming-challenge",
"ecmascript-6"
],
"Title": "Process strings of operations"
}
|
229666
|
<p><em>The most valuable of all talents is that of never using two words when one will do. Thomas Jefferson.</em></p>
<p><a href="https://www.nuget.org/packages/X.ComponentModel/" rel="nofollow noreferrer">NuGet</a> and <a href="https://github.com/dmitrynogin/x-utils/tree/e8082084758ae3a4d60c9c922b863d131bb50d2a" rel="nofollow noreferrer">GitHub</a></p>
<p>I found it useful to automatically normalize string content a little bit and explicitly state what kind of content could be held in a field:</p>
<pre><code>[TestMethod]
public void Normalize()
{
var name = new Name(" Thomas ", null, " Jefferson \n \r ");
Assert.AreEqual("Thomas", name.First);
Assert.AreEqual("", name.Middle);
Assert.AreEqual("Jefferson", name.Last);
}
</code></pre>
<p>where test uses the following demo class:</p>
<pre><code>class Name
{
public Name(string first, string middle, string last)
: this((Word)first, (WordOrEmpty)middle, (Word)last)
{
}
public Name(Word first, WordOrEmpty middle, Word last)
{
First = first;
Middle = middle;
Last = last;
}
public Word First { get; }
public WordOrEmpty Middle { get; }
public Word Last { get; }
}
</code></pre>
<p>Library classes are:</p>
<pre><code>public class Text : String<Text>, IEnumerable<Line>
{
public static explicit operator Text(string text) => new Text(text);
public Text(string text)
: base(text, EmptyIfNull, Trim)
{
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<Line> GetEnumerator() => Text
.Split(new[] { "\r\n", "\n\r", "\r", "\n" }, StringSplitOptions.None)
.Select(l => (Line)l)
.GetEnumerator();
}
</code></pre>
<p>And:</p>
<pre><code>public class Line : String<Line>, IEnumerable<Word>
{
public static explicit operator Line(string text) => new Line(text);
public Line(string text)
: base(text, EmptyIfNull, Trim, SpaceIfNewLine)
{
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<Word> GetEnumerator() => Text
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(l => (Word)l)
.GetEnumerator();
}
</code></pre>
<p>And:</p>
<pre><code>public class LineOrNull : String<LineOrNull>, IEnumerable<Word>
{
public static explicit operator LineOrNull(string text) => new LineOrNull(text);
public LineOrNull(string text)
: base(text, NullIfEmpty, Trim, SpaceIfNewLine)
{
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<Word> GetEnumerator() => (Text ?? "")
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(l => (Word)l)
.GetEnumerator();
}
</code></pre>
<p>And:</p>
<pre><code>public class Word : String<Word>
{
public static explicit operator Word(string text) => new Word(text);
public Word(string text)
: base(text, NotNullOrWhitespace, Trim, NotMultiline, NoSpace)
{
}
}
</code></pre>
<p>And:</p>
<pre><code>public class WordOrNull : String<WordOrNull>
{
public static explicit operator WordOrNull(string text) => new WordOrNull(text);
public WordOrNull(string text)
: base(text, Trim, NullIfEmpty, NotMultiline, NoSpace)
{
}
}
</code></pre>
<p>And:</p>
<pre><code>public class WordOrEmpty : String<WordOrEmpty>
{
public static explicit operator WordOrEmpty(string text) => new WordOrEmpty(text);
public WordOrEmpty(string text)
: base(text, Trim, EmptyIfNull, NotMultiline, NoSpace)
{
}
}
</code></pre>
<p>Where:</p>
<pre><code>[JsonConverter(typeof(StringJsonConverter))]
public abstract class String<T> : ValueObject<T>
where T: String<T>
{
protected static string Trim(string text) => text?.Trim();
protected static string EmptyIfNull(string text) => text ?? Empty;
protected static string NullIfEmpty(string text) => IsNullOrWhiteSpace(text) ? null : text;
protected static string SpaceIfNewLine(string text) => text
?.Replace("\n\r", " ")
?.Replace("\r\n", " ")
?.Replace("\r", " ")
?.Replace("\n", " ");
protected static string Upper(string text) => text?.ToUpper();
protected static string Lower(string text) => text?.ToLower();
protected static string NotNull(string text) =>
text ?? throw new TextException();
protected static string NotNullOrWhitespace(string text) =>
IsNullOrWhiteSpace(text) ? throw new TextException() :
text;
protected static string NotNullOrEmpty(string text) =>
IsNullOrEmpty(text) ? throw new TextException() :
text;
protected static string NoSpace(string text) =>
text == null ? null :
text.Contains(' ') ? throw new TextException() :
text;
protected static string NotMultiline(string text) =>
text == null ? null :
text.Contains('\n') || text.Contains('\r') ? throw new TextException() :
text;
public static implicit operator string(String<T> s) => s?.Text;
protected String(string text, params Func<string, string>[] actions) =>
Text = actions.Aggregate(text, (acc, f) => f(acc));
public string Text { get; set; }
public override string ToString() => Text;
protected override IEnumerable<object> EqualityCheckAttributes =>
new[] { Text };
}
</code></pre>
<p>Where:</p>
<pre><code>public class TextException : Exception
{
public TextException([CallerMemberName] string rule = null)
: base($"Must be {rule}.")
{
}
}
</code></pre>
<p>And:</p>
<pre><code>class StringJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType) =>
objectType == typeof(object) ? false :
objectType.IsConstructedGenericType && objectType.GetGenericTypeDefinition() == typeof(String<>) ? true :
CanConvert(objectType.BaseType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) =>
Activator.CreateInstance(objectType, reader.Value);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>
writer.WriteValue(value.ToString());
}
</code></pre>
<p>And:</p>
<pre><code>public abstract class ValueObject<T> : IEquatable<ValueObject<T>>
where T : ValueObject<T>
{
protected abstract IEnumerable<object> EqualityCheckAttributes { get; }
public override int GetHashCode() =>
EqualityCheckAttributes
.Aggregate(0, (hash, a) => unchecked(hash * 31 + (a?.GetHashCode() ?? 0)));
public override bool Equals(object obj) =>
Equals(obj as ValueObject<T>);
public virtual bool Equals(ValueObject<T> other) =>
other != null &&
GetType() == other.GetType() &&
EqualityCheckAttributes.SequenceEqual(other.EqualityCheckAttributes);
public static bool operator ==(ValueObject<T> left, ValueObject<T> right) =>
Equals(left, right);
public static bool operator !=(ValueObject<T> left, ValueObject<T> right) =>
!Equals(left, right);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T08:10:19.343",
"Id": "446953",
"Score": "1",
"body": "Would you mind clarifying why you provide string overloads for the construct of `Name`? It's not clear to me why it should be the job of `Name` (or other similar classes) to normalise those inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T14:46:04.677",
"Id": "447010",
"Score": "1",
"body": "@VisualMelon compare to `StreamWriter` ctor overloads. It saves a bunch of typing by having a primitive type based overload, especially while unit testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T16:26:08.763",
"Id": "447019",
"Score": "0",
"body": "@VisualMelon Though it is a little bit of \"frameworkish\", not so common for business object types where we are trying to get rid of all technical complexity. It asks for a partial class :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:45:03.887",
"Id": "448002",
"Score": "1",
"body": "I would _group_ the `static` helpers in nested classes like `Filters` and `Constraints` so their usage would be easier to understand like: `base(text, Filters.Trim, Filters.NullIfEmpty, Constraints.NotMultiline, Constraints.NoSpace)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:49:14.683",
"Id": "448003",
"Score": "1",
"body": "@t3chb0t How `Use.Trimmed`, `Use.NullIfEmpty` and `Only.NotMultiline` sound?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:52:35.973",
"Id": "448004",
"Score": "1",
"body": "You're thinking about making it _fluent_? ;-] then we'll need to think harder :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:53:38.357",
"Id": "448005",
"Score": "0",
"body": "Oh, I've just noticed the edit... `Use` sounds much better... I could live with `Only`, sounds ok too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:54:40.040",
"Id": "448006",
"Score": "1",
"body": "@t3chb0t May be three: `Use`, `Only`, and `Not` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:55:19.790",
"Id": "448007",
"Score": "1",
"body": "haha, I was going to suggest the same thing to get rid of the `Not` in some names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T07:13:32.760",
"Id": "448054",
"Score": "0",
"body": "I wonder why `Equals` needs this `GetType() == other.GetType()` condition? It works only with `ValueObject<T>` so they are always of the same type - this check is redundant, isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:28:58.253",
"Id": "448117",
"Score": "0",
"body": "@t3chb0t there is no limit of the inheritance depth captured in VO<T>, while value equality semantics requires type equality. It is a well documented pattern - you could read about it [here](https://www.amazon.com/Patterns-Principles-Practices-Domain-Driven-Design/dp/1118714709/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:52:30.377",
"Id": "448127",
"Score": "0",
"body": "I even own this book o_O bought it once and forgot about it LOL - I'd be very nice if you could give me the pattern's name ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:01:31.583",
"Id": "448129",
"Score": "1",
"body": "@t3chb0t No surprise here - Chapter 15: Value Objects :) You could also have a look at Pluralsight [course](https://app.pluralsight.com/library/courses/csharp-equality-comparisons/) on Equality and Comparisons - equality is tricky when inheritance is involved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T17:58:03.753",
"Id": "448142",
"Score": "0",
"body": "ok, I looked at that chapter and I find my solution is much better, especially that their examples are only examples and they suggest using reflection or other techniques anyway. I also find it's weird that they do not use `yield return` in their attribute enumerators but create arrays and that the `ValueObject<T>` does not implement `IEquatable<>` which you have already addressed ;-] Overall it's a good starting point and inspiration that certainly requires adding the `IEqualityComparer<T>` and using a different technique from `SequenceEqual` which is very weak in the long run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:01:02.483",
"Id": "448143",
"Score": "0",
"body": "...and I need to look at the other chapters too... lot's of interesting stuff there but I guess they are only basics that need to be made production-ready first ;-] If they made it bullet-proof they could just have made it a NuGet package :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T19:43:36.013",
"Id": "448154",
"Score": "0",
"body": "@t3chb0t Actually, I found this `VO<T>` a very useful tool as it is. It just keeps all technical stuff away in the base type without polluting business object itself. You could also find a good explanation of redundancy of `IEquitable<T> where T: class` in that Pluralsight video. `IEquitable<T>` was mostly introduced to prevent boxing of value types..."
}
] |
[
{
"body": "<p>I don't have much to say, but this stuff does look useful. The types are designed to be exposed to the world, so it's transparent to the consumer and could make the intentions clear.</p>\n\n<p>There is one huge problem: </p>\n\n<pre><code>public string Text { get; set; }\n</code></pre>\n\n<p>Anyone can change this value and by-pass all the rules: I assume this is a typo and you intended for this to be getter-only.</p>\n\n<h2>General Stuff</h2>\n\n<p>This all needs documenting, to explain what the different classes do. <code>SpaceIfNewLine</code> is one example that baffles me completely: I would expect <code>Line</code> to fail if someone threw a complete text at it. I don't like this behaviour, because we shouldn't allow the user to accidently overlook that and give them nonsensical but meaningful results to trip over later (fail fast and all that); if you want this behaviour, then it must be documented clearly. <code>NotMultiline</code> and <code>NoSpace</code> with <code>Word</code> make much more sense to me.</p>\n\n<p>I don't like how you swap <code>null</code> or <code>\"\"</code> and vice-versa in places. Perhaps this is completely necessary in your domain, but receiving a <code>null</code> all too often indicates a programming error (not necessarily on the part of the component that produces the <code>null</code> originally), and quietly coercing it obscures this from the caller.</p>\n\n<p>The behaviour of <code>ValueObject<T></code> really needs documentating: it is completely opaque to the consumer, and will create confusion if someone extends a class that extends it. <code>Word</code> etc. should probably be <code>sealed</code>.</p>\n\n<h2>Exceptions</h2>\n\n<p>The exceptions this produces will be cryptic: \"Must be IsNullOrEmpty\". I would ditch the <code>CallerMemberName</code> stuff and just force yourself to write a clear message, or atleast change it to $\"String value violates rule {rule}\" (where the grammar won't go funky) and rename it to a <code>TextRuleViolationException</code>, or something like that: it shoudn't be used by things that aren't 'rules', because then the message would be meaningless.</p>\n\n<p>Buffering the <code>CallerMemberName</code> bit inside a <code>TextException Violated(string rule)</code> method in <code>String<T></code> would avoid misuse of this otherwise public API from outside, and save you typing <code>new</code> in each rule, which you seem to be very keep to avoid.</p>\n\n<p>There is also no provision for informing the user <em>what</em> was in violation: as it <code>first</code> or <code>last</code> that went wrong when I tried to create my name? Your code cannot adequately support the stringy constructor for <code>Name</code> (which I don't think should exist anyway) without some addition method to perform the conversion, catch the exception, and annotate it with the parameter name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T09:48:42.567",
"Id": "229689",
"ParentId": "229680",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229689",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T05:14:36.163",
"Id": "229680",
"Score": "8",
"Tags": [
"c#",
"strings",
"api"
],
"Title": "Normalize whitespace and describe string"
}
|
229680
|
<p>I am creating a user request model to pass-params for web service call</p>
<ul>
<li>toRegisterParams() is used call register web service request</li>
<li><p>toLoginParams() is used call register web service request</p></li>
<li><p>so my question is this correct way or I need to Optimise my code
or I should make different models for the same. As most-of parameters are the same. </p></li>
<li><p>for example, if I need add param in login service there are more probability to add the same in register service param. </p>
<pre><code> struct UserResquest
{
var phone: String = ""
var countryPhoneCode: String = ""
var referralCode: String = ""
var firstName : String = ""
var lastName : String = ""
var email: String = ""
var country: String = ""
var loginBy: String = CONSTANT.MANUAL
var socialUniqueID: String = ""
var password: String = ""
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
func toRegisterParams() -> [String:Any] {
var dictParam: [String:Any] = [:]
dictParam[PARAMS.PHONE] = phone
dictParam[PARAMS.COUNTRY_PHONE_CODE] = countryPhoneCode
dictParam[PARAMS.APP_VERSION] = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String)
dictParam[PARAMS.EMAIL] = email
dictParam[PARAMS.LAST_NAME] = firstName
dictParam[PARAMS.FIRST_NAME] = lastName
dictParam[PARAMS.DEVICE_TOKEN] = preferenceHelper.getDeviceToken()
dictParam[PARAMS.DEVICE_TYPE] = CONSTANT.IOS
dictParam[PARAMS.DEVICE_TIMEZONE] = TimeZone.current.identifier
dictParam[PARAMS.COUNTRY] = country
dictParam[PARAMS.LOGIN_BY] = loginBy
if loginBy != CONSTANT.MANUAL {
dictParam[PARAMS.SOCIAL_UNIQUE_ID] = socialUniqueID
dictParam[PARAMS.PASSWORD] = ""
} else {
dictParam[PARAMS.SOCIAL_UNIQUE_ID] = ""
dictParam[PARAMS.PASSWORD] = password
}
return dictParam
}
func toLoginParams() {
var dictParam: [String:Any] = [:]
dictParam[PARAMS.APP_VERSION] = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String)
dictParam[PARAMS.EMAIL] = phone
dictParam[PARAMS.COUNTRY_PHONE_CODE] = countryPhoneCode
dictParam[PARAMS.DEVICE_TIMEZONE] = TimeZone.current.identifier
dictParam[PARAMS.DEVICE_TYPE] = CONSTANT.IOS
dictParam[PARAMS.SOCIAL_UNIQUE_ID] = ""
dictParam[PARAMS.DEVICE_TOKEN] = preferenceHelper.getDeviceToken()
dictParam[PARAMS.LOGIN_BY] = CONSTANT.MANUAL
dictParam[PARAMS.PASSWORD] = password
dictParam[PARAMS.PHONE] = phone
return dictParam
}
}
</code></pre></li>
</ul>
<p>let me explain the scenario </p>
<p>in my app user can login throught phone number
- in first screen user inputs the mobile number and place submit button (which call api and check number exist or not)</p>
<ul>
<li><p>if yes then password screen will display when user enter password login api call with above params </p></li>
<li><p>If number is not registered register screen will display with entered mobile number and then user can't edit number as it verified by otp. after fill form register api call with above param.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T06:51:32.090",
"Id": "446938",
"Score": "0",
"body": "Both `toRegisterParams()` and `toLoginParams()` are described as “used call register web service request” – copy/paste error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T07:25:54.383",
"Id": "446943",
"Score": "0",
"body": "Is `dictParam[PARAMS.EMAIL] = phone` a typo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:25:30.553",
"Id": "446982",
"Score": "0",
"body": "yes, its a typo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:26:59.200",
"Id": "446983",
"Score": "0",
"body": "toRegisterParams() used to pass register params while toLoginParams() to pass login params there is no error everything work perfect, but i want to know is it correct way or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T01:59:57.487",
"Id": "447077",
"Score": "0",
"body": "Did you fill it once one-time and then call the services? When they are on different places filled then I would do 2 different structs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T04:31:16.950",
"Id": "447086",
"Score": "0",
"body": "@muescha I have updated the question with description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:07:24.630",
"Id": "447158",
"Score": "0",
"body": "then i miss a `toCheckPhoneParams` here.... if you like to reuse all in one step"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:08:26.250",
"Id": "447159",
"Score": "0",
"body": "i would extract all device infos which are the same in both calls into ohne method where you init the `dictParam` -> `var dictParam: [String:Any] = getDeviceInfo()`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T05:16:53.137",
"Id": "229681",
"Score": "1",
"Tags": [
"design-patterns",
"swift",
"ios",
"web-services",
"file-structure"
],
"Title": "Clean way of passing parameters in swift"
}
|
229681
|
<p>I have a god-class (GodClass) which work with class-adapter. Class-adapter (OldController) work with old api-class which can't to use directly cause it has bad api with low-level parameters. God-class violates SRP principle. I want to split god-class but not sure of correct way to do it. In the future, some code will change in this class. How to divide it correctly for convenient further programming?</p>
<p>I think should create some classes which has depency injection of class-adapter as singleton. (see code example). Need help. I not sure about correct way to do it.</p>
<pre><code>public class PmacDataService : BindableBase, ICNCControllerService
{
//Dependency injections
private readonly PMAC _controller = new PMAC();
private readonly IUserSettingsService _userSettings;
private readonly ILoggerFacade _logger;
private readonly IEventAggregator _aggregator;
public PmacDataService(IEventAggregator aggregator, IUserSettingsService userSettings, ILoggerFacade logger)
{
_userSettings = userSettings;
_logger = logger;
_logger.Log("Pmac loaded", Category.Debug, Priority.High);
_aggregator = aggregator;
_aggregator.GetEvent<MachineState>().Subscribe(MachineStateChanged);
RegisterEventHandlers();
}
//Machine state changing handlers
private void MachineStateChanged(int state)
{
switch (state)
{
case 0:
OnAutoStateChanged();
break;
case 1:
OnMDIStateChanged();
break;
case 2:
OnManualStateChanged();
break;
default:
break;
}
}
private void OnAutoStateChanged()
{
}
private void OnMDIStateChanged()
{
if (IsProgramRunning)
AbortProgram();
}
private void OnManualStateChanged()
{
if (IsProgramRunning)
AbortProgram();
}
//Event handlers
private void RegisterEventHandlers()
{
OnConnect += PmacDataService_OnConnect;
OnLostConnection += PmacDataService_OnLostConnection;
OnError += PmacDataService_OnError;
OnDisconnected += PmacDataService_OnDisconnected;
OnInvalidInputFormat += PmacDataService_OnInvalidInputFormat;
}
private void PmacDataService_OnInvalidInputFormat(string errorMessage)
{
_logger.Log(errorMessage, Category.Warn, Priority.High);
}
private void PmacDataService_OnDisconnected()
{
_cancToken.Cancel();
_logger.Log("Disconnected", Category.Warn, Priority.High);
_aggregator.GetEvent<ConnectionEvent>().Publish(false);
}
private void PmacDataService_OnError(long errorCode, string errorMessage)
{
_logger.Log($"Code: {errorCode}. {errorMessage}", Category.Exception, Priority.High);
}
private void PmacDataService_OnLostConnection(long errorCode)
{
_cancToken.Cancel();
_logger.Log($"Lost connection. Code {errorCode}", Category.Warn, Priority.High);
_aggregator.GetEvent<ConnectionEvent>().Publish(false);
IsReconnectionStarted = true;
}
private void PmacDataService_OnConnect()
{
_logger.Log("Connected to controller.", Category.Info, Priority.Medium);
_aggregator.GetEvent<ConnectionEvent>().Publish(true);
}
#region Poll motors function
private Task _motorCheck;
private CancellationTokenSource _cancToken = new CancellationTokenSource();
private int _motorCount;
public ConcurrentObservableCollection<IMotor> Motors { get; } = new ConcurrentObservableCollection<IMotor>();
private void DoPollMotors()
{
while (!_cancToken.IsCancellationRequested)
{
for (int i = 0; i < _motorCount; i++)
{
var motor = Motors[i];
//Statuses
if (_controller.GetMotorStatus(i, out PMAC.MotorStatusX statusesX, out PMAC.MotorStatusY statusesY))
SetMotorBits(ref motor, statusesX, statusesY);
//Current
if (_controller.GetMotorCurrent(i, out int phaseA, out int phaseB))
SetMotorCurrent(ref motor, phaseA, phaseB);
//Position
_controller.GetMotorPosition(i, out double position);
motor.Position = position;
//Letter
if (_controller.GetResponse($"#{i + 1}->", out string motorBinding))
{
string letter = string.Empty;
if (motorBinding.Where(c => char.IsLetter(c)).Count() > 0)
letter = new string(motorBinding.Where(c => char.IsLetter(c)).ToArray());
if (motor.Letter != letter)
{
motor.Letter = letter;
ActivatedMotorsCountChanged();
}
}
}
Task.Delay(_userSettings.Timeout).Wait();
}
}
private void GetMotorsCount()
{
if (_controller.I7XX0[0] > 0 && _controller.I7XX0[1] > 0) //8 моторов доступно
_motorCount = 8;
else if (_controller.I7XX0[0] > 0 && _controller.I7XX0[1] == 0)
_motorCount = 4;
Motors.Clear();
for (int i = 0; i < _motorCount; i++)
Motors.Add(new Motor());
}
private void WhenMotorCheckingTaskIsFall(Task motorChekingTask)
{
_logger.Log($"Error. Motor checking task has crashed. {motorChekingTask.Exception}", Category.Exception, Priority.High);
}
private void SetMotorCurrent(ref IMotor motor, int phaseA, int phaseB)
{
motor.PhaseA = phaseA;
motor.PhaseB = phaseB;
motor.CurrentPercentage = (double)(Math.Abs(phaseA)) / _userSettings.MaxCurrentLimit * 100; //Calculate the percentage of the current load.
}
private void SetMotorBits(ref IMotor motor, PMAC.MotorStatusX statusesX, PMAC.MotorStatusY statusesY)
{
var activatedMotorStatus = statusesX.HasFlag(PMAC.MotorStatusX.MotorActivated);
if (motor.Activated != activatedMotorStatus)
ActivatedMotorsCountChanged();
motor.Activated = activatedMotorStatus;
motor.InPosition = statusesY.HasFlag(PMAC.MotorStatusY.InPositionTrue);
motor.FatalFollowing = statusesY.HasFlag(PMAC.MotorStatusY.FatalFollowingErrorEx);
motor.WarningFollowing = statusesY.HasFlag(PMAC.MotorStatusY.WarningFollowingErrorEx);
motor.AmplifierFaultError = statusesY.HasFlag(PMAC.MotorStatusY.AmplifierFaultError);
motor.PhasingSearchError = statusesY.HasFlag(PMAC.MotorStatusY.PhasingSearchError);
motor.PhaseRequest = statusesY.HasFlag(PMAC.MotorStatusY.MotorPhaseRequest);
}
#endregion
#region Manage connection function
public bool Connected => _controller.Connected;
private bool _isReconnectionStarted;
public bool IsReconnectionStarted
{
get => _isReconnectionStarted;
private set
{
_isReconnectionStarted = value;
if (value == true)
DoReconnect();
}
}
/// <summary>
/// Try connect to controller
/// </summary>
public void Connect()
{
if (_userSettings.DeviceNumber == -1)
SelectController();
_controller.Connect(_userSettings.DeviceNumber, _userSettings.Timeout);
GetMotorsCount();
_cancToken = new CancellationTokenSource();
_motorCheck = new Task(DoPollMotors, _cancToken.Token, TaskCreationOptions.LongRunning);
_motorCheck.ContinueWith(WhenMotorCheckingTaskIsFall, TaskContinuationOptions.OnlyOnFaulted);
_motorCheck.Start();
}
private void DoReconnect()
{
for (int i = 0; i < _userSettings.ReconnectionCount; i++)
{
Task.Delay(5000).Wait();
if (!Connected)
{
_logger.Log($"Try reconnect to controller #{i + 1}", Category.Info, Priority.Medium);
Connect();
if (Connected)
{
IsReconnectionStarted = false;
break;
}
}
}
}
/// <summary>
/// Breaks the connection to the controller.
/// </summary>
public void Disconnect()
{
_cancToken.Cancel();
_cancToken = new CancellationTokenSource();
_controller.Disconnect();
}
/// <summary>
/// Invites the user to select a controller
/// </summary>
public bool SelectController(bool autoConnect = false)
{
if (!_controller.SelectController(out int deviceNumber))
return false;
_userSettings.DeviceNumber = deviceNumber;
if (autoConnect)
{
if (Connected)
Disconnect();
Connect();
}
return true;
}
#endregion
#region Get/Set variables function
/// <summary>
/// Set int variable value
/// </summary>
/// <param name="variableName">Variable name.</param>
/// <param name="value">The value for the given variable.</param>
/// <returns>The success of the operation.</returns>
public bool SetVariable(string variableName, int value)
{
if (Regex.Match(variableName, @"^[IMPimp]\d+$").Success)
{
var result = _controller.GetResponse($"{variableName}={value}", out string response);
if (result && response.Length == 0)
return true;
}
OnInvalidInputFormat($"Invalid request format when setting a variable: {variableName}");
return false;
}
/// <summary>
/// Sets a double value for the given variable.
/// </summary>
/// <param name="variableName">Variable name.</param>
/// <param name="value">The value for the given variable.</param>
/// <returns>The success of the operation.</returns>
public bool SetVariable(string variableName, double value)
{
if (Regex.Match(variableName, @"^[IMPimp]\d+$").Success)
{
var result = _controller.GetResponse($"{variableName}={value}", out string response);
if (result && response.Length == 0)
return true;
}
OnInvalidInputFormat($"Invalid request format when setting a variable: {variableName}");
return false;
}
/// <summary>
/// Reading a variable of value of type int.
/// </summary>
/// <param name="variableName">Variable name.</param>
/// <param name="result">Variable value.</param>
/// <returns>The success of the operation.</returns>
public bool GetVariable(string variableName, out int result)
{
result = -1;
bool parseSuccess = false;
if (Regex.Match(variableName, @"^[IMPimp]\d+$").Success && _controller.GetResponse($"{variableName}", out string response))
{
if (response.Contains("$"))
parseSuccess = int.TryParse(response.Trim('$'), System.Globalization.NumberStyles.HexNumber, null, out result);
else
parseSuccess = int.TryParse(response, out result);
return parseSuccess;
}
OnInvalidInputFormat($"Invalid request format when reading a variable: {variableName}");
return parseSuccess;
}
/// <summary>
/// Reading a variable of value of type double.
/// </summary>
/// <param name="variableName">Variable name.</param>
/// <param name="result">Variable value.</param>
/// <returns>The success of the operation.</returns>
public bool GetVariable(string variableName, out double result)
{
result = -1;
bool parseSuccess = false;
if (Regex.Match(variableName, @"^[IMPimp]\d+$").Success && _controller.GetResponse($"{variableName}", out string response))
{
if (response[0] == '$')
parseSuccess = (double.TryParse(response.Trim('$'), System.Globalization.NumberStyles.HexNumber, null, out result));
else if (response.Contains('.'))
parseSuccess = double.TryParse(response, out result);
return parseSuccess;
}
OnInvalidInputFormat($"Invalid request format when reading a variable: {variableName}");
return parseSuccess;
}
#endregion
#region Jog functions
public void TryJog(string axis, bool negativeDirection, int velocityFactor = 1)
{
var motors = Motors.Where(m => m.Activated && string.Compare(m.Letter, axis) == 0);
string direction = negativeDirection ? "-" : "+";
string command = "";
foreach (var motor in motors)
{
command += $"#{Motors.IndexOf(motor) + 1}J{direction} ";
RememberOldFeedrateVelocity(Motors.IndexOf(motor) + 1);
SetVariable($"I{Motors.IndexOf(motor) + 1}22", 20 * velocityFactor);
}
_controller.GetResponse(command, out _);
}
private readonly Dictionary<int, int> _oldFeedrateVelocity = new Dictionary<int, int>();
private void RememberOldFeedrateVelocity(int motorNumber)
{
GetVariable($"I{motorNumber}22", out int oldVelocity);
_oldFeedrateVelocity.Add(motorNumber, oldVelocity);
}
private void RestoreOldFeedrateVelocity()
{
foreach (var motor in _oldFeedrateVelocity)
{
SetVariable($"I{motor.Key}22", motor.Value);
}
_oldFeedrateVelocity.Clear();
}
public void StopJog()
{
_controller.GetResponse("K", out _);
RestoreOldFeedrateVelocity();
}
public void JogIncrementally(string axis, int stepLength, bool negativeDirection, int velocityFactor = 1)
{
var motors = Motors.Where(m => m.Activated && string.Compare(m.Letter, axis) == 0);
string direction = negativeDirection ? "-" : "+";
string command = "";
foreach (var motor in motors)
{
command += $"#{Motors.IndexOf(motor) + 1}J:{direction}{stepLength} ";
}
_controller.GetResponse(command, out _);
}
#endregion
# region Program load function
public bool IsProgramRunning
{
get => _isProgramRunning;
private set => SetProperty(ref _isProgramRunning, value);
}
private bool _isProgramPaused;
public bool IsProgramPaused
{
get => _isProgramPaused;
set => SetProperty(ref _isProgramPaused, value);
}
private bool _isProgramRunning;
private int _ProgramStringNumber;
public int ProgramStringNumber
{
get => _ProgramStringNumber;
private set => SetProperty(ref _ProgramStringNumber, value);
}
public int CoordinateSystemNumber { get; set; }
public int MachineType
{
get => _userSettings.MachineType;
set => _userSettings.MachineType = value;
}
private Task _rotBufLoader;
private CancellationTokenSource _rotBufCancToken = new CancellationTokenSource();
private NCFile _programFile;
private CancellationTokenSource _programStringNumberCheckerCancToken = new CancellationTokenSource();
public ConcurrentDictionary<int, string> LoadedProgram { get; } = new ConcurrentDictionary<int, string>();
public async Task<string[]> OpenProgramFile(string programPath)
{
if (_programFile != null)
_programFile.Dispose();
LoadedProgram.Clear();
return await Task.Run(() =>
{
_programFile = new NCFile(programPath, false);
return _programFile.GetSomeString(0, _programFile.StringCount > 10 ? 10 : _programFile.StringCount).Replace("\r", "").Split('\n');
}).ConfigureAwait(true);
}
private void DoRotLoad()
{
IsProgramRunning = true;
int currentString = 0;
int loadedString;
Guard.Against.Null(_programFile, nameof(_programFile));
// Initial load N number of rows
for (loadedString = 0; loadedString < 300 && loadedString < _programFile.StringCount; loadedString++)
{
string sourceString = _programFile.GetClearSomeString(loadedString, 1);
LoadedProgram.AddOrUpdate(loadedString + 1, $"N{loadedString + 1} {sourceString}", (key, val) => $"N{loadedString + 1} {sourceString}");
var tempStr = ApplyOffsets($"M920=={loadedString + 1}M921={loadedString + 1}{sourceString}", CoordinateSystemNumber, GetTCode(sourceString) ?? 0, MachineType);
_controller.RotBufSendString(tempStr, 0);
}
// Run the program
_controller.GetResponse("J/ R", out _);
// Start polling the current line number
if (_programStringNumberCheckerCancToken != null)
_programStringNumberCheckerCancToken.Cancel();
_programStringNumberCheckerCancToken = new CancellationTokenSource();
Task.Run(DoCheckProgramStringNumber, _programStringNumberCheckerCancToken.Token);
//Reload lines to buffer
while (loadedString < _programFile.StringCount)
{
GetVariable("M920", out currentString);
while ((loadedString - currentString) < 30)
{
GetVariable("M920", out currentString);
if (loadedString == _programFile.StringCount) // The program has ended
{
_programStringNumberCheckerCancToken.Cancel();
IsProgramRunning = false;
return;
}
string sourceString = _programFile.GetClearSomeString(loadedString, 1);
LoadedProgram.AddOrUpdate(loadedString + 1, $"N{loadedString + 1} {sourceString}", (key, val) => $"N{loadedString + 1} {sourceString}");
var tempStr = ApplyOffsets($"M920=={loadedString + 1}M921={loadedString + 1}{sourceString}", CoordinateSystemNumber, GetTCode(sourceString) ?? 0, MachineType);
_controller.RotBufSendString(tempStr, 0);
loadedString++;
}
// Check for the Abort command
if (_rotBufCancToken.IsCancellationRequested)
{
bool canceledOk = false;
string abortResult;
_programStringNumberCheckerCancToken.Cancel();
do
{
canceledOk = _controller.GetResponse("A K", out abortResult);
} while (!canceledOk && !string.IsNullOrEmpty(abortResult));
IsProgramRunning = false;
return;
}
Task.Delay(500).Wait();
}
// All lines are loaded, expect when all remaining lines are processed or the Abort command is called
while (currentString != loadedString)
{
GetVariable("M920", out currentString);
if (_rotBufCancToken.IsCancellationRequested)
{
bool canceledOk = false;
string abortResult;
_programStringNumberCheckerCancToken.Cancel();
do
{
canceledOk = _controller.GetResponse("A K", out abortResult);
} while (!canceledOk && !string.IsNullOrEmpty(abortResult));
break;
}
Task.Delay(500).Wait();
}
IsProgramRunning = false;
_programStringNumberCheckerCancToken.Cancel();
}
private void DoCheckProgramStringNumber()
{
while (!_programStringNumberCheckerCancToken.IsCancellationRequested)
{
GetVariable("M920", out int num);
ProgramStringNumber = num;
Task.Delay(500);
}
}
/// <summary>
/// Applies offset to the program line.
/// </summary>
/// <param name="programString">Program string.</param>
/// <param name="coordinateSystem">Number of coordinate system.</param>
/// <param name="toolNumber">Tool number</param>
/// <param name="machineType">Machine type</param>
/// <returns>Program line with recalculated coordinates.</returns>
public string ApplyOffsets(string programString, int coordinateSystem, int toolNumber, int machineType) =>
MachineOffsetCalculator.ApplyOffsets(programString, coordinateSystem, toolNumber, (MachineType)machineType, _userSettings);
public void ResetProgram()
{
_aggregator.GetEvent<ResetEvent>().Publish();
_controller.GetResponse("A K", out _);
if (IsProgramRunning)
AbortProgram();
_programFile?.Dispose();
IsProgramPaused = false;
}
public void StartProgram(int line = 0)
{
if (!_controller.Connected)
return;
if (_controller.DPRAvailable())
{
_controller.GetResponse("A", out _);
SetVariable("M920", 0);
SetVariable("M921", 0);
_controller.GetResponse("DELETE LOOKAHEAD", out _);
_controller.GetResponse("DELETE ROT", out _);
_controller.GetResponse("DELETE GATHER", out _);
_controller.RotBufRemove(0);
_controller.GetResponse("&1 DEFINE ROT 4096", out _);
_controller.GetResponse("&1 DEFINE LOOKAHEAD 500,5", out _);
_controller.RotBufClear(0);
Task.Delay(1000);
_controller.RotBufSet(true);
if (_rotBufLoader != null)
_rotBufLoader.Dispose();
if (_rotBufCancToken != null)
_rotBufCancToken.Cancel();
_rotBufCancToken = new CancellationTokenSource();
_rotBufLoader = new Task(() => DoRotLoad(), _rotBufCancToken.Token);
_rotBufLoader.ContinueWith(WhenRotaryBufferLoadingTaskIsFall, TaskContinuationOptions.OnlyOnFaulted);
_rotBufLoader.Start();
}
}
private void WhenRotaryBufferLoadingTaskIsFall(Task task)
{
_rotBufCancToken.Cancel();
_programStringNumberCheckerCancToken.Cancel();
IsProgramRunning = false;
foreach (var item in task.Exception.InnerExceptions)
{
_logger.Log($"Exception: {item.GetType().Name} Message: {item.Message}. Stack: {item.StackTrace}", Category.Exception, Priority.High);
}
}
public void AbortProgram()
{
_rotBufCancToken.Cancel();
}
public void PauseProgram()
{
var result = _controller.GetResponse("Q", out string res);
if (result)
IsProgramPaused = true;
if (!result || res.ToUpper().Contains("ERR"))
_logger.Log("Pausing error", Category.Warn, Priority.High);
}
public void ResumeProgram()
{
if (!IsProgramPaused)
return;
_controller.GetResponse("R", out _);
IsProgramPaused = false;
}
public string[] GetProgramString(int stringNumber, int count = 1)
{
return _programFile.GetSomeString(stringNumber, count).Replace("\r", "").Split('\n');
}
#endregion
#region Calculate codes function
public void GetGCodes(string programString, Dictionary<int, double?> gGroups)
{
CodeProcessor.GetGCodes(programString, gGroups);
}
public void GetMCodes(string programString, Dictionary<int, int?> mGroup)
{
CodeProcessor.GetMCodes(programString, mGroup);
}
public int GetGGroup(double gCode)
{
return CodeProcessor.GetGCodeGroup(gCode);
}
public int GetMGroup(int mCode)
{
return CodeProcessor.GetMCodeGroup(mCode);
}
public int? GetTCode(string programString)
{
return CodeProcessor.GetTCode(programString);
}
#endregion
#region Terminal client function
/// <summary>
/// Sends command to controller terminal
/// </summary>
/// <param name="query">The command to send.</param>
/// <param name="answer">The success of the operation.</param>
/// <returns></returns>
public bool TerminalResponse(string query, out string answer)
{
return _controller.GetResponse(query, out answer);
}
#endregion
#region Events
public event Action OnConnect
{
add { _controller.OnConnect += value; }
remove { _controller.OnConnect -= value; }
}
public event Action<long, string> OnError
{
add { _controller.OnError += value; }
remove { _controller.OnError -= value; }
}
public event Action OnDisconnected
{
add { _controller.OnDisconnected += value; }
remove { _controller.OnDisconnected -= value; }
}
public event Action<long> OnLostConnection
{
add { _controller.OnLostConnection += value; }
remove { _controller.OnLostConnection -= value; }
}
public event Action ActivatedMotorsCountChanged = delegate { };
public event Action<string> OnInvalidInputFormat = delegate { };
#endregion
}
</code></pre>
<p>Is this variant of refactoring correct?</p>
<p><em>It's an abstract solution.</em></p>
<pre><code>class ControllerConnectionManager : IControllerConnectionManager
{
OldController _controller;
public ControllerManager(OldController controller)
{
_controller = controller;
}
public bool Connected => _controller.Connected;
public bool IsReconnectionStarted { get; set; }
public event Action OnConnect;
public event Action OnDisconnected;
public event Action<long> OnLostConnection;
public event Action<long, string> OnError;
public void Connect();
public bool SelectController(bool autoConnect = false);
public void Disconnect();
}
class ControllerInformationService : IControllerInformation
{
OldController _controller;
public ControllerManager(OldController controller)
{
_controller = controller;
if (_controller.Connected)
Task.Run(() => StartMotorsPolling());
}
public ConcurrentObservableCollection<IMotor> Motors { get; set; }
private void StartMotorsPolling();
}
class ManualMovementManager : IManualMovementManager
{
OldController _controller;
public ManualMovementManager(OldController controller)
{
_controller = controller;
}
public void TryJog(string axis, bool negativeDirection, int velocityFactor = 1);
public void StopJog();
public void JogIncrementally(string axis, int stepLength, bool negativeDirection, int velocityFactor = 1);
public event Action<long, string> OnError;
}
class ControllerProgramManager : IControllerProgramManager
{
OldController _controller;
public ControllerProgramManager(OldController controller)
{
_controller = controller;
}
public int CoordinateSystemNumber { get; set; }
public int MachineType { get; set; }
public ConcurrentDictionary<int, string> LoadedProgram { get; set; }
public int ProgramStringNumber { get; set; }
public bool IsProgramRunned { get; set; }
public bool IsProgramPaused { get; set; }
public Task<string[]> OpenProgramFile(string programPath);
public void StartProgram(int line = 0);
public void PauseProgram();
public void ResumeProgram();
public void AbortProgram();
public void ResetProgram();
public string[] GetProgramStrings(int strNumber, int count = 1);
public event Action<long, string> OnError;
}
class CodeCalculator : ICodeCalculator
{
public static void GetGCodes(string progStr, Dictionary<int, double?> gGroups);
public static int GetGGroup(double gcode);
public static void GetMCodes(string progStr, Dictionary<int, int?> mGroup);
public static int GetMGroup(int mcode);
public static int? GetTCode(string progStr);
public event Action<long, string> OnError;
}
class ControllerTerminalManager : IControllerTerminalManager
{
OldController _controller;
public ControllerTerminalManager(OldController controller)
{
_controller = controller;
}
public bool TerminalResponse(string query, out string answer);
public event Action<string> OnInvalidInputFormat;
public event Action<long, string> OnError;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T06:20:20.770",
"Id": "446934",
"Score": "0",
"body": "@Heslacher thank you very much. I was advised at stack to transfer my question here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T07:19:47.723",
"Id": "446941",
"Score": "0",
"body": "@Heslacher ok. I added full body of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T07:21:16.090",
"Id": "446942",
"Score": "0",
"body": "Thanks.Retracted close vote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T13:15:06.790",
"Id": "446997",
"Score": "0",
"body": "It would be very helpful if you told us what the code does, what is the application? I see the word `motor` in the class, is this an automotive solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T13:45:01.490",
"Id": "447004",
"Score": "0",
"body": "@pacmaninbw no. It's a cnc machine. Universal program for laser, turning, milling machines. This class works with cnc macnines."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T06:00:00.047",
"Id": "229682",
"Score": "3",
"Tags": [
"c#",
"object-oriented"
],
"Title": "God-class which controll CNC machine"
}
|
229682
|
<p>I'm doing a code-challenge problem:</p>
<p>Captain Kaban: National Treasure is a popular football simulation game which can be played on most smartphones. In this game, you put up a team of 11 players and then compete in either story mode or multi-player mode. As you might already know, a football match is played by 11 players, which consists of one goalkeeper and ten outfield players.</p>
<p>Each outfield player's capability is measured with scores in 3 areas: Attack (dribble, shoot, pass), Defense (tackle, block, intercept), and Physical (speed, power, technique). For example, a player with A:4103 D:2837 P:3410 is a typical attacker player (forward position) as his Attack (4103) is higher than his Defense (2837) and Physical (3410). On the other hand, a player with A:1546, D:5209, P:2708 is a typical defensive player as his Defense is much higher than his Attack and Physical. A goalkeeper has a different measurement (Saving and Physical), but it's not our concern in this problem.</p>
<p>A team strength is simply the sum of all the main outfield player's capability-scores. Note that the team strength score does not consider the team's balance, e.g., a team of 10 players where each player has A:8000, D:1000, P:1000 is stronger than a team where each player has A:3000, D:3000, P:3000; the first team's team strength is 100,000 (10 * (8000 + 1000 + 1000)) while the second one is 90,000 (10 * (3000 + 3000 + 3000)).</p>
<p>Let say you are given a team with ten main outfield players and N reserve players. If you are allowed to substitute at most 1 main outfield player (with a reserve player), what is the maximum team strength you can obtain?</p>
<hr>
<h3>Input</h3>
<p>Input begins with an integer: <code>T</code> (1 ≤ <code>T</code> ≤ 20) denoting the number of cases.</p>
<p>Each case contains the following input block: Each case begins with an integer: <code>N</code> (1 ≤ <code>N</code> ≤ 10) denoting the number of reserve players. The next 10 lines each contains three integers: <code>Ai</code> <code>Di</code> <code>Pi</code> (100 ≤ <code>Ai</code>, <code>Di</code>, <code>Pi</code> ≤ 20,000) representing the Attack, Defense, and Physical score for the ith main player. The next N lines each contains three integers: <code>Aj</code> <code>Dj</code> <code>Pj</code> (100 ≤ <code>Aj</code>, <code>Dj</code>, <code>Pj</code> ≤ 20,000) representing the Attack, Defense, and Physical score for the jth reserve player.</p>
<h3>Output</h3>
<p>For each case, output in a line "Case #X: Y" where X is the case number (starts from 1) and Y is the output for the respective case.</p>
<pre><code>#include <iostream>
using namespace std;
int main () {
const int totalOriginalPlayer {10};
int testCases {};
cin >> testCases;
for (int i = 1; i <= testCases; i++) {
int reserve {}, total {}, lowest {500000}, highest {};
int attack {}, defense {}, physical {};
cin >> reserve;
int reservePlayers [reserve];
int powerReservePlayers [reserve];
int powerOriginalPlayers [totalOriginalPlayer];
// Get power of all original players, calculate sum and find the minimum
for (int i = 0; i < totalOriginalPlayer; i++) {
cin >> attack >> defense >> physical;
powerOriginalPlayers[i] = attack + defense + physical;
total += powerOriginalPlayers[i];
if (powerOriginalPlayers[i] < lowest) {
lowest = powerOriginalPlayers[i];
}
}
// Get power of all reserve players and find the maximum power
for (int j = 0; j < reserve; j++) {
cin >> attack >> defense >> physical;
powerReservePlayers[j] = attack + defense + physical;
if (powerReservePlayers[j] > highest) {
highest = powerReservePlayers[j];
}
}
// Subtract total with lowest and add highest
if (lowest < highest) {
total = total - lowest + highest;
} else if (lowest >= highest) {
total = total;
}
// Print out total
cout << "Case #" << i << ": "<< total << endl;
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Don't do <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std;</code></a>.</p></li>\n<li><p>Use an appropriate type for the range. The number of test-cases can never be negative, so we should use an unsigned integer. It looks like the player capabilities are similarly unsigned.</p></li>\n<li><p><code>for (int i = 1; i <= testCases; i++)</code> In C++, it's more usual to use <code>!=</code> for the end condition, and use the pre-increment operator (since we don't a temporary value). It's usually safer to use a zero-based index, and simply add one for printing if we need to convert to one-based: <code>for (int i = 0; i != testCases; ++i)</code>.</p></li>\n<li><p><code>int attack {}, defense {}, physical {};</code>. Declare variables (especially POD variables) as close to the point of use as possible to minimize their scope and avoid reusing them for multiple things. These should be declared in each of the innermost loops.</p></li>\n<li><p><code>reserve</code> is not a constant value, so this is not valid C++: <code>int reservePlayers [reserve];</code>, even if some compilers allow it. We should use a <code>std::vector</code> instead. (This particular array also appears to be unused!)</p></li>\n<li><p><code>for (int i = 0; i < totalOriginalPlayer; i++)</code> The loop condition variable shadows the <code>i</code> variable of the outer loop. This is likely to cause confusion. It would be better to pick a meaningful name for the loop variables, e.g. <code>outfielderIndex</code>.</p></li>\n<li><p>It might be neater to separate the logic of the program from reading the input. Then we could reuse the input reading code for both sets of players.</p>\n\n<pre><code>std::vector<std::uint32_t> outfielders = ReadPlayerData(numOutfielders);\nstd::vector<std::uint32_t> reserves = ReadPlayerData(numReserves);\nstd::uint32_t total = // ...\nstd::uint32_t worstOutfielder = // ...\nstd::uint32_t bestReserve = // ...\n\n// ... do output\n</code></pre></li>\n<li><p>We can use the standard library to do the necessary math. Specifically <code>std::accumulate</code>, <code>std::min_element</code> and <code>std::max_element</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T11:22:21.870",
"Id": "229695",
"ParentId": "229691",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T10:03:33.667",
"Id": "229691",
"Score": "1",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "Finding Minimum and Maximum Value"
}
|
229691
|
<p>This is my first rocket web-app. It serves images from a directory and thumbnails from a sub-directory. if no thumbnail is found for an existing image it is created on the fly.</p>
<p>Before I launch this thing into production/space, it would be calming to have some experts' eyes on it and be made aware of any glaring holes as well as things that would work, but can be optimized.</p>
<h2>Question</h2>
<p>In particular I am not sure what happens, if the app is run in multiple workers and multiple requests to thumbnail the same image are handled simultaneously.</p>
<p>Would I have to place locks on files and how would i do that?</p>
<h2>Code</h2>
<pre class="lang-rust prettyprint-override"><code>#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
extern crate image;
use std::fs::File;
use std::path::PathBuf;
use rocket::{Request, response::content, response::NamedFile};
use self::image::{FilterType, JPEG};
const IMAGE_DIR: &str = "images/";
pub fn resize_and_crop_to(filename: &PathBuf, cached: &PathBuf, width: u32, height: u32) -> Option<()> {
let i = image::open(filename);
match i {
Ok(img) => {
let scaled = img.resize_to_fill(width, height, FilterType::CatmullRom);
let mut output = File::create(cached).expect("Could not open cache file");
scaled.write_to(&mut output, JPEG).ok()
},
Err(_error) => None
}
}
pub fn get_filename(name: &str) -> PathBuf {
let filename: PathBuf = [ IMAGE_DIR, name ].iter().collect();
filename
}
pub fn get_cache_filename(name: &str, format: &str) -> PathBuf {
let filename = [ IMAGE_DIR, format, name ].iter().collect();
filename
}
#[get("/<image>")]
fn original(image: String) -> Option<NamedFile> {
let filename = get_filename(image.as_str());
NamedFile::open(filename.as_os_str()).ok()
}
#[get("/thumb/<image>")]
fn scaled(image: String) -> Option<NamedFile> {
let format = "thumb";
let cached = get_cache_filename(image.as_str(), format);
let f = NamedFile::open(&cached);
match f {
Ok(file) => Some(file),
Err(_error) => {
let filename = get_filename(image.as_str());
resize_and_crop_to(&filename, &cached, 280, 180)?;
NamedFile::open(cached).ok()
}
}
}
#[catch(404)]
fn not_found(request: &Request) -> content::Html<String> {
let html = format!(
"<p>{} not found</p>",
request.uri()
);
content::Html(html)
}
fn main() {
rocket::ignite()
.mount("/", routes![original, scaled])
.register(catchers![not_found])
.launch();
}
</code></pre>
<p>(I could not add tags #rocket, nor #rust-rocket for lack of reputation points)</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T14:08:53.670",
"Id": "229703",
"Score": "3",
"Tags": [
"image",
"file-system",
"rust"
],
"Title": "Caching image thumbnail web-application based on rocket"
}
|
229703
|
<p>I've written a wrapper package for redis. The idea is to be able to provide better error reporting with the package, as well as integrating stats and logging at a later stage. For now it's just better error reporting with traces.</p>
<p>My first iteration of the package looked nice and neat and rather simple. The problem came around when I wanted to write unit tests. Because of the way mocking works (or doesn't work) with implicit struct inheritance, I had to code my package differently, just so that the tests would work.</p>
<p>This is a small part of the redis extension package:</p>
<pre class="lang-golang prettyprint-override"><code>package cache
import (
"time"
"github.com/go-redis/redis"
errors "github.com/pkg/errors"
)
// StringResult - Interface for implicit inheritence for redis.StatsCMD
type StringResult interface {
Result() (string, error)
Err() error
}
// Client - Interface that we use to wrap the redis lib around, so that we can mock it's behaivour
type Client interface {
Ping() StringResult
Get(string) StringResult
}
type redisclient struct {
rc *redis.Client
}
func (c *redisclient) Ping() StringResult {
return c.rc.Ping()
}
func (c *redisclient) Get(key string) StringResult {
return c.rc.Get(key)
}
// NewCacheClient - Functiom to create a instance of RedisClient
var NewCacheClient = func(options *redis.Options) Client {
// here wrap the *redis.Client into *redisclient
return &redisclient{redis.NewClient(options)}
}
// Cache - Duplo Redis Type
type Cache struct {
redis.Options
DefaultLifetime time.Duration
client Client
}
// Connect - Connect to Reddis
func (cache *Cache) Connect() error {
cache.client = NewCacheClient(&redis.Options{
Addr: cache.Addr,
Password: cache.Password,
DB: cache.DB,
})
err := cache.checkConnection()
if err != nil {
return err
}
return nil
}
func (cache *Cache) checkConnection() error {
_, err := cache.client.Ping().Result()
if err != nil {
return errors.Wrap(err, "cache")
}
return nil
}
// Get - Get's a value from Redis. All values are returned as strings
func (cache *Cache) Get(key string) (bool, string, error) {
var val string
err := cache.checkConnection()
if err != nil {
return false, val, err
}
val, err = cache.client.Get(key).Result()
if err == redis.Nil {
// Key not found
return false, val, nil
}
if err != nil {
// Error happened
return false, val, errors.Wrap(err, "cache")
}
// Value found
return true, val, nil
}
</code></pre>
<p>Then this is my unit test for this bit of code:</p>
<pre class="lang-golang prettyprint-override"><code>package cache
import (
"errors"
"testing"
"github.com/go-redis/redis"
pkgErr "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
/**
* StringResult - Mock
*/
type StringResultMock struct {
mock.Mock
}
func (m *StringResultMock) Result() (string, error) {
args := m.Called()
return args.Get(0).(string), args.Error(1)
}
func (m *StringResultMock) Err() error {
args := m.Called()
return args.Error(0)
}
/**
* RedisClient - Mock
*/
type redisClientMock struct {
mock.Mock
}
func (m *redisClientMock) Ping() StringResult {
args := m.Called()
return args.Get(0).(StringResult)
}
func (m *redisClientMock) Get(key string) StringResult {
args := m.Called(key)
return args.Get(0).(StringResult)
}
func TestConnect(t *testing.T) {
assert := assert.New(t)
old := NewCacheClient
defer func() { NewCacheClient = old }()
tests := []struct {
testName string
statusCmdResult string
statusCmdErr error
expectedResult error
}{
{"TestConnect-Success", "success", nil, nil},
{"TestConnect-Fail", "failure", errors.New("error message"), pkgErr.Wrap(errors.New("error message"), "cache")},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
NewCacheClient = func(options *redis.Options) Client {
assert.Equal("127.0.0.1:1001", options.Addr)
assert.Equal("password", options.Password)
assert.Equal(1, options.DB)
statusCmdMock := new(StringResultMock)
statusCmdMock.On("Result").Return(tc.statusCmdResult, tc.statusCmdErr)
clientMock := new(redisClientMock)
clientMock.On("Ping").Return(statusCmdMock)
return clientMock
}
cache := Cache{}
cache.Addr = "127.0.0.1:1001"
cache.Password = "password"
cache.DB = 1
err := cache.Connect()
if tc.expectedResult != nil {
assert.Equal(tc.expectedResult.Error(), err.Error())
} else {
assert.Equal(nil, err)
}
})
}
}
func TestGet(t *testing.T) {
assert := assert.New(t)
old := NewCacheClient
defer func() { NewCacheClient = old }()
baseError := errors.New("error message")
wrappedError := pkgErr.Wrap(baseError, "cache")
keyString := "key_string"
keyValue := "key_value"
tests := []struct {
testName string
pingStatusCmdResult string
pingError error
pingErrorWrap error
getKey string
getResultValue string
getResultErr error
getResultErrWrap error
expectedResult bool
expectedValue string
}{
{"TestGet-CheckConnectFail", "failure", baseError, wrappedError, "", "", nil, nil, false, ""},
{"TestGet-NoValue", "success", nil, nil, keyString, "", redis.Nil, nil, false, ""},
{"TestGet-GetError", "success", nil, nil, keyString, "", baseError, wrappedError, false, ""},
{"TestGet-Success", "success", nil, nil, keyString, "", nil, nil, true, keyValue},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
NewCacheClient = func(options *redis.Options) Client {
assert.Equal("127.0.0.1:1001", options.Addr)
assert.Equal("password", options.Password)
assert.Equal(1, options.DB)
pingStatusCmdMock := new(StringResultMock)
if tc.pingError != nil {
pingStatusCmdMock.On("Result").Return(tc.pingStatusCmdResult, tc.pingError)
} else {
pingStatusCmdMock.On("Result").Return(tc.pingStatusCmdResult, nil)
}
clientMock := new(redisClientMock)
clientMock.On("Ping").Return(pingStatusCmdMock)
if tc.pingError == nil {
getStatusCmdMock := new(StringResultMock)
getStatusCmdMock.On("Result").Return(tc.getResultValue, tc.getResultErr)
clientMock.On("Get", tc.getKey).Return(getStatusCmdMock)
}
return clientMock
}
cache := Cache{}
cache.Addr = "127.0.0.1:1001"
cache.Password = "password"
cache.DB = 1
connErr := cache.Connect()
if tc.pingError != nil {
assert.Equal(tc.pingErrorWrap.Error(), connErr.Error())
return // If the connect fails, we don't get to the other code, so exit here
}
assert.Equal(nil, connErr)
result, value, err := cache.Get("key_string")
assert.Equal(tc.expectedResult, result)
assert.Equal(tc.getResultValue, value)
if tc.getResultErr == nil || tc.getResultErr == redis.Nil {
assert.Equal(nil, err)
} else {
assert.Equal(tc.getResultErrWrap.Error(), err.Error())
}
})
}
}
</code></pre>
<p>The package code structure is okay I guess, it could probably be better, but I think that will come in time as I work more with the language.</p>
<p>However, the test looks messy and ugly as hell. It seems to be a lot of code to test what is quite a simple function. There must be a better way to do this, or clean it up and make it simpler.</p>
<p>Is there something I'm missing? I feel like perhaps I'm coding the initial package incorrectly and maybe it's the reason I'm having to do a lot of extra work in the tests. Each test would probably look a bit cleaner if I wasn't doing table tests, but then we're looking at a lot of duplicate code for testing small differences in the function, so that's probably not the way to go.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T14:55:50.507",
"Id": "229706",
"Score": "2",
"Tags": [
"unit-testing",
"go"
],
"Title": "Tests for redis wrapper"
}
|
229706
|
<p>There are seven sorting algorithms in the code copied below. </p>
<blockquote>
<p>The first five algorithms have been previously reviewed in <a href="https://codereview.stackexchange.com/questions/229598/shell-sort-insertion-sort-bubble-sort-selection-sort-algorithms-python">this
link</a>.</p>
</blockquote>
<h3>Selection Sort</h3>
<p>The Selection Sort algorithm sorts a list by finding the element with minimum value from the right (unsorted part) of the list and putting it at the left (sorted part) of the list. </p>
<h3>Bubble Sort</h3>
<p>The Bubble Sort algorithm repeatedly swaps the adjacent elements of an input list using two for loops, if they aren't in correct order.</p>
<h3>Efficient Bubble Sort</h3>
<p>A might-be slightly efficient version of Bubble Sort algorithm is to break the outer loop, when there is no further swapping to be made, in an entire pass. For example, if the list has 10 million elements, it is possible that in the outer for loop, at pass 10,000 for instance, there would be no further swapping required to be made, if the array has been already sorted, thus the rest of the loop would become unnecessary to continue.</p>
<h3>Insertion Sort</h3>
<p>Insertion Sort algorithm builds the final sorted array in a one element at a time manner. It is less efficient on large lists than more advanced algorithms, such as Quick Sort, Heap Sort or Merge Sort, yet it provides some advantages such as implementation simplicity, efficiency for small datasets, and sorting stability.</p>
<h3>Shell Sort</h3>
<p>Shell Sort is just a variation of Insertion Sort. In Insertion Sort, when an element has to be moved far ahead, too many movements are involved, which is a drawback. In Shell Sort, we'd make the array "h-sorted" for a large value of <code>h</code> and then keep reducing the value of h (<code>sublist_increment</code>) until it'd become 1. In Shell Sort, selecting odd numbers for "h-sorting" would not be the best idea, since there'd be more overlaps, as compared to even numbers. In the following implementation, <code>sublist_increment</code> was an odd number. </p>
<h3>Efficient Shell Sort</h3>
<p>In Shell Sort, the selection of <code>h</code> values is important. For instance, <code>[9, 6, 3, 1]</code> are not proper values for <code>h</code>, since 3, 6, and 9 overlap. A list of prime numbers, such as [7, 5, 3, 1], would be much efficient for Shell Sort algorithm.</p>
<h3>Merging Two Lists into a New List</h3>
<p>In this algorithm, we would first sort two lists using one of the above in-place sorting methods, then we'd create a new list, compare the lists elements, and finally we'd place them into the new list using three simple loops:</p>
<ul>
<li>if both lists have elements to be compared </li>
<li>if list 1 has elements left to be placed in the new list </li>
<li>if list 2 has elements left to be placed in the new list </li>
</ul>
<hr>
<p>I've been trying to implement the above algorithms in Python, just for practicing, and modified them based on prior reviews (as much as I could succeed to do so), I'd appreciate it if you'd review any part of it for any other small or big changes/improvements/recommendations.</p>
<pre><code>import random
from typing import List, TypeVar
from scipy import stats
T = TypeVar('T')
def selection_sort(input_list: List[T]) -> List[T]:
"""
This method gets an integer/float list and returns
an ascendingly sorted integer/float list using Selection Sort Algorithm.
Attributes:
- In-Place Sort: Space Complexity O(1)
- Efficiency: Time Complexity => O(N^2)
- Unstable Sort: Order of duplicate elements is not preserved
Iterates through the list and swaps the min value found from the right unsorted side
of the list with the sorted elements from the left side of the list.
"""
# Is the length of the list.
length = len(input_list)
# Iterates through the list to do the swapping.
for element_index in range(length - 1):
min_index = element_index
# Iterates through the list to find the min index.
for finder_index in range(element_index + 1, length):
if input_list[min_index] > input_list[finder_index]:
min_index = finder_index
# Swaps the min value with the pointer value.
if element_index is not min_index:
_swap_elements(input_list, element_index, min_index)
return input_list
def bubble_sort(input_list: List[T]) -> List[T]:
"""
This method gets an integer/float list and returns
an ascendingly sorted integer/float list using regular Bubble Sort algorithm.
Attributes:
- In-Place Sort: Space Complexity => O(1)
- Efficiency: Time Complexity => O(N^2)
- Stable Sort (Order of equal elements does not change)
"""
length = len(input_list)
for i in range(length - 1):
for j in range(length - i - 1):
if input_list[j] > input_list[j + 1]:
_swap_elements(input_list, j, j + 1)
return input_list
def efficient_bubble_sort(input_list: List[T]) -> List[T]:
"""
This method gets an integer/float list and returns
an ascendingly sorted integer/float list
using a slightly efficient Bubble Sort algorithm.
For optimization, the Bubble Sort algorithm stops, if in a pass,
there would be no further swaps between an element of the array and the next element.
Attributes:
- In-Place Sort: Space Complexity => O(1)
- Efficiency: Time Complexity => O(N^2)
- Stable Sort (Order of equal elements does not change)
"""
# Assigns the length of to be sorted array.
length = len(input_list)
for i in range(length - 1):
number_of_swaps = 0
for j in range(length - i - 1):
if input_list[j] > input_list[j + 1]:
_swap_elements(input_list, j, j + 1)
number_of_swaps += 1
# If there is no further swaps in iteration i, the array is already sorted.
if number_of_swaps == 0:
break
return input_list
def _swap_elements(input_list: List[T], index1: int, index2: int) -> None:
"""
Swaps the adjacent elements of the input list.
"""
input_list[index1], input_list[index2] = input_list[index2], input_list[index1]
def insertion_sort(input_list: List[T]) -> List[T]:
"""
This method gets an integer/float list and returns
an ascendingly sorted integer/float list using Shell Sort algorithm.
Attributes:
- In-Place: Space Complexity O(1)
- Efficiency (Time Complexity O(N^2)
- Good if N is small
- It has too many movements
- Stable Sort (Order of duplicate elements is preserved)
"""
# Assigns the length of to be sorted array.
length = len(input_list)
# Picks the to-be-inserted element from the right side of the array, starting with index 1.
for i in range(1, length):
element_for_insertion = input_list[i]
# Iterates through the left sorted-side of the array to find
# the correct position for the element to be inserted.
j = i - 1
while j >= 0 and input_list[j] > element_for_insertion:
input_list[j + 1] = input_list[j]
j -= 1
# Inserts the element.
input_list[j + 1] = element_for_insertion
return input_list
def shell_sort(input_list: List[T], sublist_increment: int = 5) -> List[T]:
"""
This method gets an integer/float list and returns
an ascendingly sorted integer/float list using Insertion Sort algorithm.
Attributes:
- In-Place: Space Complexity O(1)
- Efficiency (Time Complexity O(N*(log N)^2 ) or O(N^1.25)
- Good if N is large
- It reduces the number of movements as compared to Insertion Sort
- Unstable Sort: Order of duplicate elements is not preserved
"""
try:
if sublist_increment // 2 == 0:
return
finally:
# Assigns the length of to be sorted array.
length = len(input_list)
while sublist_increment >= 1:
for i in range(sublist_increment, length):
element_for_insertion = input_list[i]
# Iterates through the left sorted-side of the array to find
# the correct position for the element to be inserted.
j = i - sublist_increment
while j >= 0 and input_list[j] > element_for_insertion:
input_list[j + sublist_increment] = input_list[j]
j -= sublist_increment
# Inserts the element.
input_list[j + sublist_increment] = element_for_insertion
# Narrows down the sublists by two increments.
sublist_increment -= 2
return input_list
def efficient_shell_sort(input_list: List[T]) -> List[T]:
"""
This method gets an integer/float list and returns
an ascendingly sorted integer/float list using Insertion Sort algorithm.
Here, we would use prime numbers,
somewhat distributed relative to the length of list to be sorted,
such that we'd have optimal number of sublists and movements.
Attributes:
- In-Place: Space Complexity O(1)
- Efficiency (Time Complexity O(N*(log N)^2 ) or O(N^1.25)
- Good if N is large
- It reduces the number of movements as compared to Insertion Sort
- Unstable Sort: Order of duplicate elements is not preserved
"""
# Assigns the length of to be sorted array.
length = len(input_list)
# Assigns a list of prime numbers larger than three
# as well as one, in descending order, for sublist increments of Shell Sort.
sublist_increments = prime_numbers_and_one(length)[::-1]
for sublist_increment in sublist_increments:
for i in range(sublist_increment, length):
element_for_insertion = input_list[i]
# Iterates through the left sorted-side of the array to find
# the correct position for the element to be inserted.
j = i - sublist_increment
while j >= 0 and input_list[j] > element_for_insertion:
input_list[j + sublist_increment] = input_list[j]
j -= sublist_increment
# Inserts the element.
input_list[j + sublist_increment] = element_for_insertion
return input_list
def merge_two_sorted_lists(list1: List[T], list2: List[T]) -> List[T]:
"""
This method sorts two integer/float lists first, then it'd merge them into a new list.
Attributes:
- Initial In-Place Sorting (Space Complexity O(1) = O(1) + O(1))
- Secondary Not-In-Place Sorting (Space Complexity O(N+M) = O(N) + O(M))
- Efficiency (Experimental Time Complexity O(N*(log N)^2 ) or O(N^1.25)
- Good if N is large
- It reduces the number of movements as compared to Insertion Sort
- Stable Sort: Order of duplicate elements would be preserved
"""
# Sorts both arrays using for instance Optimized Shell Sort.
efficient_shell_sort(list1)
efficient_shell_sort(list2)
# Assigns the lengths of two lists.
length1, length2 = len(list1), len(list2)
# Increments for the two lists and the third output list.
i = j = k = 0
# Creates a new list with size of lists one and two.
merged_list = [None] * (length1 + length2)
# If both lists are have elements to be inserted in the new merged array.
while i <= length1 - 1 and j <= length2 - 1:
if list1[i] < list2[j]:
merged_list[k] = list1[i]
i += 1
else:
merged_list[k] = list2[j]
j += 1
k += 1
# If list one has elements to be inserted in the new merged array,
# and list two is already done.
while i <= length1 - 1:
merged_list[k] = list1[i]
i += 1
k += 1
# If list two has elements to be inserted in the new merged array,
# and list one is already done.
while j < length2 - 1:
merged_list[k] = list1[j]
j += 1
k += 1
return merged_list
def prime_numbers_and_one(array_length: int = 5, prime_numbers=[1]) -> List[T]:
"""
This method returns a list of prime numbers larger and equal than three
in addition to one, such as:
[1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
"""
if array_length <= 1:
return prime_numbers
number = 3
while len(prime_numbers) in range(array_length):
i = 2
count_divisibles = 0
for i in range(2, number):
# If it is not a prime number:
if number % i == 0:
count_divisibles += 1
break
i += 1
# If it is a prime number:
if count_divisibles == 0:
prime_numbers.append(number)
number += 1
return prime_numbers
if __name__ == "__main__":
# Creates a dash line string and a new line for in between the tests.
delimiter = "-" * 70 + "\n"
# Generates a random integer list.
TEST_LIST_INTEGER = random.sample(range(-100, 100), 15) * 3
print(f"""The unsorted integer array is:
{TEST_LIST_INTEGER}""")
print(delimiter)
# Generates a random float list.
TEST_LIST_FLOAT = stats.uniform(0, 100).rvs(45)
print(f"""The unsorted float array is:
{TEST_LIST_FLOAT}""")
print(delimiter)
# Sample float/integer test list for input.
INTEGER_FLOAT_INPUT = list(TEST_LIST_INTEGER + TEST_LIST_FLOAT)
# Sample float/integer test list for output.
INTEGER_FLOAT_OUTPUT = sorted(INTEGER_FLOAT_INPUT)
sorting_algorithms = [
("Selection Sort", selection_sort),
("Bubble Sort", bubble_sort),
("Efficient Bubble Sort", efficient_bubble_sort),
("Insertion Sort", insertion_sort),
# Wrap shell_sort into a lambda to make it a single-argument function for testing
("Shell Sort", lambda s: shell_sort(s, 5)),
("Efficient Shell Sort", efficient_shell_sort)
]
# Testing
for description, func in sorting_algorithms:
if (func(INTEGER_FLOAT_INPUT.copy()) == INTEGER_FLOAT_OUTPUT):
print(f"{description} Test was Successful.")
else:
print(f"{description} Test was not Successful.")
print(f"""{description} (Integer):
{func(TEST_LIST_INTEGER.copy())}""")
print(f"""{description} (Float):
{func(TEST_LIST_FLOAT.copy())}""")
print(delimiter)
print(f"""Merging and sorting float and integer lists:\n
{merge_two_sorted_lists(TEST_LIST_INTEGER, TEST_LIST_FLOAT)}""")
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/229598/shell-sort-insertion-sort-bubble-sort-selection-sort-algorithms-python">Shell Sort, Insertion Sort, Bubble Sort, Selection Sort Algorithms (Python) - Code Review</a></li>
<li><a href="https://codereview.stackexchange.com/questions/229535/sorting-algorithms-python">Sorting Algorithms (Python) - Code Review</a></li>
<li><a href="https://codereview.stackexchange.com/questions/229509/selection-sort-algorithm-python">Selection Sort Algorithm (Python) - Code Review</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:22:52.630",
"Id": "447039",
"Score": "2",
"body": "Is this an update on the previous question? If so, I would state so in the question."
}
] |
[
{
"body": "<p>A few points:</p>\n\n<ul>\n<li><p>As mentioned in the previous review, the lambda expression in <code>lambda s: shell_sort(s, 5)</code> is no longer needed once the second parameter of <code>shell_sort</code> has a default value, since the function can be called by <code>shell_sort(input_list)</code> just like other functions. Therefore using <code>shell_sort</code> is sufficient.</p></li>\n<li><p>This piece of code is not correctly written.</p>\n\n<pre><code>def shell_sort(input_list: List[T], sublist_increment: int = 5) -> List[T]:\n try:\n if sublist_increment // 2 == 0:\n return\n finally:\n ...\n</code></pre>\n\n<p>It should be like this.</p>\n\n<pre><code>def shell_sort(input_list: List[T], sublist_increment: int = 5) -> List[T]:\n # `//` is floor division so this is the equivalent form.\n # I am not sure whether the logic is actually correct or not.\n # Maybe it should just be `sublist_increment < 2` instead.\n if 0 <= sublist_increment < 2:\n raise ValueError(\" ... error message ...\")\n\n ... remaining code ...\n</code></pre></li>\n<li><p>As suggested by others in the previous review, the functions modify the input in-place. So it is better not to return a list (simply omit the return statements). And it is called this way:</p>\n\n<pre><code>list_items = ...\nfunc(list_items)\n\n... list_items holds the output so it can be used directly ...\n</code></pre></li>\n<li><p>In small programs, test cases can be better organized as a list or tuple and iterated over during tests, similarly as the tested functions. It makes adding new tests cases (either manually crafted or automatically generated) easier. For larger projects one would need other tools such as <code>pytest</code>.</p>\n\n<pre><code>GENERATED_INTEGER_TEST = [random.randint(-100, 100) for _ in range(50)] # `_` represents a don't-care variable\nGENERATED_FLOAT_TEST = [random.uniform(-10, 10) for _ in range(50)]\n\ntest_cases = (\n [\"Test 1 (Normal)\", [10, 45, 20, 30, ....]],\n [\"Test 2 (Sorted list)\", [10, 20, 30]],\n [\"Test 3 (Reverse ordered list)\", [0, -10, -24, -33]],\n [\"Test 4 (Randomly generated integers)\", GENERATED_INTEGER_TEST],\n ....\n [\"Test .... (Randomly generated floats)\", GENERATED_FLOAT_TEST]\n)\n\n# Add expected output\nfor test_case in test_cases:\n test_case.append(sorted(test_case[1]))\n\n...\n\n# Actual testing\nfor func_description, func in sorting_algorithms:\n print(\"Testing\", func_description)\n for test_description, test_input, expected_output in test:\n output = test_input[:]\n func(output)\n\n message = \"passed\" if output == expected_output else \"failed\"\n print(test_description, message)\n\n ... print inputs and outputs if needed, using `test_input` and `output` ...\n</code></pre>\n\n<p>Also note that <em>test cases need to be designed to cover different kinds of inputs that go through different code branches, including edge cases that can possibly lead to bugs</em>. Here, tests on floats would succeed as long as corresponding integer tests succeed. So there is no need to repeat every test for both integer and floats. In other words, as long as the comparision operators are well-defined, the type of inputs is not a feature that can lead to different behaviour of the tested functions. You need to look for other variations instead, as shown in the sample code above. <br /><br />\nAs a side remark, the sample code also demonstrates generating random numbers using the <code>random</code> module so <code>scipy</code> is no longer needed.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T21:56:23.023",
"Id": "447302",
"Score": "1",
"body": "@Emma (1) It's fine to keep `lambda`s for calls with non-default arguments, but I think you could also add one extra test for `shell_short` with default arguments (so no `lambda` is needed); (2) if it is intended to fail for even numbers, the condition should be `if sublist_increment % 2 == 0`; (3) to remove `return`s, the functions have to be called as shown in my answer (i.e. make a copy of the test input, call function, and compare the in-place modified list with expected result). The sample code is provided exactly because I assumed that you failed to figure out how to correct it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T03:00:51.930",
"Id": "229775",
"ParentId": "229707",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229775",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:49:04.303",
"Id": "229707",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"sorting"
],
"Title": "Shell Sort, Insertion Sort, Bubble Sort, Selection Sort Algorithms"
}
|
229707
|
<p><strong>Goal:</strong> I want to output all non-standard FK constraints from clients DB, versus our "standard" DB (which contains, by default, 2,631 FK).</p>
<p><strong>Trial:</strong> I wrote this code:</p>
<pre><code>SELECT owner, table_name, constraint_name, r_owner, r_constraint_name, status
FROM all_constraints
WHERE constraint_type = 'R' -- "Referential integrity"
AND r_constraint_name IN
(
SELECT constraint_name
FROM all_constraints
WHERE constraint_type IN ('P', 'U') -- "Primary key" or "Unique"
)
AND constraint_name <> 'AB_C_COST_GRP_ID'
AND constraint_name <> 'AB_C_COST_GRP_ID'
AND constraint_name <> 'AB_C_SRC_ID'
-- ... 2,625 other such lines ...
AND constraint_name <> 'ZN_BD_ID'
AND constraint_name <> 'ZN_FR_ID'
AND constraint_name <> 'ZN_SYST_ID'
ORDER BY table_name, constraint_name;
</code></pre>
<p>... with 2,631 constraints names (= the known FK in our standard DB) which I then exclude from the listing (via the <code>WHERE</code> clause).</p>
<p><strong>NOTE --</strong> I wrote it this way, because it's above the 1,000 items constraints of an <code>IN</code> clause… Anyway, the time was equivalent… </p>
<p><strong>Results:</strong> It works well, but it takes 6 MIN to complete!</p>
<p>How to write this to get a normal performance (and eventually write the code more compactly)?</p>
<ul>
<li><p>RDBMS is Oracle, indeed better to state it clearly.</p></li>
<li><p>Why not adding a table? Because I may not have sufficient privileges to do so; I'd like the test to be totally "transparent", not intrusive, so that I can run it on any client Oracle DB.</p></li>
<li><p>Same thing regarding indexes: I don't know if that column (of that system table or view) is indexed, but I can't do anything for it. I may just have SELECT rights granted on our clients' DB.</p></li>
</ul>
<p>EXPLAIN PLAN OUTPUT:</p>
<pre><code>-----------------------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-----------------------------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 182 | 91910 | 1978 (1)| 00:00:01 |
| 1 | SORT ORDER BY | | 182 | 91910 | 1978 (1)| 00:00:01 |
|* 2 | FILTER | | | | | |
|* 3 | HASH JOIN RIGHT OUTER | | 1715 | 845K| 1977 (1)| 00:00:01 |
| 4 | INDEX FULL SCAN | I_USER2 | 130 | 520 | 1 (0)| 00:00:01 |
|* 5 | HASH JOIN | | 1715 | 839K| 1976 (1)| 00:00:01 |
| 6 | INDEX FULL SCAN | I_USER2 | 130 | 3120 | 1 (0)| 00:00:01 |
|* 7 | HASH JOIN RIGHT OUTER | | 1715 | 798K| 1975 (1)| 00:00:01 |
| 8 | TABLE ACCESS FULL | USER$ | 130 | 21710 | 4 (0)| 00:00:01 |
|* 9 | HASH JOIN | | 1715 | 519K| 1971 (1)| 00:00:01 |
| 10 | TABLE ACCESS FULL | USER$ | 130 | 21710 | 4 (0)| 00:00:01 |
|* 11 | HASH JOIN OUTER | | 1715 | 239K| 1967 (1)| 00:00:01 |
| 12 | NESTED LOOPS OUTER | | 1715 | 226K| 1886 (1)| 00:00:01 |
| 13 | NESTED LOOPS | | 93 | 12369 | 1514 (1)| 00:00:01 |
| 14 | NESTED LOOPS | | 93 | 10044 | 1421 (1)| 00:00:01 |
|* 15 | HASH JOIN | | 93 | 5766 | 1235 (1)| 00:00:01 |
|* 16 | HASH JOIN | | 435 | 17835 | 1125 (1)| 00:00:01 |
| 17 | VIEW | VW_NSO_1 | 362 | 5792 | 1088 (1)| 00:00:01 |
| 18 | HASH UNIQUE | | 362 | 110K| 1088 (1)| 00:00:01 |
|* 19 | FILTER | | | | | |
|* 20 | HASH JOIN OUTER | | 3410 | 1042K| 1087 (1)| 00:00:01 |
| 21 | JOIN FILTER CREATE | :BF0000 | 3410 | 1025K| 678 (1)| 00:00:01 |
|* 22 | HASH JOIN | | 3410 | 1025K| 678 (1)| 00:00:01 |
| 23 | INDEX FULL SCAN | I_USER2 | 130 | 3120 | 1 (0)| 00:00:01 |
|* 24 | HASH JOIN | | 3410 | 945K| 677 (1)| 00:00:01 |
| 25 | TABLE ACCESS FULL | USER$ | 130 | 21710 | 4 (0)| 00:00:01 |
|* 26 | HASH JOIN | | 3410 | 389K| 673 (1)| 00:00:01 |
|* 27 | HASH JOIN RIGHT OUTER | | 3410 | 236K| 266 (1)| 00:00:01 |
| 28 | INDEX FULL SCAN | I_USER2 | 130 | 520 | 1 (0)| 00:00:01 |
|* 29 | HASH JOIN OUTER | | 3410 | 223K| 265 (1)| 00:00:01 |
|* 30 | HASH JOIN RIGHT OUTER | | 3410 | 196K| 184 (1)| 00:00:01 |
| 31 | INDEX FULL SCAN | I_USER2 | 130 | 520 | 1 (0)| 00:00:01 |
|* 32 | HASH JOIN | | 3410 | 183K| 183 (1)| 00:00:01 |
|* 33 | HASH JOIN OUTER | | 3410 | 99K| 147 (1)| 00:00:01 |
|* 34 | TABLE ACCESS FULL | CDEF$ | 3410 | 71610 | 111 (1)| 00:00:01 |
| 35 | TABLE ACCESS FULL | CON$ | 28840 | 253K| 36 (0)| 00:00:01 |
| 36 | TABLE ACCESS FULL | CON$ | 28840 | 704K| 36 (0)| 00:00:01 |
| 37 | INDEX FAST FULL SCAN | I_OBJ1 | 96451 | 753K| 80 (0)| 00:00:01 |
|* 38 | TABLE ACCESS FULL | OBJ$ | 6797 | 305K| 408 (1)| 00:00:01 |
| 39 | VIEW | _CURRENT_EDITION_OBJ | 96115 | 469K| 409 (1)| 00:00:01 |
|* 40 | FILTER | | | | | |
| 41 | JOIN FILTER USE | :BF0000 | 96451 | 4238K| 409 (1)| 00:00:01 |
|* 42 | HASH JOIN | | 96451 | 4238K| 409 (1)| 00:00:01 |
| 43 | INDEX FULL SCAN | I_USER2 | 130 | 3120 | 1 (0)| 00:00:01 |
| 44 | TABLE ACCESS FULL | OBJ$ | 96451 | 1977K| 408 (1)| 00:00:01 |
|* 45 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 46 | NESTED LOOPS SEMI | | 1 | 29 | 3 (0)| 00:00:01 |
|* 47 | INDEX SKIP SCAN | I_USER2 | 1 | 20 | 1 (0)| 00:00:01 |
|* 48 | INDEX RANGE SCAN | I_OBJ4 | 1 | 9 | 2 (0)| 00:00:01 |
|* 49 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 50 | NESTED LOOPS SEMI | | 1 | 12 | 2 (0)| 00:00:01 |
| 51 | FIXED TABLE FULL | X$KZSRO | 2 | 6 | 0 (0)| 00:00:01 |
|* 52 | INDEX RANGE SCAN | I_OBJAUTH2 | 1 | 9 | 1 (0)| 00:00:01 |
|* 53 | FIXED TABLE FULL | X$KZSPR | 23 | 161 | 0 (0)| 00:00:01 |
|* 54 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 55 | NESTED LOOPS SEMI | | 1 | 29 | 3 (0)| 00:00:01 |
|* 56 | INDEX SKIP SCAN | I_USER2 | 1 | 20 | 1 (0)| 00:00:01 |
|* 57 | INDEX RANGE SCAN | I_OBJ4 | 1 | 9 | 2 (0)| 00:00:01 |
|* 58 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 59 | TABLE ACCESS FULL | CON$ | 28840 | 704K| 36 (0)| 00:00:01 |
|* 60 | TABLE ACCESS FULL | CDEF$ | 6191 | 126K| 110 (0)| 00:00:01 |
|* 61 | TABLE ACCESS BY INDEX ROWID BATCHED | OBJ$ | 1 | 46 | 2 (0)| 00:00:01 |
|* 62 | INDEX RANGE SCAN | I_OBJ1 | 1 | | 1 (0)| 00:00:01 |
|* 63 | TABLE ACCESS BY INDEX ROWID | CON$ | 1 | 25 | 1 (0)| 00:00:01 |
|* 64 | INDEX UNIQUE SCAN | I_CON2 | 1 | | 0 (0)| 00:00:01 |
| 65 | VIEW PUSHED PREDICATE | _CURRENT_EDITION_OBJ | 18 | 36 | 4 (0)| 00:00:01 |
|* 66 | FILTER | | | | | |
| 67 | NESTED LOOPS | | 96567 | 4243K| 4 (0)| 00:00:01 |
| 68 | TABLE ACCESS BY INDEX ROWID BATCHED| OBJ$ | 1 | 21 | 3 (0)| 00:00:01 |
|* 69 | INDEX RANGE SCAN | I_OBJ1 | 1 | | 2 (0)| 00:00:01 |
|* 70 | INDEX RANGE SCAN | I_USER2 | 96567 | 2263K| 1 (0)| 00:00:01 |
|* 71 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 72 | NESTED LOOPS SEMI | | 1 | 29 | 3 (0)| 00:00:01 |
|* 73 | INDEX SKIP SCAN | I_USER2 | 1 | 20 | 1 (0)| 00:00:01 |
|* 74 | INDEX RANGE SCAN | I_OBJ4 | 1 | 9 | 2 (0)| 00:00:01 |
|* 75 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 76 | INDEX FAST FULL SCAN | I_OBJ1 | 96451 | 753K| 80 (0)| 00:00:01 |
| 77 | NESTED LOOPS SEMI | | 1 | 12 | 2 (0)| 00:00:01 |
| 78 | FIXED TABLE FULL | X$KZSRO | 2 | 6 | 0 (0)| 00:00:01 |
|* 79 | INDEX RANGE SCAN | I_OBJAUTH2 | 1 | 9 | 1 (0)| 00:00:01 |
|* 80 | FIXED TABLE FULL | X$KZSPR | 2 | 14 | 0 (0)| 00:00:01 |
|* 81 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
| 82 | NESTED LOOPS SEMI | | 1 | 29 | 3 (0)| 00:00:01 |
|* 83 | INDEX SKIP SCAN | I_USER2 | 1 | 20 | 1 (0)| 00:00:01 |
|* 84 | INDEX RANGE SCAN | I_OBJ4 | 1 | 9 | 2 (0)| 00:00:01 |
|* 85 | TABLE ACCESS FULL | USER_EDITIONING$ | 1 | 6 | 2 (0)| 00:00:01 |
-----------------------------------------------------------------------------------------------------------------------
</code></pre>
<p><strong>SOLUTION</strong></p>
<pre><code>CREATE GLOBAL TEMPORARY TABLE std_temp_table
(
constraint_name varchar2(45)
)
ON COMMIT PRESERVE ROWS;
-- Insert.
INSERT INTO std_temp_table (constraint_name)
WITH names
AS
(
SELECT 'AB_C_COST_GRP_ID' FROM dual UNION ALL
...
SELECT 'ZN_FR_ID' FROM dual UNION ALL
SELECT 'ZN_SYST_ID' FROM dual
)
SELECT *
FROM names;
SELECT owner, table_name, constraint_name, r_owner, r_constraint_name, status
FROM all_constraints
WHERE constraint_type = 'R' -- "Referential integrity"
AND r_constraint_name IN
(
SELECT constraint_name
FROM all_constraints
WHERE constraint_type IN ('P', 'U') -- "Primary key" or "Unique"
)
AND owner NOT IN ('CTXSYS', 'MDSYS', 'SYS', 'SYSTEM', 'XDB')
AND constraint_name NOT IN (SELECT constraint_name FROM std_temp_table);
</code></pre>
<p>takes around 6.5 seconds!!</p>
<p>The other variant, with a JOIN, takes around 7 seconds:</p>
<pre><code>SELECT owner, table_name, ac.constraint_name, std_temp_table.constraint_name, r_owner, r_constraint_name, status
FROM all_constraints ac
FULL OUTER JOIN std_temp_table
ON ac.constraint_name = std_temp_table.constraint_name
WHERE constraint_type = 'R' -- "Referential integrity"
AND r_constraint_name IN
(
SELECT constraint_name
FROM all_constraints
WHERE constraint_type IN ('P', 'U') -- "Primary key" or "Unique"
)
AND owner NOT IN ('CTXSYS', 'MDSYS', 'SYS', 'SYSTEM', 'XDB')
AND std_temp_table.constraint_name IS NULL;
</code></pre>
<p>PS- Both must be equivalent, simply not run enough times. So the choice then comes down to a question of readability...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:08:54.093",
"Id": "447033",
"Score": "2",
"body": "Can you please edit your question to give some more context (e.g. what is the goal of doing this), provide schemas of your table, tell us what RDBMS you're using, and give us the output of EXPLAIN SQL, or query plan, or equivalent?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:16:03.190",
"Id": "447034",
"Score": "0",
"body": "Why not have a table with those forbidden constraint_names (with index). Also there must be an index on constraint_type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:46:08.133",
"Id": "447052",
"Score": "0",
"body": "I think that the exclusion table (like Joop mentioned), with an index on the constraint name column, is probably going to be your best bet, given what you have to work with here. Listing each exclusion constraint_name in the WHERE clause is, as you've seen, going to be slow and not reasonably maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T22:59:05.873",
"Id": "447074",
"Score": "2",
"body": "Update: I read your reason for not wanting to use a table. In SQL Server world we would be able to create a variable of \"table\" datatype right in the script, add index(es) to it, fill it with data, and then utilize that elsewhere in the script just as you would any physical table. Is something similar available in Oracle? This option would allow you to take advantage of the performance improvements without needing special schema permissions. Worth giving that a shot."
}
] |
[
{
"body": "<p>The query plan seems to be too complicated because <code>all_constraint</code> is a view and not table. So it's difficult to derive what it's doing.</p>\n\n<p>But from common sense it seems the optimal execution plan would be this:</p>\n\n<ol>\n<li>It first selects all ('P', 'U') records in the inner query</li>\n<li>For each of them finds correspondent 'R' records (with loop join)</li>\n<li>Filters and sorts what it gets after the loop</li>\n</ol>\n\n<p>Maybe it could be achieved by adding a <code>/*+ MATERIALIZE */</code> hint in the subquery, maybe additionally use qb_name+leading hints as describe <a href=\"https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:9530989800346226954\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>But a better solution would be to rewrite the query to use explicit JOIN instead of IN (see <a href=\"https://explainextended.com/2009/09/30/in-vs-join-vs-exists-oracle/\" rel=\"nofollow noreferrer\">this</a> for example. Note that even if it tells Oracle query optimizer is capable of parsing IN as JOIN, it's not the case with your query because it self-joins view and not table). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:21:06.187",
"Id": "229814",
"ParentId": "229709",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229814",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:55:53.837",
"Id": "229709",
"Score": "2",
"Tags": [
"performance",
"sql",
"oracle",
"plsql"
],
"Title": "Seek to get acceptable performance of SQL request (SOLVED)"
}
|
229709
|
<p>I have the following piece of code which is FSI tested and works.<br>
However, I want to trim it as much as possible (not only the comments, which are there for my own future reference) and make it as idiomatic as possible. </p>
<p>The gist of the code is the first step of the good ole' "Robot on a grid" kata: receive a path to a file holding strings, only some of which are valid commands. </p>
<p>Verify the path and sanitize the file, where for my needs "sanitize" means:</p>
<ul>
<li>Remove all invalid strings (i.e. not valid commands).
<ul>
<li>Valid commands are defined in the active pattern in the code.</li>
</ul></li>
<li>Remove all <em>invalid</em> placement commands, regardless of their position in the file.
<ul>
<li>Invalid in the sense that they place the robot outside the grid's bounds.</li>
</ul></li>
<li>Once a <em>valid</em> placement command was found, remove all subsequent valid placement commands while keeping the first. </li>
</ul>
<p>The <code>async</code> is there because I'm learning how to use it. It isn't material to the sanitation algorithm.</p>
<p><em>P.S.</em> By "trim" I don't mean my (some would say) verbose function names. In the days of IDEs with IntelliSense and tab-completion, that's a non-issue for me and I much prefer clarity over succinctness.</p>
<pre><code>open System.IO
open System.Text.RegularExpressions
let validatePathInsecurely filePath =
match File.Exists filePath with
// Decided to go with an exception since the path to the file is supplied to the function as a parameter, not queried from the user at runtime
// so, if the path is wrong, there is no way of fixing it in runtime, and since the application can't operate a non-existing file... BOOM!
| false -> failwith "Path specified is non existent, you don't have permissions or another error occured"
| true -> filePath
let onlyOneCorretPlaceAsync xmax ymax filePath = async {
// Tried using this code first:
// ```
// let allowedCommands =
// [ "place"; "advance"; "turn right"; "turn left" ]
// ```
// In hindsight this is wrong since the `place` command MUST also take a facing direction and X/Y coordinates (that may be any natural number).
// We'll limit it to max 999-by-999 though, for this implementation.
let (|AllowedCommands|_|) candidate =
let pattern = Regex @"(place (?:north|south|east|west) \d{3} \d{3})|(advance)|(turn right)|(turn left)"
let matches = pattern.Match candidate
if matches.Success then matches.Groups.[1].Value.Trim() |> Some else None
let onlyValidStrings filePath =
File.ReadAllLines filePath
|> Array.toList
|> List.map (fun term -> term.ToLower())
|> List.filter (fun term ->
match term with
| AllowedCommands term -> true
| _ -> false)
let sanitizeToFirstValidPlacement (content: string list) =
content |> List.skipWhile (fun elem ->
// By now we KNOW all strings in the file are valid-looking strings, however placement command might be invalid due to bounds.
// No command is valid before the robot has been placed in a valid position!
let splitElement = elem.Split()
splitElement.Length <> 4 ||
(int)(Array.item 2 splitElement) > xmax ||
(int)(Array.item 3 splitElement) > ymax)
let h::t = (onlyValidStrings filePath |> sanitizeToFirstValidPlacement)
let sanitizeRestOfList (rest: string list) =
rest
|> List.filter (fun elem ->
Array.item 0 (elem.Split()) <> "place")
let completeSanitizedList = h :: sanitizeRestOfList t
return completeSanitizedList
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T19:52:04.440",
"Id": "447061",
"Score": "0",
"body": "The `sanitizeToFirstValidPlacement` function is never used "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T03:45:06.497",
"Id": "447078",
"Score": "0",
"body": "@TheQuickBrownFox, yes, you're right, I did some refactoring prior to uploading, and didn't rename in all places. I forgot to replace the name in the `let h::t... trimToFirstValidPlacement`. I'll edit the snippet right away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T03:48:19.953",
"Id": "447079",
"Score": "1",
"body": "@Emma, sure: suppose the command file has a bunch of strings: \"hi\", \"F# world!\", \"turn right\", \"place north 1000 1000\". Now, if my grid size is 10X10, **all** those would be thrown out (the \"place\" command is out of bounds). Next, the file has \"place south 1 4\", \"turn left\", \"advance\". This is the gist of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T03:49:28.330",
"Id": "447080",
"Score": "0",
"body": "@200_success, thanks for editing the post. Your edits make it more on the point, without a shadow of a doubt!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:36:43.277",
"Id": "447136",
"Score": "0",
"body": "Could you provide a minimal use case with valid/invalid input and the expected output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T20:38:18.513",
"Id": "447393",
"Score": "0",
"body": "Hi @HenrikHansen, sorry for the late reply. An example would be (supposing a 10-by-10 board) (all the following are strings): \"Hi, place north 20 20, turn left, advance, place south 3 3, advance, turn left, place north 2 2, advance\" and the remainder of the sanitized file: \"place south 3 3, advance, turn left, advance\". All invalid stuff is removed, everything valid *before* first valid placement is removed and all valid placements *after* the first are also removed, leaving us with a valid placement and movement commands... OR nothing at all (my code is not as robust as I thought...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T13:52:32.383",
"Id": "449045",
"Score": "0",
"body": "I've tried the code with the input, you've provided in your answer to my comment, but I can't get it to work. Could you please update your question with some valid test data and show the expected output. Provide an example of the content of the input file - showing how each line is formatted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:58:46.243",
"Id": "449226",
"Score": "0",
"body": "Hi @HenrikHansen, thank you for validating my comment. As it is, I've already solved the kata, bringing my code to a size I'm content with (not a lot I managed to trim, but I'm happy with the outcome). If someone wants me to share, I'll post the GitHub link, but otherwise, I consider my question now solved. Thanks a lot for yours, and everyone else's on this thread, time and efforts!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:59:08.213",
"Id": "229710",
"Score": "2",
"Tags": [
"regex",
"file",
"validation",
"f#"
],
"Title": "Sanitize input for a \"robot on a grid\" kata"
}
|
229710
|
<blockquote>
<p>The objective of this code is to add the first 3 cells of a column
with the next 9 in another column and then to total out in 2
currencyeditor control (which is like a textbox).</p>
</blockquote>
<p>Here is a demonstration of what I am adding. </p>
<ul>
<li>For the 1st control it's going to be the actual + adjusted (left square).</li>
<li>For the 2nd control value will be the actual + original (right square).</li>
</ul>
<p><a href="https://i.stack.imgur.com/lGrk0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lGrk0.png" alt="ultragridview"></a></p>
<p>I've never added different rows of an ultragridrow before this. It works right now but doesn't look neat or professional, and I really hate the saying "at least it works" . I was just wondering if you could help me write this code neater or more efficiently?</p>
<pre class="lang-cs prettyprint-override"><code>private void doMath()
{
decimal actualsum = 0m;
decimal adjustedsum = 0m;
decimal totalsum = 0m;
for (int i = 0; i < 2; i++)
{
var row = dgvBudget.Rows[i];
actualsum += Convert.ToDecimal(row.Cells["Actual_c"].Value);
}
for (int i = 3; i < 12; i++)
{
var row = dgvBudget.Rows[i];
adjustedsum += Convert.ToDecimal(row.Cells["PrevFY"].Value);
}
totalsum = (adjustedsum + actualsum);
nbrAdjustedTotal.Value = totalsum;
adjustedsum = 0;
actualsum = 0;
totalsum = 0;
for (int i = 0; i < 2; i++)
{
var row = dgvBudget.Rows[i];
actualsum += Convert.ToDecimal(row.Cells["Actual_c"].Value);
}
for (int i = 3; i < 12; i++)
{
var row = dgvBudget.Rows[i];
adjustedsum += Convert.ToDecimal(row.Cells["BudgetAmt"].Value);
}
totalsum = (adjustedsum + actualsum);
nbrOriginalTotal.Value = totalsum;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:28:02.817",
"Id": "447050",
"Score": "2",
"body": "Is this a Winforms or WebForms app? If you have access to the data that's used to populate the gridview (CodeBehind class?), I would greatly prefer to do the sum calculations directly against that data (using LINQ, perhaps), rather than navigating through UI datagrid cells to do it. What if the order of the columns or rows changes, or the grid is tweaked to present data in a slightly different format? This could cause your logic to break or spit out incorrect results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:39:53.460",
"Id": "447051",
"Score": "0",
"body": "@DBro it's infragistics, with Epicor which is a ERP. The format remains the same as it is set on the controls. the order or columns cannot change as there is only 12 months. I suppose I could just run it against the data but it would still be iterating through a datarows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:59:00.587",
"Id": "447053",
"Score": "1",
"body": "With LINQ, you could easily and succinctly query from the data set, without having to manually loop through rows and cells."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:46:00.420",
"Id": "447147",
"Score": "1",
"body": "Not the most descriptive, but the function name made me laugh"
}
] |
[
{
"body": "<h2>Your Concerns</h2>\n\n<blockquote>\n <p><em>I was just wondering if you could help me write this code neater or more efficiently?</em></p>\n</blockquote>\n\n<h2>Efficiency</h2>\n\n<p>You are looping through the data twice. Once to calculate <code>adjustedsum</code> from <code>column[\"PrevFY\"]</code> and once for <code>column[\"BudgetAmt\"]</code>. In both cases, <code>actualsum</code> gets calculated exactly the same way. It seems you so badly wanted to reuse variables that you forgot you could have just looped through the rows and store data in multiple variables.</p>\n\n<pre><code>decimal actualsum = 0m;\ndecimal adjustedTotal = 0m;\ndecimal originalTotal = 0m;\n\nfor (int i = 0; i < 2; i++)\n{\n var row = dgvBudget.Rows[i];\n actualsum += Convert.ToDecimal(row.Cells[\"Actual_c\"].Value);\n}\n\nfor (int i = 3; i < 12; i++)\n{\n var row = dgvBudget.Rows[i];\n adjustedTotal += Convert.ToDecimal(row.Cells[\"PrevFY\"].Value);\n originalTotal += Convert.ToDecimal(row.Cells[\"BudgetAmt\"].Value);\n}\n\nnbrAdjustedTotal.Value = adjustedTotal + actualsum;\nnbrOriginalTotal.Value = originalTotal + actualsum;\n</code></pre>\n\n<hr>\n\n<h2>Compactness (neatness)</h2>\n\n<p>You have recurring decimal parsing from data cells:</p>\n\n<blockquote>\n<pre><code>Convert.ToDecimal(row.Cells[\"Actual_c\"].Value)\n</code></pre>\n</blockquote>\n\n<p>You could make a utility method for this. I'm assuming the class for the data row is called <code>Row</code>.</p>\n\n<pre><code>private static decimal ParseDecimal(Row row, string columnName)\n{\n return Convert.ToDecimal(row.Cells[columnName].Value);\n}\n</code></pre>\n\n<p>Further refactored:</p>\n\n<pre><code>decimal actualsum = 0m;\ndecimal adjustedTotal = 0m;\ndecimal originalTotal = 0m;\n\nfor (int i = 0; i < 2; i++)\n{\n var row = dgvBudget.Rows[i];\n actualsum += ParseDecimal(row, \"Actual_c\");\n}\n\nfor (int i = 3; i < 12; i++)\n{\n var row = dgvBudget.Rows[i];\n adjustedTotal += ParseDecimal(row, \"PrevFY\");\n originalTotal += ParseDecimal(row, \"BudgetAmt\");\n}\n\nnbrAdjustedTotal.Value = adjustedTotal + actualsum;\nnbrOriginalTotal.Value = originalTotal + actualsum;\n</code></pre>\n\n<h1>Proposed Result</h1>\n\n<p>We could make the code even more compact by using LINQ's <code>Skip</code>, <code>Take</code> and <code>Sum</code> extension methods. I don't have access to the code, but I'm sure you could do something like:</p>\n\n<pre><code>var rows = dgvBudget.Rows.Take(3);\nvar actualsum = rows.Select(row => ParseDecimal(row, \"Actual_c\")).Sum();\nvar rows = dgvBudget.Rows.Skip(3).Take(9);\nvar adjustedTotal = rows.Select(row => ParseDecimal(row, \"PrevFY\")).Sum();\nvar originalTotal = rows.Select(row => ParseDecimal(row, \"BudgetAmt\")).Sum();\n\nnbrAdjustedTotal.Value = adjustedTotal + actualsum;\nnbrOriginalTotal.Value = originalTotal + actualsum;\n</code></pre>\n\n<p>This does come with a slight performance penalty, since you loop the first 3 items twice (once to skip). But it comes at a good increase in readability and compactness.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:35:51.903",
"Id": "447125",
"Score": "1",
"body": "Thank you very much for the time that you used on this question. You really have taught me a few things and I appreciate it! I also love the layout you used made it really easy to read! Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:49:36.553",
"Id": "229717",
"ParentId": "229711",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229717",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T16:02:17.403",
"Id": "229711",
"Score": "2",
"Tags": [
"c#",
"performance"
],
"Title": "Getting a sum of added cells in an ultragridview"
}
|
229711
|
<p>I was recently in need of a class that checks if a computer has a valid internet connection, so I wrote one; however, I feel that there is a better way to do so and I just don't have the knowledge myself. The object I choose to wrap is the <a href="https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-networkadapter" rel="nofollow noreferrer">Win32_NeworkAdapter</a>, which unfortunately forces me to use "stringly" comparisons to determine the <code>NetconnectionID</code> (see <code>DetermineConnectionStatus</code> procedure below). </p>
<p>I am looking for suggestions on efficiency, possible caveats to what I am using currently, and anything else anyone comes up with. </p>
<p><strong>NetworkConnectionMonitor (Class):</strong></p>
<pre><code>Option Explicit
Private Const NULL_VALUE As String = "null"
Private Const WIFI_CONNECTION_ID As String = "Wi-Fi"
Private Const ETHERNET_V1_CONNECTION_ID As String = "Ethernet"
Private Const ETHERNET_V2_CONNECTION_ID As String = "Ethernet 2"
Private Const BLUETOOTH_CONNECTION_ID As String = "Bluetooth Network Connection"
Private Const LAN_CONNECTION_ID As String = "Local Area Connection"
Private Type TNetworkConnectionMonitor
HasWiFi As Boolean
HasEthernetV1 As Boolean
HasEthernetV2 As Boolean
HasBluetooth As Boolean
HasLocalAreaConnection As Boolean
ConnectedToInternet As Boolean
End Type
Private Enum NetworkConnectionStatusEnum
Disconnected
Connecting
Connected
Disconnecting
HardwareNotPresent
HardwareDisabled
HardwareMalfunction
MediaDisconnected
Authenticating
AuthenticationSucceeded
AuthenticationFailed
InvalidAddress
CredentialsRequired
End Enum
Private this As TNetworkConnectionMonitor
Public Property Get HasWiFi()
HasWiFi = this.HasWiFi
End Property
Public Property Get HasEthernetV1()
HasEthernetV1 = this.HasEthernetV1
End Property
Public Property Get HasEthernetV2()
HasEthernetV2 = this.HasEthernetV2
End Property
Public Property Get HasBluetooth()
HasBluetooth = this.HasBluetooth
End Property
Public Property Get HasLocalAreaConnection()
HasLocalAreaConnection = this.HasLocalAreaConnection
End Property
Public Property Get ConnectedToInternet()
ConnectedToInternet = this.ConnectedToInternet
End Property
Private Sub Class_Initialize()
DetermineConnectionStatus
End Sub
Private Sub DetermineConnectionStatus()
Dim WinMgmtInsrumentation As Object, WinNtwkAdapter As Object, Instance As Object
Set WinMgmtInsrumentation = GetObject("WINMGMTS:\\.\ROOT\cimv2")
Set WinNtwkAdapter = WinMgmtInsrumentation.InstancesOf("Win32_NetworkAdapter")
On Error GoTo CleanFail
For Each Instance In WinNtwkAdapter
If Instance.NetconnectionID <> NULL_VALUE Then
Select Case Instance.NetconnectionID
'conduct bit wise comparisons
Case WIFI_CONNECTION_ID
If (Instance.NetConnectionStatus And _
NetworkConnectionStatusEnum.Connected) Then this.HasWiFi = True
Case ETHERNET_V1_CONNECTION_ID
If (Instance.NetConnectionStatus And _
NetworkConnectionStatusEnum.Connected) Then this.HasEthernetV1 = True
Case ETHERNET_V2_CONNECTION_ID
If (Instance.NetConnectionStatus And _
NetworkConnectionStatusEnum.Connected) Then this.HasEthernetV2 = True
Case BLUETOOTH_CONNECTION_ID
If (Instance.NetConnectionStatus And _
NetworkConnectionStatusEnum.Connected) Then this.HasBluetooth = True
Case LAN_CONNECTION_ID
If (Instance.NetConnectionStatus And _
NetworkConnectionStatusEnum.Connected) Then this.HasLocalAreaConnection = True
End Select
End If
Next
'If None of these are true then not connected to the internet
this.ConnectedToInternet = (this.HasEthernetV2 Or this.HasWiFi Or this.HasEthernetV1)
CleanExit:
Exit Sub
CleanFail:
Resume CleanExit
End Sub
Public Function IsConnectedToHost(ByVal HostName As String, ByVal PingCount As Integer, _
Optional ByVal PingTimeOut As Long = 550)
With CreateObject("WScript.Shell")
IsConnectedToHost = (.Run("%comspec% /c ping.exe -n " & PingCount & _
" -w " & PingTimeOut & " " & HostName & _
" | find ""TTL="" > nul 2>&1", 0, True) = 0)
End With
End Function
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code>Private Sub TestConnections()
Dim NetworkStatus As NetworkConnectionMonitor
Set NetworkStatus = New NetworkConnectionMonitor
If Not NetworkStatus.ConnectedToInternet Then MsgBox "You Are not Connected to the internet"
If Not NetworkStatus.IsConnectedToHost("some.hostdomanin.com", 2) Then MsgBox "You Are not Connected to the host"
End Sub
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T16:17:37.310",
"Id": "229712",
"Score": "3",
"Tags": [
"performance",
"vba",
"networking",
"winapi",
"status-monitoring"
],
"Title": "Network connection monitor"
}
|
229712
|
<p>I have a loop to add <code>Recordset</code> items to a <code>Dictionary</code> so I can do comparisons and retrieve specific data later in the code (not shown below).</p>
<p>The first loop I tried takes around 17 seconds, the second takes 16 seconds, the third takes 15 seconds. It seems like a long wait to add 500-700 records. </p>
<p>The connection is to a SQL Server database.</p>
<pre class="lang-vb prettyprint-override"><code>'add all apps to dictionary
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set dict = New Scripting.Dictionary
Set rs = New ADODB.Recordset
rs.Open SQLStr2, cn, adOpenStatic
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer
'This takes 16 seconds - class module separate
'Source: https://codereview.stackexchange.com/questions/25956/storing-recordset-data
'Dim entity As MyEntity
'Dim entities As New Collection
'While Not rs.EOF And Not rs.BOF
'Set entity = New MyEntity
'With entity
'.Property1 = rs.Fields("app_number").value
'.Property2 = rs.Fields("FlexFstDispAmt").value
'.Property3 = rs.Fields("FlexSecDispAmt").value
'.Property4 = rs.Fields("NonFlexAmt").value
'End With
'entities.Add entity
'rs.MoveNext
'Wend
'this takes 15 seconds
Dim Key1 As String
Dim Key2 As String
Dim Key3 As String
Dim Key4 As String
With dict
For i = 1 To rs.RecordCount
Key1 = rs.Fields("app_number").value
Key2 = rs.Fields("FlexFstDispAmt").value
Key3 = rs.Fields("FlexSecDispAmt").value
Key4 = rs.Fields("NonFlexAmt").value
.Add Key1, Array(Key2, Key3, Key4)
'.Add rs.Fields("app_number").Value, Array(rs.Fields("FlexFstDispAmt").Value, rs.Fields("FlexSecDispAmt").Value, rs.Fields("NonFlexAmt").Value)
rs.MoveNext
Next
End With
'this takes 17 seconds
'With dict
'For i = 1 To rs.RecordCount
'.Add rs.Fields("app_number").value, Array(rs.Fields("FlexFstDispAmt").value, rs.Fields("FlexSecDispAmt").value, rs.Fields("NonFlexAmt").value)
'rs.MoveNext
'Next
'End With
Debug.Print Round(Timer - StartTime, 2)
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
</code></pre>
<p>I'd really like some help speeding this up. Anything is appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T16:43:25.470",
"Id": "447021",
"Score": "0",
"body": "Pretty sure the difference between the 3 approaches is statistically insignificant"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:24:54.667",
"Id": "447478",
"Score": "0",
"body": "*so I can do comparisons and retrieve specific data later* ... pretty sure you can handle such comparisons in SQL (a language to utilize relations between objects for manipulation and retrieval) without application layer looping."
}
] |
[
{
"body": "<p>It is much faster to iterate over an array then a recordset. You should also pass the recordset to a function to return the dictionary. The fewer tasks a subroutine performs the better.</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Function RecordsetMap(ByRef rs As ADODB.Recordset, ByVal KeyColumn As Long) As Scripting.Dictionary\n Dim Map As New Scripting.Dictionary\n Dim Key, Item, Values\n Rem 1000000 is used to ensure all rows are returned\n Values = rs.GetRows(1000000)\n\n Dim r As Long, c As Long\n\n For r = 0 To UBound(Values, 2)\n ReDim Item(0 To UBound(Values))\n\n For c = 0 To UBound(Values)\n Item(c) = Values(c, r)\n Next\n Key = Item(KeyColumn)\n Map.Add Key:=Key, Item:=Item\n Next\n\n Set RecordsetMap = Map\n\nEnd Function\n</code></pre>\n\n<hr>\n\n<h2>Usage</h2>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim KeyColumn As Long, n As Long\n\n' Get Field Name Index if not know\nFor n = 0 To rs.Fields.Count - 1\n If rs.Fields(n).Name = \"app_number\" Then\n KeyColumn = n\n Exit For\n End If\nNext\n\nSet dict = RecordsetMap(rs, KeyColumn)\nDim Item, Key\n\nDebug.Print \"Iterating over Keys\"\nFor Each Key In dict.Keys\n Item = dict(Key)\n Debug.Print Join(Item, \",\")\nNext\n\nDebug.Print\nDebug.Print \"Iterating over Items\"\nFor Each Item In dict.Items\n Debug.Print Join(Item, \",\")\nNext\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T21:49:30.883",
"Id": "447185",
"Score": "0",
"body": "Please forgive the lack of knowledge, but how do I place this in my code? Also, when trying to test it, `RowData` gives an undefined error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T00:20:01.520",
"Id": "447192",
"Score": "0",
"body": "I renamed `RowData ` to Item before posting. I updated the code and added example usage. Sorry that I didn't have time for a better review."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T18:00:12.320",
"Id": "229757",
"ParentId": "229713",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T16:25:35.610",
"Id": "229713",
"Score": "0",
"Tags": [
"sql",
"vba",
"excel",
"time-limit-exceeded"
],
"Title": "VBA Excel Looping through recordset and storing the data to use later"
}
|
229713
|
<p>There is a basic difference in the way C++ manages the deleter for <code>std::unique_ptr</code> and <code>std::shared_ptr</code>, mainly for allowing unique_ptr with default deleter to have the same size as a raw pointer.</p>
<p>However, the way <code>std::unique_ptr</code> manages its deleter requires stating the deleter type, in case you need a custom deleter, and also doesn't allow an easy way for setting a deleter of a different type for a declared unique_ptr (so for example you cannot manage a container of unique_ptrs with different type of deleters).</p>
<p>This leads people to use shared_ptr in cases where there is a need for different custom deleters, even if there is no actual need for shared ownership.</p>
<p>Proposing below a <code>polymorphic_deleter</code> that easily allows <code>std::unique_ptr</code> to have true polymorphic behavior for its deleter, similar to the way shared_ptr works.</p>
<p>Features of the suggested code: </p>
<ul>
<li>no change of <code>std::unique_ptr</code> is required</li>
<li>no need to declare the type of the deleter</li>
<li>can use the same <code>unique_ptr</code> with different custom deleters, the proper deleter would be called based on the runtime type</li>
<li>allows assignment of <code>unique_ptr</code> with default deleter into <code>unique_ptr</code> with <code>polymorphic_deleter</code>, i.e. <code>std::default_delete</code> is considered as a type of <code>polymorphic_deleter</code></li>
<li>the size of a <code>unique_ptr</code> with <code>polymorphic_deleter</code> is the size of a raw pointer + size of <code>std::function</code> (e.g. 40 bytes if pointer is 8 bytes and <code>std::function</code> is 32)</li>
</ul>
<h1>class <code>base_polymorphic_deleter</code> for a common base</h1>
<p>The class doesn't have a virtual destructor in purpose, as we do not delete it using a pointer to base</p>
<pre><code>class base_polymorphic_deleter {
protected:
// the deleter with type erased using std::function
std::function<void(void*)> deleter;
base_polymorphic_deleter(std::function<void(void*)>&& deleter)
: deleter { std::move(deleter) } {}
public:
auto get_deleter() {
return deleter;
}
};
</code></pre>
<h1>template class <code>polymorphic_deleter<P></code> for actual deleters</h1>
<p>Using template parameter so the type can check that the actual deleter passed to it matches the managed pointer type.</p>
<p>The code relies on the type traits code from: <a href="https://github.com/kennytm/utils/blob/master/traits.hpp" rel="nofollow noreferrer">https://github.com/kennytm/utils/blob/master/traits.hpp</a> to validate in compile time that the provided deleter matches the managed pointer type.</p>
<pre><code>template<typename P>
class polymorphic_deleter: public base_polymorphic_deleter {
// private ctor
polymorphic_deleter(std::function<void(void*)>&& deleter)
: base_polymorphic_deleter { std::move(deleter) } {}
// private validator for compile time checking arg type against pointer type
template<typename ARG,
std::enable_if_t<std::is_same<ARG, P>() || std::is_base_of<ARG, P>()>*
dummy = nullptr>
void check_arg_matching_pointer(){}
// end of private part
</code></pre>
<p>Constructors for <code>polymorphic_deleter</code>:</p>
<pre><code>public:
// empty ctor for default polymorphic_deleter
polymorphic_deleter()
: base_polymorphic_deleter {
[](void* p) {
delete static_cast<P*>(p);
}
} {}
// custom polymorphic_deleter
template<typename F>
polymorphic_deleter(F&& method)
: base_polymorphic_deleter {
[inner_deleter = std::forward<F>(method)](void* p) mutable {
inner_deleter(static_cast< ARG1<F> >(p));
}
} {
using ARG = typename std::remove_pointer< ARG1<F> >::type;
check_arg_matching_pointer<ARG>();
}
// getting another polymorphic deleter
template<typename PP>
polymorphic_deleter(polymorphic_deleter<PP>&& another)
: base_polymorphic_deleter { std::move(another.get_deleter()) } {
check_arg_matching_pointer<PP>();
}
// getting std::default_delete
template<typename PP>
polymorphic_deleter(std::default_delete<PP>&& defaultDeleter)
: base_polymorphic_deleter {
[inner_deleter = std::forward<std::default_delete<P>>(defaultDeleter)]
(void* p) mutable {
inner_deleter(static_cast<PP*>(p));
}
} {}
</code></pre>
<p>Assignment:</p>
<pre><code> template<typename PP>
polymorphic_deleter& operator=(polymorphic_deleter<PP>&& another) {
deleter = std::move(another.get_deleter());
return *this;
}
</code></pre>
<p>operator():</p>
<pre><code> void operator() (void* p) {
std::cout << "in polymorphic_deleter for address: " << p << std::endl;
std::cout << "calling the actual deleter..." << std::endl;
deleter(p);
}
};
// end of polymorphic_deleter
</code></pre>
<p>Utilities:</p>
<pre><code>template<typename T, typename... Args>
std::unique_ptr<T, polymorphic_deleter<T>>
make_unique_with_default_polymorphic_deleter(Args&&... args) {
return {
new T(std::forward<Args>(args)...),
polymorphic_deleter<T>{}
};
}
template<typename T, typename F, typename... Args>
std::unique_ptr<T, polymorphic_deleter<T>>
make_unique_with_polymorphic_deleter(F&& deleter, Args&&... args) {
return {
new T(std::forward<Args>(args)...),
polymorphic_deleter<T>{ std::forward<F>(deleter)}
};
}
template<typename T>
using unique_ptr_with_polymorphic_deleter =
std::unique_ptr<T, polymorphic_deleter<T>>;
</code></pre>
<h1>Usage Example</h1>
<pre><code>// Intuitively:
// IntegerDerived is derived from Integer
// IntegerDerivedDeleter and IntegerDeleter are their deleters
// for full code see link below
int main() {
auto pint = make_unique_with_polymorphic_deleter<Integer>(IntegerDeleter{});
pint = std::make_unique<Integer>(1);
pint = make_unique_with_default_polymorphic_deleter<IntegerDerived>(2);
pint = std::make_unique<IntegerDerived>(3);
pint = std::make_unique<Integer>(4);
pint = std::make_unique<IntegerDerived>(5);
pint = make_unique_with_default_polymorphic_deleter<Integer>(6);
}
</code></pre>
<p>Code: <a href="http://coliru.stacked-crooked.com/a/3ffc35f71ab6c432" rel="nofollow noreferrer">http://coliru.stacked-crooked.com/a/3ffc35f71ab6c432</a></p>
<p>Comments on the need of this class (alternatives?) and on the implementation would be welcomed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T09:47:42.447",
"Id": "447108",
"Score": "0",
"body": "I'm not sure whether this is correct (hence comment, not answer), but can we actively prevent deletion of `base_polymorphic_deleter` as base class by giving it a protected default deleter? (i.e. `protected: ~base_polymorphic_deleter() = default;`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T12:09:52.877",
"Id": "447119",
"Score": "1",
"body": "Do you have a use-case for those polymorphic deleters? `std::unique_ptr<T, std::function<void(T*)>>` already covers a lot of polymorphic cases and the ones it doesn't cover, like `std::unique_ptr<Base, BaseDel> p = std::unique_ptr<Derived, DerivedDel>{};` look questionable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:07:00.203",
"Id": "447139",
"Score": "0",
"body": "@nwp this is how unique_ptr works with custom deleters without the proposed code: http://coliru.stacked-crooked.com/a/7e3d158b890b8067 the deleter is not polymorphic even if it has virtual methods as can be seen in the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T18:51:05.680",
"Id": "229718",
"Score": "5",
"Tags": [
"c++",
"c++11",
"memory-management",
"pointers",
"polymorphism"
],
"Title": "Polymorphic deleter for unique_ptr"
}
|
229718
|
<p>I've written the below bash script to run as a pre-commit hook. The intention is to check the git staging area for any files larger than 1mb, and prevent the commit if any are present.</p>
<pre><code>#!/bin/sh
too_big() {
bytez=$(cat "$(git rev-parse --show-toplevel)/$1" | wc -c)
if [ "$bytez" -gt 1000000 ] ; then
cat <<EOF
Error: Attempting to commit a file larger than approximately 1mb.
Commiting large files slows jenkins builds, clones, and other operations we'd rather not slow down.
Consider generating, downloading, zipping, etc these files.
Offending file - $1
EOF
exit 1
fi
}
# If you want to allow large files to be committed set this variable to true.
allowbigfiles=$(git config --bool hooks.allowbigfiles)
# Redirect output to stderr.
exec 1>&2
if [ "$allowbigfiles" != "true" ]
then
set -e
git diff --name-only --cached $1 | while read x; do too_big $x; done
fi
</code></pre>
<p>Edit:
The final script ended up as part of a library of <a href="https://github.com/rudikershaw/client-git-hooks" rel="nofollow noreferrer">client side Git Hooks</a></p>
|
[] |
[
{
"body": "<p>Although described as a Bash script, this appears to be a portable shell script that can be run by any POSIX-conformant shell. That's a good thing, as it means we can use a much smaller, leaner shell such as Dash.</p>\n\n<p>If you haven't yet installed <code>shellcheck</code>, I recommend you do so (there's also a web version you can try). It highlights the following:</p>\n\n<ul>\n<li><p>Useless <code>cat</code> here:</p>\n\n<blockquote>\n<pre><code>bytez=$(cat \"$(git rev-parse --show-toplevel)/$1\" | wc -c)\n</code></pre>\n</blockquote>\n\n<p>That can be simplified to</p>\n\n<blockquote>\n<pre><code>bytez=$(<\"$(git rev-parse --show-toplevel)/$1\" wc -c)\n</code></pre>\n</blockquote></li>\n<li><p>Unquoted expansion of <code>$1</code> - we really wanted to write <code>\"$1\"</code> there.</p></li>\n<li>Unsafe <code>read x</code> ought to be <code>read -r x</code></li>\n<li><code>$x</code> is unquoted</li>\n</ul>\n\n<p>Piping the file into <code>wc</code> isn't an efficient way to measure size of a file; we could simply use <code>stat</code>:</p>\n\n<pre><code>bytez=$(stat -c %s \"$(git rev-parse --show-toplevel)/$1\")\n</code></pre>\n\n<p>And instead of running <code>git rev-parse</code> for every file in the changeset, run it once and remember the value in a variable.</p>\n\n<p><del>The error message should go to the standard error stream</del> (I see the whole script is redirected to <code>&2</code>)</p>\n\n<p>It's not obvious why <code>set -e</code> is right down inside the <code>if</code> - I'd normally put that immediately after the shebang.</p>\n\n<p>Consider also <code>set -u</code> to help detect a likely cause of errors.</p>\n\n<p>Spelling: unless you really mean \"1 millibit\", that should be \"1MB\".</p>\n\n<p>A suggestion that might fall into the \"too cute\" category: since <code>git config --bool</code> always produces <code>true</code> or <code>false</code> as output, we can simply execute that as a command:</p>\n\n<pre><code>if ! $(git config --bool hooks.allowbigfiles)\nthen\n</code></pre>\n\n<p>Line-based reading (i.e. <code>git diff --name-only | while read</code>) isn't totally robust; there's a <code>-z</code> option provided to produce NUL-separated output. This will require Bash, though, in order to <code>read -d</code>.</p>\n\n<hr>\n\n<h1>Improved code</h1>\n\n<pre><code>#!/bin/bash\n\nset -e\n\ntoo_big() {\n if [ \"$(stat -c %s \"$toplevel/$1\")\" -gt 1000000 ] ; then\n cat <<EOF\nError: Attempting to commit a file larger than approximately 1MB.\nCommiting large files slows jenkins builds, clones, and other\noperations we would rather not slow down.\nConsider generating, downloading, zipping, etc these files.\nOffending file - $1\nEOF\n exit 1\n fi\n}\n\n# If you want to allow large files to be committed set this variable to true.\nallowbigfiles=$(git config --bool hooks.allowbigfiles)\n\n# Redirect output to stderr.\nexec >&2\n\nif ! \"$allowbigfiles\"\nthen\n toplevel=$(git rev-parse --show-toplevel)\n git diff --name-only -z --cached \"$1\" | \n while IFS= read -d '' -r x; do too_big \"$x\"; done\nfi\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:35:36.367",
"Id": "447135",
"Score": "2",
"body": "Some people can't imagine cuteness in a shell script. I love putting commands in `if` statements. This is a fabulous twist."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T10:37:29.773",
"Id": "229745",
"ParentId": "229721",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229745",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T21:01:03.437",
"Id": "229721",
"Score": "6",
"Tags": [
"bash",
"shell",
"git"
],
"Title": "Pre-commit hook to prevent large file commits"
}
|
229721
|
<p>Let's say that I have a directory that looks like this:</p>
<pre><code>dir
| File1.txt
| fILE2.md
| file3.tex
</code></pre>
<p>When I execute my bash script from within the dir directory, I want to receive files with names "file1.txt", "file2.md" and "file3.tex".</p>
<p>I have written this script:</p>
<pre><code>ls | xargs -n1 -I {} sh -c 'fst={}; snd=`echo $fst | tr [:upper:] [:lower:]`; mv $fst $snd'
</code></pre>
<p>It works but is complex (uses variables). Is there a nicer way to perform it by piping commands? I don't want to use loops.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T05:19:21.730",
"Id": "447089",
"Score": "2",
"body": "How about: `rename 'y/A-Z/a-z/' *`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T05:26:24.290",
"Id": "447090",
"Score": "0",
"body": "Rename is not installed on the machine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T17:12:10.260",
"Id": "447508",
"Score": "1",
"body": "Well, then install `rename` on your machine. This is code review, and the best code (as expanded upon in [@Fólkvangr's answer](https://codereview.stackexchange.com/a/229821/100620)) is the code which is clear, and easy to understand & maintain. This shouldn't be a programming challenge, where you must solve a problem with one hand tied behind your back. If this machine is under external management, make a case for to host to install `rename`. If they won't, find another hosting service."
}
] |
[
{
"body": "<p>The design constraint of \"<em>repeat (some action) without loops</em>\" is nonsensical. </p>\n\n<p>Any solution that is not \"<em>type every rename command yourself</em>\" involves a loop. The loop may be hidden inside <code>xargs</code> and <code>awk</code> or <code>rename</code>; it's still there.</p>\n\n<p>Anyway, assuming the files are like you say (well-formed, no embedded whitespace, all printable characters), you can have <code>awk</code> generate a shell script and feed that to a shell:</p>\n\n<pre><code>\\ls | awk '/[A-Z]/ {print \"mv\",$1,tolower($1)}' | sh\n</code></pre>\n\n<p>If you need to deal with spaces and special characters, add quotes and use <code>$0</code> (whole line) instead of <code>$1</code> (first field):</p>\n\n<pre><code>\\ls | awk '/[A-Z]/ {printf \"mv '\\''%s'\\'\\ \\''%s'\\''\\n\",$0,tolower($0)}'\n</code></pre>\n\n<p>If the filenames contain <code>'</code> then this will fail and you need to work that out. Your code has the same problem. I won't get into the solution here because it involves a zillion backslashes and is <strong>the wrong way to solve this problem</strong>.</p>\n\n<p>The right way to solve this problem is to use a tool built for the task (<code>rename</code>) or a shell loop. And adding <code>-i</code> is a good idea, in case the new filename already exists. This will work with any filename:</p>\n\n<pre><code>for f in *[A-Z]* ; do mv -i -- \"$f\" \"${f,,}\"; done\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T06:07:14.777",
"Id": "229737",
"ParentId": "229723",
"Score": "5"
}
},
{
"body": "<p>Based on the answers provided by @Oh My Goodness and @AJNeufeld, I would say that you should use <code>rename</code>.</p>\n\n<p>The most important issue is that your script is difficult to understand or hard to read. I recommend you read the chapter \"<a href=\"http://www.gnu.org/software/coreutils/manual/html_node/Opening-the-software-toolbox.html#Opening-the-software-toolbox\" rel=\"nofollow noreferrer\">Opening the Software Toolbox</a>\" which exposes the right approach to use the shell.</p>\n\n<blockquote>\n <p>(An important additional point was that, if necessary, take a detour and build any software tools you may need first, if you don’t already have something appropriate in the toolbox.)</p>\n</blockquote>\n\n<p>The best way to rename your filenames is to use <code>rename</code> because it is the right tool and the resulting command invocation is easy to read. </p>\n\n<pre><code>rename 'y/A-Z/a-z/' *\n</code></pre>\n\n<p>Note that the following command redirects the standard error of the command to a temporary file which has a \"random\" name. Therefore, you may know which files were not renamed. It may be useful if the information send to the standard error cannot be viewed on the screen (e.g. too much information displayed).</p>\n\n<pre><code>fn=$(mktemp -u); rename 'y/A-Z/a-z/' * 2>\"$fn\" && less -FX \"$fn\"\n</code></pre>\n\n<p>Eventually, you may test the command invocation before renaming files.</p>\n\n<pre><code>rename -n 'y/A-Z/a-z/' * >/dev/null\n</code></pre>\n\n<p>In conclusion, if you have the wrong tools you will do a bad job.</p>\n\n<p>See also: <a href=\"https://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow noreferrer\">Why you shouldn't parse the output of ls</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T21:09:14.063",
"Id": "229821",
"ParentId": "229723",
"Score": "3"
}
},
{
"body": "<p>A shell script intended to be run as a command (i.e. not sourced into a running shell) should always have a shebang to specify the interpreter it should be run with. For <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged 'bash'\" rel=\"tag\">bash</a>, that would normally be</p>\n\n<pre><code>#!/bin/bash\n</code></pre>\n\n<p>That said, the script presented appears to be portable shell, so <code>#!/bin/sh</code> would be more appropriate as it stands.</p>\n\n<p>There's no need for such long lines. A simple reformat gives a slightly more readable version:</p>\n\n<pre><code>#!/bin/sh\n\nls |\n xargs -n1 -I {} \\\n sh -c 'fst={}; snd=`echo $fst | tr [:upper:] [:lower:]`; mv $fst $snd'\n</code></pre>\n\n<p>If we use Bash for the command, then we can use a downcasing expansion (<code>${var,,}</code>) instead of the cumbersome <code>tr</code> command:</p>\n\n<pre><code>#!/bin/sh\n\nls |\n xargs -n1 -I {} \\\n bash -c 'fst={}; snd=${fst,,}; mv $fst $snd'\n</code></pre>\n\n<p>The output of <code>ls</code> isn't suitable for parsing. If we can assume GNU <code>ls</code>, then we could use <code>--quoting-style</code> to escape the names for reading by a shell:</p>\n\n<pre><code>#!/bin/sh\n\nls --quoting-style=shell-escape |\n xargs -n1 -I {} \\\n bash -c 'fst={}; mv $fst ${fst,,}'\n</code></pre>\n\n<p>When we have names which differ only in case, do we really want the second to overwrite the first? I would suggest using <code>mv -n</code> to avoid overwriting existing files. Sadly this won't give any diagnostic that the file wasn't moved, though.</p>\n\n<p>All this said, a simple <code>for</code> loop is a much simpler alternative:</p>\n\n<pre><code>#!/bin/bash\n\nset -eu\n\nfor i in *\ndo mv -n -- \"$i\" \"${i,,}\"\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T11:01:09.547",
"Id": "229906",
"ParentId": "229723",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T21:36:09.380",
"Id": "229723",
"Score": "2",
"Tags": [
"bash",
"shell"
],
"Title": "Non-recursively replace all uppercase letters in files within current directory with lowercase letters - without looping"
}
|
229723
|
<p>I submitted a technical assignment for a job interview process and I am stressing out wondering if my submission was any good. I would like to learn and be a better developer, so please give me pointers about what I could improve on.</p>
<p><a href="https://github.com/Javed-Ali/ParsetheParcel/tree/0455d582769c5da795202816d61f42350676b2da" rel="nofollow noreferrer">GitHub link</a></p>
<pre><code>using System;
namespace ParsetheParcel
{
interface ICalculatable<Parcel>
{
string Calculator(Parcel p);
}
public class Parcel
{
//(fun fact, store currency as decimal and not float/double)
public const decimal CostSmall = 5M;
public const decimal CostMedium = 7.5M;
public const decimal CostLarge = 8.5M;
//Uppser limit placed on the weight
public const double PackageWeight = 25;
public double Weight { get; set; }
public double Length { get; set; }
public double Height { get; set; }
public double Breadth { get; set; }
public enum SizeSmall
{
length = 200,
breadth = 300,
height = 150,
}
public enum SizeMedium
{
length = 300,
breadth = 400,
height = 200,
}
public enum SizeLarge
{
length = 400,
breadth = 600,
height = 250
}
}
class Program : ICalculatable<Parcel>
{
static void Main(string[] args)
{
//show welcome message
Console.WriteLine("Kia ora, welcome to the trademe parcel calculator!\n");
//start asking for inputs
//ask for dimensions
Console.WriteLine("Please enter the dimensions of your parcel and the unit (mm, cm or m) when promted:\n");
Console.Write("Enter your dimensions for length: ");
string length = GetInput();
Console.Write("\nEnter your dimensions for breadth: ");
string breadth = GetInput();
Console.Write("\nEnter your dimensions for height: ");
string height = GetInput();
Console.Write("\nEnter the unit used for length, breadth and height (valid inputs: mm or cm or m): ");
string dimenunit = GetUnitDimen();
//ask for weight
Console.WriteLine("\n Please Enter the weight of your parcel and the unit (g, kg) when promted: \n");
Console.Write("Enter your weight: ");
string weight = GetInput();
Console.Write("\nEnter the unit used for used for weight (valid inputs: kg or g): ");
string weightunit = GetUnitWeight();
Parcel myparcel = Converter(length, breadth, height, dimenunit, weight, weightunit);
Program p = new Program();
Console.WriteLine("\n"+p.Calculator(myparcel));
//make sure the console doesnt shutdown prematurely
Console.WriteLine("\nPress Return key (enter) to Exit");
Console.Read();
}
/* Function determines if what package type appropriate for the parcel*/
public string Calculator(Parcel parcel)
{
//check if package meets minimum 25kg limit first
if (parcel.Weight <= Parcel.PackageWeight)
{
//check if package is bigger than largest available first so it doesnt have to check through the other ifs
if (parcel.Length > (double)Parcel.SizeLarge.length ||
parcel.Breadth > (double)Parcel.SizeLarge.breadth || parcel.Height > (double)Parcel.SizeLarge.height)
{
return "Sorry your Parcel is too large for us to ship!" +
"\nOur Largest Package: " + (double)Parcel.SizeLarge.length + "mm x" + (double)Parcel.SizeLarge.breadth + "mm x" + (double)Parcel.SizeLarge.height + "mm" +
"\nYour Dimensions:" + parcel.Length + "mm x" + parcel.Breadth + "mm x" + parcel.Height + "mm";
}
//check if package can fit in smallest first
if (parcel.Length <= (double)Parcel.SizeSmall.length &&
parcel.Breadth <= (double)Parcel.SizeSmall.breadth && parcel.Height <= (double)Parcel.SizeSmall.height)
{
return "Your Parcel can fit in our small package type! The cost would be: " + Parcel.CostSmall.ToString("C");
}
else if (parcel.Length <= (double)Parcel.SizeMedium.length &&
parcel.Breadth <= (double)Parcel.SizeMedium.breadth && parcel.Height <= (double)Parcel.SizeMedium.height)
{
return "Your Parcel can fit in our Medium package type! The cost would be: " + Parcel.CostMedium.ToString("C");
}
else
{
/*we already know the parcel is not greater than the largest availbe and we know that it wont fit in small or medium*/
return "Your Parcel can fit in our Large package type! The cost would be: " + Parcel.CostLarge.ToString("C");
}
}
else //parcel too heavy
{
return "Sorry your Parcel is too heavy for us to ship! Our Limit: " + Parcel.PackageWeight + " Your Parcel Weight: " + parcel.Weight;
}
}
/* Gets dimensions and weight values from the user*/
private static string GetInput()
{
string Value; double result;
do
{
Value = Console.ReadLine();
if (!string.IsNullOrEmpty(Value) && double.TryParse(Value, out result))
{
return Value;
}
else
{
Console.WriteLine("Empty or incorrect input, please try again by entering a number only");
}
} while (string.IsNullOrEmpty(Value) || !double.TryParse(Value, out result));
return Value;
}
/* Gets the unit input for the dimensions (mm, cm, m) */
private static string GetUnitDimen()
{
string Value;
do
{
Value = Console.ReadLine();
if (!string.IsNullOrEmpty(Value) && Value.Equals("m", StringComparison.OrdinalIgnoreCase)
|| Value.Equals("mm", StringComparison.OrdinalIgnoreCase)
|| Value.Equals("cm", StringComparison.OrdinalIgnoreCase))
{
return Value;
}
else
{
Console.WriteLine("Empty or incorrect input, please try again");
}
} while (string.IsNullOrEmpty(Value) && !Value.Equals("m", StringComparison.OrdinalIgnoreCase)
|| !Value.Equals("mm", StringComparison.OrdinalIgnoreCase)
|| !Value.Equals("cm", StringComparison.OrdinalIgnoreCase));
return Value;
}
/* Gets the unit input for the weight (kg, g) */
private static string GetUnitWeight()
{
string Value;
do
{
Value = Console.ReadLine();
if (!string.IsNullOrEmpty(Value) && Value.Equals("kg", StringComparison.OrdinalIgnoreCase)
|| Value.Equals("g", StringComparison.OrdinalIgnoreCase))
{
return Value;
}
else
{
Console.WriteLine("Empty or incorrect input, please try again");
}
} while (string.IsNullOrEmpty(Value) && !Value.Equals("kg", StringComparison.OrdinalIgnoreCase)
|| !Value.Equals("g", StringComparison.OrdinalIgnoreCase));
return Value;
}
/*convert dimensions to mm if it isnt already and convert weight to kg if it isnt already */
private static Parcel Converter(string length, string breadth, string height, string dimenunit, string weight, string weightunit)
{
double result;
double[] parcel = new double[4];
if (double.TryParse(length, out result))//this should always pass as we have sanitized it in getInput Function
{
parcel[0] = result; //length
}
if (double.TryParse(breadth, out result))//this should always pass as we have sanitized it in getInput Function
{
parcel[1] = result; //breadth
}
if (double.TryParse(height, out result))//this should always pass as we have sanitized it in getInput Function
{
parcel[2] = result; //height
}
if (double.TryParse(weight, out result))//this should always pass as we have sanitized it in getInput Function
{
parcel[3] = result; //weight
}
//check units and convert to mm and kg if needed
if (dimenunit.Equals("m", StringComparison.OrdinalIgnoreCase))
{
//convert m to mm for comparision
parcel[0] = parcel[0] * 1000; //length convert to mm
parcel[1] = parcel[1] * 1000; //breadth convert to mm
parcel[2] = parcel[2] * 1000; //height convert to mm
}
else if (dimenunit.Equals("cm", StringComparison.OrdinalIgnoreCase))
{
//convert cm to mm for comparision
parcel[0] = parcel[0] * 10; //length convert to mm
parcel[1] = parcel[1] * 10; //breadth convert to mm
parcel[2] = parcel[2] * 10; //height convert to mm
}
if (weightunit.Equals("g", StringComparison.OrdinalIgnoreCase))
{
//convert gram to kg for comprasion
parcel[3] = parcel[3] / 1000;
}
Parcel p = new Parcel()
{
Length = parcel[0],
Breadth = parcel[1],
Height = parcel[2],
Weight = parcel[3]
};
return p;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T17:16:36.550",
"Id": "447985",
"Score": "2",
"body": "I'm voting to close this question because it lacks any description about the task you had to solve in your assignment and also any explanation of your solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T18:19:32.747",
"Id": "447988",
"Score": "2",
"body": "Hey Javed, you should explain in more details what your code is supposed to do, otherwise it's very hard to review it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:14:55.023",
"Id": "448013",
"Score": "0",
"body": "@t3chb0t okay..."
}
] |
[
{
"body": "<h2>Usability</h2>\n\n<p>Your design is pretty string-heavy. If you want to build reusable functions, you should try to avoid this and work with more appropriate types given the context.</p>\n\n<p>One such example is your interface design:</p>\n\n<blockquote>\n<pre><code>interface ICalculatable<Parcel>\n{\n string Calculator(Parcel p);\n}\n</code></pre>\n</blockquote>\n\n<p>What can consumers do with the returned string? This interface can only be used to render results to a UI like the console. Consider returning a <code>decimal</code> or a response class that stores all the required data for consumers to act upon.</p>\n\n<blockquote>\n<pre><code>return \"Your Parcel can fit in our small package type! The cost would be: \" + Parcel.CostSmall.ToString(\"C\");\n</code></pre>\n</blockquote>\n\n<p>could be:</p>\n\n<pre><code>return Parsel.CostSmall;\n</code></pre>\n\n<p>Another example of returning the wrong type is <code>GetInput</code>. Internally you parse the data to <code>double</code> only to return the raw string. This seems a bit nuts to me.</p>\n\n<blockquote>\n<pre><code> string Value; double result;\n // ..\n if (!string.IsNullOrEmpty(Value) && double.TryParse(Value, out result))\n {\n return Value; // should return result instead\n }\n // ..\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h2>Design</h2>\n\n<h3><code>ICalculatable<Parcel></code></h3>\n\n<blockquote>\n<pre><code>interface ICalculatable<Parcel>\n{\n string Calculator(Parcel p);\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Start by defining proper names. The interface is used to calculate the cost price of a <code>Parcel</code>. The interface is hence a <code>ICalculator</code>, not <code>ICalculatable</code>. The parcel would be the latter. </li>\n<li>The name of the operation should be a verb specifying the action. <code>CalculateCostPrice</code> is a verb and is more specific than the generic <code>Calculator</code>.</li>\n<li>If using generics, use a type <code>T</code> both as generic class type and input parameter for the method. But since this interface is specific to calculating the cost price, I would not use a generic class, unless you define an interface for types that have a cost price. This would be an exercise left for you to explore.</li>\n<li>As already discussed, return a more useful return type. Let's assume all you want is the cost price, so a <code>decimal</code> would do.</li>\n</ul>\n\n\n\n<pre><code>/// <summary>\n/// Performs calculations on Parcel instances.\n/// </summary>\ninterface ICalculator\n{ \n /// <summary> Calculates the cost price of a Parcel in <unit>. </summary>\n decimal CalculateCostPrice(Parcel parcel);\n}\n</code></pre>\n\n<h3>General</h3>\n\n<ul>\n<li>Consider making <code>Parcel</code> immutable. This ensures better encapsulation of its state.</li>\n<li>Enum names should be PascalCased, not camelCased.</li>\n<li>Don't let the entrypoint <code>Program</code> implement an interface. Create a specific <code>ParcelCalculator</code> class.</li>\n<li>Make sure to split API logic from end-user rendering. The string-based API is an anti-pattern for usability and reusability.</li>\n<li>I like the fact you put all user input parsing in <code>Program</code>, not in the API.</li>\n</ul>\n\n<hr>\n\n<h2>Conclusion</h2>\n\n<ul>\n<li>I would focus on making a good design, think good about the arguments, return types and names of interfaces and methods. And don't forget to document interfaces to provide a clear <strong>Specification</strong> for consumers that focuses on <strong>Usability</strong>.</li>\n<li>Don't let rendering pollute the API. Remove all string-based messages from the API and put them in the presentation layer. This is called <strong>Separation of Concerns</strong>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:26:59.170",
"Id": "447400",
"Score": "1",
"body": "Thank you very much for your input! They were very insightful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T04:47:53.227",
"Id": "229734",
"ParentId": "229728",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code> public enum SizeSmall\n {\n length = 200,\n breadth = 300,\n height = 150,\n }\n public enum SizeMedium\n {\n length = 300,\n breadth = 400,\n height = 200,\n }\n public enum SizeLarge\n {\n length = 400,\n breadth = 600,\n height = 250\n }\n</code></pre>\n</blockquote>\n\n<p>Your use of the <code>enum</code> type is a little unusual. Normally an <code>enum</code> represents discrete values of the same kind, but yours each describes a parcel definition. A more \"correct\" way to define your dimension limits by <code>enum</code> types could be:</p>\n\n<pre><code>public enum Lengths \n{\n Small = 200,\n Medium = 300,\n Large = 400\n}\n\npublic enum Breadths\n{\n Small = 300,\n Medium = 400,\n Large = 200\n}\n\npublic enum Heights \n{\n Small = 150,\n Medium = 200,\n Large = 250\n}\n</code></pre>\n\n<hr>\n\n<p>You don't tell if the input dialog was given by the assignment, but anyway I find it a little laborious, not least because the user has to determine which side of the parcel is the length, the breadth and the height. Normally I would take the longest dimension for the length, but your lengths are actually shorter than the breadths? </p>\n\n<p>Therefore I would help the user by letting him/her enter the dimensions more or less arbitrarily at one single prompt:</p>\n\n<p>Start by letting the user enter units (it is counter intuitive that the units is entered after the values):</p>\n\n<pre><code>Console.Write(\"Enter units to use [m, cm, mm]: \");\n</code></pre>\n\n<p>Then the input with the max values as guidance: </p>\n\n<pre><code>Console.Write(\"Enter the size (L, B, H) (max: 400 x 200 x 250 mm) \");\n</code></pre>\n\n<p>Then when done, it's your programs job to first parse the input and then determine the right parcel by comparing the input with the parcel dimensions and maybe exchange the values for length and breadth if necessary etc.</p>\n\n<hr>\n\n<p>Another thing that I would be frustrated about if I had to use your program, is that it evaluates the input as the last thing before it gives me the answer. A more user friendly approach would be to evaluate each input when it is entered - and letting the user enter a new value until a valid one is entered or until a an \"exit program\" token is specified.</p>\n\n<hr>\n\n<p>You are very polite and descriptive in dialogue with the user, which is normally fine in human to human interaction (and maybe AI to human interaction) but in a plain calculation dialogue no one expects a detailed conversation so make it shorter and more precise. If needed you can provide a help function for each prompt or something like that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:27:42.530",
"Id": "447401",
"Score": "1",
"body": "Thank you so much for your input Henrik!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:51:27.083",
"Id": "229752",
"ParentId": "229728",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229734",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T00:55:34.907",
"Id": "229728",
"Score": "3",
"Tags": [
"c#",
".net",
"interview-questions",
"console",
"interface"
],
"Title": "Parcel size classifier"
}
|
229728
|
<p>I run into issues where I forget to run UI changes on the main thread. </p>
<p>I've just fixed an issue for loading and unloading an activity indicator and fixed it with the following code:</p>
<pre><code>if active {
DispatchQueue.main.async {
UIApplication.shared.keyWindow?.startIndicatingActivity()
}
} else {
DispatchQueue.main.async {
UIApplication.shared.keyWindow?.stopIndicatingActivity()
}
}
</code></pre>
<p>Now an alternative is this code:</p>
<pre><code>DispatchQueue.main.async {
if active { UIApplication.shared.keyWindow?.startIndicatingActivity()
} else { UIApplication.shared.keyWindow?.stopIndicatingActivity()
}
}
</code></pre>
<p>Now which one is right / more maintainable for the future?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T06:59:35.487",
"Id": "447095",
"Score": "0",
"body": "Where do the `start/stopIndicatingActivity` methods come from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T00:55:00.367",
"Id": "447193",
"Score": "0",
"body": "Given how little processing each takes to execute, I'd say it doesn't matter. Whichever way makes you happy."
}
] |
[
{
"body": "<p>If you want to do more things in the main thread when <code>active</code> is <code>true</code> or when it is <code>false</code>, then the first version would be recommendable. </p>\n\n<p>Bear in mind that checking for <code>active</code> being <code>true</code> or <code>false</code> is done <em>quicker</em> in the first version since it's made on the main thread. In the second version, the checking isn't done until the background thread starts executing. By then, <code>active</code> may have changed in value from when the async call was made.</p>\n\n<p>Here is a sample test that illustrates the behaviour of concurrent code:</p>\n\n<pre><code>var i = 0\nfor _ in 0..<10 {\n i += 1\n let str = \"\\(i)\\t=\"\n DispatchQueue.main.async {\n print(\"Back\", str, i)\n }\n print(\"Main\", str, i)\n}\nprint(\"------------\")\n</code></pre>\n\n<p>It may print in the console:</p>\n\n<blockquote>\n<pre><code>Main 1 = 1\nMain 2 = 2\nMain 3 = 3\nMain 4 = 4\nMain 5 = 5\nMain 6 = 6\nMain 7 = 7\nMain 8 = 8\nMain 9 = 9\nMain 10 = 10\n------------\nBack 1 = 10\nBack 2 = 10\nBack 3 = 10\nBack 4 = 10\nBack 5 = 10\nBack 6 = 10\nBack 7 = 10\nBack 8 = 10\nBack 9 = 10\nBack 10 = 10\n</code></pre>\n</blockquote>\n\n<p>(The order of the lines that are printed asynchronously, may vary).</p>\n\n<p>This is the difference between checking the value of a variable on the main thread or asynchronously.</p>\n\n<hr>\n\n<p>If you are aiming for conciseness, here are a couple of versions that use <a href=\"https://developer.apple.com/documentation/swift/optional/1539476-map\" rel=\"nofollow noreferrer\">Optional map</a> and are similar in functionality to your versions respectively:</p>\n\n<p>1)</p>\n\n<pre><code>UIApplication.shared.keyWindow.map { w in\n active?\n DispatchQueue.main.async { w.startIndicatingActivity() }\n :\n DispatchQueue.main.async { w.stopIndicatingActivity() }\n}\n</code></pre>\n\n<p>2)</p>\n\n<pre><code>DispatchQueue.main.async {\n UIApplication.shared.keyWindow.map {\n active ? $0.startIndicatingActivity() : $0.stopIndicatingActivity()\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:24:33.190",
"Id": "229805",
"ParentId": "229729",
"Score": "2"
}
},
{
"body": "<p>From a processing efficiency perspective, they are largely indistinguishable. But if I were forced to choose between these two approaches, I might lean towards the latter, wrapping the whole <code>if</code>-<code>else</code> test in a single dispatch to the main queue, for two reasons:</p>\n\n<ol>\n<li><p>There is a timing issue: </p>\n\n<p>Let’s assume you ran this from a background thread and <code>active</code> was <code>false</code>, so you asynchronously dispatch the activity indicator update back to the main queue. What if, by the time the main queue gets to the dispatched block, that <code>active</code> is now <code>true</code>? Do you still really want to turn off the activity indicator? No, you almost certainly want to treat the combined test of <code>active</code> and the corresponding updating of the activity indicator as a single operation.</p></li>\n<li><p>There is a thread safety issue:</p>\n\n<p>When dealing with this boolean (and I’m assuming it’s a simple boolean, not wrapped in some synchronization mechanism), you should think about how you ensure thread-safe access to it. One really should synchronize access to one’s properties when writing multi-threaded code, and the first approach makes it unclear from which thread are you retrieving <code>active</code> (much less from which thread(s) is it being updated). One very simple synchronization technique to ensure that all reads and writes to <code>active</code> are done on the main queue, which, by virtue of being a serial queue, ensures thread-safety.</p></li>\n</ol>\n\n<hr>\n\n<p>A few observations regarding other possible patterns/considerations: </p>\n\n<ol>\n<li><p>You might want to consider whether, rather than writing a routine that you manually call to check <code>active</code> and update the activity indicator accordingly (meaning that every time you update <code>active</code>, you have to remember to call this routine), whether you might prefer to just supply the <code>active</code> property an observer that does the updating of the activity indicator for you. If you can have your property automatically trigger the UI update, then it eliminates the possibility of them getting out of sync.</p></li>\n<li><p>There are special concerns if the changes to <code>active</code> are happening very quickly:</p>\n\n<ul>\n<li><p>First, if <code>active</code> changes are happening extremely quickly (e.g. thousands of times per second), you risk flooding the main queue. You can address these sorts of issues with things like dispatch sources.</p></li>\n<li><p>Second, even if it’s only a couple of times per second, you might want to avoid starting and stopping the activity indicator too quickly (because it yields a spinner that is constantly restarting, yielding a “Max Headroom” style of stuttering effect). For example, if <code>active</code> changes every ¼ second, and keeps doing that for 10 seconds, you may want to just want to keep the spinner going for that full 10 seconds, not starting and stopping it repeatedly. You can accomplish this by programming some latency in the “stop activity indicator” routine. E.g. when <code>active</code> is set to <code>false</code>, add non-repeating timer to stop the activity indicator in ½ second, but only after canceling any prior timer, if any. Likewise, when <code>active</code> is set to <code>true</code>, only “start” the activity indicator if you know it’s not already started.<br /> </p></li>\n</ul>\n\n<p>Bottom line, be aware that the right implementation might depend upon the frequency of changes.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:55:37.753",
"Id": "229917",
"ParentId": "229729",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229917",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T01:22:52.727",
"Id": "229729",
"Score": "4",
"Tags": [
"multithreading",
"swift",
"grand-central-dispatch"
],
"Title": "Swift main thread style"
}
|
229729
|
<blockquote>
<p>You have a file that describes historic data of the London Underground showing dates when stations have been unavailable. The file contains these fields, separated by a pipe character:</p>
<ul>
<li>Date: Format of this is mm-dd-yyyy.</li>
<li>Line: Each line has a unique name. For example, “Northern”.</li>
<li>Station: Each station has a unique name. For example, “Angel”.</li>
<li>Notes: Describes the outage</li>
</ul>
<p>Here is an example of one entry in the file, which shows that the Northern Line was not operating at Bank on 23 August 2019 due to a function at London Bridge.</p>
<pre><code>08-23-2019|Northern|Bank |No service on Bank branch due to birthday booking at London Bridge station.
</code></pre>
<p>Write a script that solves the following problems:</p>
<ol>
<li><p>Display each station that was affected by an outage on 10 July 2019.</p></li>
<li><p>Between 10 July 2017 and 14 November 2017, which lines had outages and what was the number of stations affected?</p></li>
</ol>
</blockquote>
<p>I was able to complete both problems but the review of the work said it was done poorly.</p>
<pre><code># I created a test input file in the same folder as a proxy input.
import datetime # import built in datetime module for problem 2
with open('input.txt') as file: # read the input file into a list of lines
file_input = file.read().splitlines()
# split the file input on the pipe
LonUndOutages = []
for var in file_input:
LonUndOutages.append(var.split("|"))
# creating empty lists for the answers for Problem 2
Prob1Output = ""
LonUndStations = []
LonUndLines = []
# solving problem 1 and prep for the answers for Problem 2
print("Problem 1:")
for line in LonUndOutages:
if line[0] == "07-10-2019":
Prob1Output = Prob1Output + line[2] + "was affected by an outage on July 10, 2019\n"
line[0] = datetime.datetime.strptime(line[0], '%m-%d-%Y') # convert the date in line[0] to a datetime object
if datetime.datetime(2017,7,10) < line[0] < datetime.datetime(2017,11,14):
# the above line checks if line[0] is in the time range july 10 2017 to nov 14, 2017
if line[1] not in LonUndLines: # ensures LonUndLines doesnt have duplicates
LonUndLines.append(line[1]) # adds each line that had an outage to a list
if line[2] not in LonUndStations: # ensures LonUndStations doesnt have duplicates
LonUndStations.append(line[2]) # adds each station that had an outage to a list
if not Prob1Output:
print("There were no stations affected by an outage on July 10, 2019")
else:
print(Prob1Output)
print()
print("Problem 2:")
print("The following lines had outages:")
print(*LonUndLines, sep=', ')
print("During the period between July 10, 2017 and November 15, 2017 there were " + str(len(LonUndStations))
+ " station(s) affected")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:53:19.887",
"Id": "447138",
"Score": "0",
"body": "Just curious - where are you getting this problem? (And others, e.g. \"Problem 2\")"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T16:27:45.093",
"Id": "447150",
"Score": "0",
"body": "If the review was done by a human supervisor and it just says \"it was done poorly\", that's horrible teaching. He should tell you what you did wrong and how to improve it, otherwise how are you going to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T01:21:30.657",
"Id": "447194",
"Score": "0",
"body": "This was from the third stage of job interview process for a network engineer. My candidacy was rejected based on this test and the recruiter was able to get this as feedback."
}
] |
[
{
"body": "<p>That's a fun problem.</p>\n\n<h2>Don't use more memory than you have to</h2>\n\n<pre><code>with open('input.txt') as file: # read the input file into a list of lines\n file_input = file.read().splitlines()\n# ...\nfor var in file_input:\n LonUndOutages.append(var.split(\"|\"))\n\n</code></pre>\n\n<p>shouldn't be necessary. Rather than calling <code>file.read()</code>, iterate on the file object itself. It will yield lines that you can split on directly.</p>\n\n<h2>Naming conventions</h2>\n\n<pre><code>LonUndOutages\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>lon_und_outages\n</code></pre>\n\n<p>and similarly for your other variables.</p>\n\n<h2>Unpack your line</h2>\n\n<p>Assign variables to the results of your split, like so:</p>\n\n<pre><code>date, line, station, notes = outage\n</code></pre>\n\n<p>Note that there's a nomenclature collision, because your spec describes one column as <code>line</code>, so call each file line a record or an outage.</p>\n\n<h2>Separate output from logic</h2>\n\n<pre><code> Prob1Output = Prob1Output + line[2] + \"was affected by an outage on July 10, 2019\\n\"\n</code></pre>\n\n<p>You're storing output early for two purposes: to eventually show that output, and to know whether there were stations affected. This dual-purpose code is generally not advisable. Store the confirmed outages in a separate list, or yield them from a generator function, to be consumed and formatted by an output function that has no logic at all.</p>\n\n<h2>General</h2>\n\n<p>Run a linter that will tell you PEP8 hints, or use an IDE that will do the same. Make functions to house your logic.</p>\n\n<h2>Example</h2>\n\n<pre><code>from collections import namedtuple\nfrom datetime import date, datetime\nfrom typing import Iterable, Set\n\nRecord = namedtuple('Record', ('date', 'line', 'station', 'notes'))\n\n\ndef read_file(fn: str) -> Iterable[Record]:\n with open(fn) as file:\n for record in file:\n date_str, *others = record.split('|')\n record_date = datetime.strptime(date_str, '%m-%d-%Y').date()\n yield Record(record_date, *others)\n\n\ndef stations_on_date(records: Iterable[Record], record_date: date) -> Set[str]:\n return set(r.station for r in records if r.date == record_date)\n\n\ndef lines_and_stations_between_dates(\n records: Iterable[Record],\n start: date,\n end: date,\n) -> (Set[str], Set[str]):\n matching = [r for r in records if start <= r.date <= end]\n lines = set(r.line for r in matching)\n stations = set(r.station for r in matching)\n return lines, stations\n\n\ndef print_iter(to_print: Iterable[str]):\n msg = ', '.join(to_print)\n print(msg or 'none')\n\n\ndef main():\n records = tuple(read_file('input.txt'))\n\n date1 = date(2019, 7, 10)\n print(f'Stations affected by an outage on {date1}:')\n stations1 = stations_on_date(records, date1)\n print_iter(stations1)\n\n start2 = date(2017, 7, 10)\n end2 = date(2017, 11, 14)\n range_desc = f'between {start2} and {end2}'\n lines2, stations2 = lines_and_stations_between_dates(records, start2, end2)\n\n print(f'Lines with outages {range_desc}:')\n print_iter(lines2)\n\n print(f'Number of stations affected {range_desc}:')\n print(len(stations2))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>Output and logic are separated</li>\n<li>Use a <code>namedtuple</code> for better structure</li>\n<li>Hold onto a <code>date</code>, not a <code>datetime</code></li>\n<li>Use <code>set</code> to avoid duplicates in the output</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T04:06:55.327",
"Id": "447081",
"Score": "0",
"body": "Can't `print_iter` be reduced to one line, `print(', '.join(to_print) if to_print else 'none')` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T09:33:05.393",
"Id": "447106",
"Score": "1",
"body": "if `print_iter` is fed an empty iterator, the `if to_print` will be True. another option would be to first assemble the message, and then print it if there is one: `msg = \", \".join(to_print); print(msg or \"none\")`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T16:57:31.063",
"Id": "447156",
"Score": "0",
"body": "And you've done it but not said it explicitly: make functions that e.g. take the date as a parameters, to promote reusability. All the arbitrary stuff, like the particular dates in question is in the reduced main program. Also by changing datetime to date I think you've fixed a open/closed interval bug in the original, which raises the issue of testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T01:45:04.850",
"Id": "447195",
"Score": "0",
"body": "re. `print_iter`: it's much ado about nothing, but yes, it's a good change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T03:12:17.310",
"Id": "447198",
"Score": "0",
"body": "So should for loops always be stored in functions? Im pretty new to python and I thought the shorter the code the better where it looks like here ur saying to break each action into its own function. Is there a style guide I should look at for these types of things?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T03:30:53.930",
"Id": "447199",
"Score": "0",
"body": "@mrhinton101 Think more generally. Not just for loops, but most longer blocks of code are more manageable in functions. There are exceptions to most rules, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T07:49:02.973",
"Id": "447207",
"Score": "0",
"body": "@mrhinton101Whole books have been written about this sort of thing but I think https://able.bio/rhett/python-functions-and-best-practices--78aclaa is a good, clear introduction. As regards readability, people generally don't sit down and read your code as if it were a novel (except for code reviews). They come to one of your co-workers (you, of course are on holiday) and say, \"the format of the data has changed and your group's reports have stopped working.\" They go into the IDE, find the read_file function and make the appropriate changes.They only need to figure out 6 lines.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T07:53:08.400",
"Id": "447209",
"Score": "0",
"body": "Small apology - I missed \"Make functions to house your logic.\""
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T03:07:40.673",
"Id": "229731",
"ParentId": "229730",
"Score": "5"
}
},
{
"body": "<h1>Memory Usage</h1>\n<p>When reading from the file, you can assign create the list there instead of reading lines, splitting them, and appending to the list later in the program. It can be as easy as this</p>\n<pre><code>with open('input.txt') as file:\n outages = [line.split("|") for line in file]\n</code></pre>\n<h1>Variable Naming</h1>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> guidelines say that variables should be in <code>snake_case</code>. The only time you should use <code>PascalCase</code> is when dealing with classes. Since you're dealing with specific outages in London, you can simply remove London from the variable names, making them shorter.</p>\n<pre class=\"lang-py prettyprint-override\"><code>LonUndOutages -> outages\nLonUndStations -> stations\nLonUndLines -> lines\n</code></pre>\n<h1>Creating Lists with Loops</h1>\n<p>Like shown above, when you have</p>\n<pre><code>my_list = []\nfor item in other_list:\n my_list.append(item)\n</code></pre>\n<p>This can be shortened to one line</p>\n<pre><code>my_list = [item for item in other_list]\n</code></pre>\n<h1>Simplifying <code>if/else</code></h1>\n<p>This</p>\n<pre><code>if not Prob1Output:\n print("There were no stations affected by an outage on July 10, 2019")\nelse:\n print(Prob1Output)\n</code></pre>\n<p>can become this</p>\n<pre><code>print("There were no stations affected by an outage on July 10, 2019" if not Prob1Output else Prob1Output)\n</code></pre>\n<p>Looks neater and less chunky.</p>\n<h1>Formatting Strings</h1>\n<p>You can directly include variables in your strings without having to type cast them, using <code>f""</code>. From this</p>\n<pre><code>print("During the period between July 10, 2017 and November 15, 2017 there were " + str(len(LonUndStations))\n + " station(s) affected")\n</code></pre>\n<p>to this</p>\n<pre><code>print(f"During the period between July 10, 2017 and November 15, 2017 there were {len(stations)} station(s) affected.")\n</code></pre>\n<h1>Too Many Comments</h1>\n<p>Comments should mainly be used to describe code that may be hard to comprehend, like an algorithm, or why you chose to do something. Comments like this</p>\n<pre><code>import datetime # import built in datetime module for problem 2\nwith open('input.txt') as file: # read the input file into a list of lines\n file_input = file.read().splitlines()\n\n# split the file input on the pipe\nLonUndOutages = []\nfor var in file_input:\n LonUndOutages.append(var.split("|"))\n</code></pre>\n<p>Anyone reading the code and see what it does, without the comments. Comments like these can decrease the readability of your code, as readers see more bulk when reading your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T04:19:53.760",
"Id": "447082",
"Score": "5",
"body": "I would add that excessive commenting is a sign that the code isn't expressive enough, and line-by-line commenting is a sign that the author isn't fluent in the programming language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T09:29:40.610",
"Id": "447105",
"Score": "1",
"body": "`print(\"There were no stations affected by an outage on July 10, 2019\" if not Prob1Output else Prob1Output)` can be even clearer. `fallback_msg = \"There were no stations affected by an outage on July 10, 2019\"; print(Prob1Output or fallback_msg)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T16:24:25.277",
"Id": "447149",
"Score": "0",
"body": "I don't see how reducing if/else etc down to one line without removing the if/else improves code readability. In fact, in many cases it will reduce it as you aren't able to see, at a glance, where the decision points in the code are, as they now \"hidden\" within blocks of text."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T03:58:25.653",
"Id": "229732",
"ParentId": "229730",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T02:23:09.753",
"Id": "229730",
"Score": "8",
"Tags": [
"python",
"interview-questions",
"csv"
],
"Title": "Analyzing records of London Underground outages"
}
|
229730
|
<p>I'm learning C, and wrote this program outside of my assignments in order to practice pointer manipulation and data structures, step by step. I want to ensure that this program follows well known conventions, has excellent style and readability, and uses pointers as efficiently as possible, before I move on to more complex structs. </p>
<p>I am aware I am not doing any error checking or type checking. I don't intend to export this code as-is, my intention is to practice with pointers. I found it easiest for now to keep the code as simple as possible and remove checking. This is also why I created the additional functions, just to help isolate parts of the code. </p>
<p>If appropriate, I'm also interested in modifying the <code>freelist()</code> function to work recursively, freeing the last node first. Currently, if the node order is <code>{1,2,3}</code>, 1 is freed first. I haven't been able to successfully call the function recursively to instead free the nodes from 3 then 2 then 1. </p>
<pre><code>// This program stores N integers from user input into a
// linked list, prints the list, and then frees each node.
#include <stdio.h>
#include <stdlib.h>
#define N 5
typedef struct _node {
int value;
struct _node *next;
} NODE;
int getinteger(void);
void printlist(NODE **head);
void freelist(NODE *head);
int main(void)
{
NODE *start = NULL;
for (int i = 0, n = 0; i < N; i++)
{
n = getinteger();
NODE *newnode = (NODE *) malloc(sizeof(NODE));
newnode->value = n;
newnode->next = NULL;
if (start == NULL)
{
start = newnode;
}
else
{
NODE *p = NULL;
for (p = start; p->next != NULL; p = p->next)
;
p->next = newnode;
}
}
printlist(&start);
freelist(start);
}
int getinteger(void)
{
int n = 0;
printf("Enter integer: ");
scanf("%i", &n);
return n;
}
void printlist(NODE **head)
{
NODE **tracer = head;
while ((*tracer) != NULL)
{
printf("%i\n",(*tracer)->value);
tracer = &(*tracer)->next;
}
}
void freelist(NODE *head)
{
NODE *p = head;
while (p != NULL)
{
NODE *next = p->next;
free(p);
p = next;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:37:19.343",
"Id": "447137",
"Score": "3",
"body": "While I voted +1 on this question, I was torn because of the lack of error checking. Because C is very close to assembly and doesn't throw exceptions one should always perform error checking on possible errors that can cause the program to terminate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:56:47.857",
"Id": "447182",
"Score": "1",
"body": "Note taken on error checking. I'll especially take this into consideration when posting for code reviews. I want to ensure that any time someone takes during review is spent wisely. Thank you."
}
] |
[
{
"body": "<p>Hi Jim Diroff II and welcome to CodeReview,</p>\n\n<p>Your code looks sane and I didn't spot any leaks.</p>\n\n<p>In <code>printlist()</code> why are you using a double pointer? This is only required if you intend to modify the pointer value, which you don't. Better use a normal pointer here:</p>\n\n<pre><code>void printlist(NODE *head)\n{\n NODE *tracer = head;\n while (tracer != NULL)\n {\n printf(\"%i\\n\", tracer->value);\n tracer = tracer->next;\n }\n}\n</code></pre>\n\n<p>If you move the definitions of your helper functions above <code>main()</code>, you can save yourself the forward declarations. </p>\n\n<p>To get <code>freelist()</code> to work in the opposite direction, I suggest making it a doubly linked list, which also would be a nice additional task to learn more about pointers. Having a recursive cleanup function has the potential to trash your programm with longer lists and will also add a lot performance overhead:</p>\n\n<pre><code>void freelist(NODE* head)\n{\n if (head)\n {\n freelist(head->next);\n free(head);\n }\n}\n</code></pre>\n\n<p>Also, don't avoid error handling. It's the biggest issue I see in code, that someone didn't want to check <em>that one return value</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T11:06:31.690",
"Id": "447114",
"Score": "1",
"body": "*\"If you move the definitions of your helper functions above `main()`, you can save yourself the forward declarations.*\" -- I wouldn't suggest that. It's easier to read if you can see the entry point of the program first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:31:34.260",
"Id": "447134",
"Score": "2",
"body": "@JL2210 It's a personal choice in a program of this size. While I wouldn't have stated it in a review, my first impression was the same as the reviewers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:32:31.690",
"Id": "447177",
"Score": "1",
"body": "As the payload does not have any complex destruction, the order really does not matter. But if it matters for a modified version, using an in-place-reversal and than destructing from the head is better than moving to double-linkage *just* for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T21:13:15.553",
"Id": "447183",
"Score": "0",
"body": "Thank you all for your comments. I really appreciate the thorough and detailed responses, as well as the discussion on specifics. On the topic of the helper functions, in the class I'm taking, the preferred style is to declare functions before main() and define functions after main(). That is fine for the class, but in real-world programming, which method is more conventional? If I'm reading the feedback correctly, we have a few votes for declaring and defining functions before main(). Also, note taken on the error handling and checking. Will remember for future posts."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T08:13:41.273",
"Id": "229741",
"ParentId": "229738",
"Score": "7"
}
},
{
"body": "<h1>Naming</h1>\n<p>It's unconventional to name a type with all-uppercase - we normally reserve those names for preprocessor macros, to warn readers that they need treating with care. Avoid such names for ordinary identifiers.</p>\n<p>Avoid using identifiers that begin with an underscore - in many situations, those names are reserved for use by the implementation, which could conflict with your own uses.</p>\n<h1>Allocation</h1>\n<p>Let's look at this section:</p>\n<blockquote>\n<pre><code> NODE *newnode = (NODE *) malloc(sizeof(NODE));\n newnode->value = n;\n newnode->next = NULL;\n</code></pre>\n</blockquote>\n<p>There's a serious bug here. Remember that <code>malloc()</code> can return a null pointer. It's <strong>essential</strong> to check that <code>newnode</code> is not null before we dereference it using <code>*</code> or <code>-></code>.</p>\n<p>Because <code>malloc()</code> returns a <code>void*</code>, it's not necessary or desirable to cast the result - we can assign it directly to <code>newnode</code>. Also, when computing the size, we can avoid repeating the type of the allocation by writing <code>sizeof *newnode</code> for the size (this has more value when the allocation is far from the declaration, but it's a good habit to be in).</p>\n<p>That gives this replacement:</p>\n<pre><code> Node *newnode = malloc(sizeof *newnode);\n if (!newnode) {\n fputs("Allocation failed\\n", stderr);\n return EXIT_FAILURE;\n }\n\n newnode->value = n;\n newnode->next = NULL;\n</code></pre>\n<h1>Reading input</h1>\n<p>Another function whose return value must be checked is <code>scanf()</code>. If I enter something that's not a number, or if I close the input stream, then we don't write to <code>n</code> here:</p>\n<blockquote>\n<pre><code>scanf("%i", &n);\n</code></pre>\n</blockquote>\n<p>We need to check the return value and test whether the expected number of items were successfully converted. Something like this:</p>\n<pre><code>int getinteger(void)\n{\n int n = 0;\n printf("Enter integer: ");\n fflush(stdout);\n while (scanf("%i", &n) != 1) {\n if (feof(stdin)) {\n /* no point retrying! */\n fputs("Read failure\\n", stderr);\n exit(EXIT_FAILURE);\n }\n printf("Invalid input! Enter integer: ");\n fflush(stdout);\n scanf("%*[^\\n]"); /* discard rest of line */\n /* newline remains, but will be discarded by scanf("%i") */\n }\n return n;\n}\n</code></pre>\n<p>Notice that there's a lot more code for dealing with the unexpected than with the "happy path" - that's a common experience when reading input using C.</p>\n<h1>Memory management</h1>\n<p>Apart from the lack of checking when <code>malloc()</code> is used, the memory management is great. No leaks, double-frees, or use of uninitialised, unallocated or released memory.</p>\n<h1>Efficiency</h1>\n<p>Notice that every time we add a node, we have to start from the head, and traverse the whole length of the list to get to the tail. This becomes more and more work as the list gets longer - sometimes likened to <a href=\"https://www.joelonsoftware.com/2001/12/11/back-to-basics/\" rel=\"noreferrer\">Schlemiel the Painter</a>. We can make this more efficient, though at the cost of some extra storage, by maintaining a pointer to the tail of the list as well as the head.</p>\n<h1>Other improvements</h1>\n<p>We don't need to pass a pointer-to-pointer into <code>printlist()</code>; a plain <code>Node *</code> is fine:</p>\n<pre><code>void printlist(Node *p)\n{\n for (; p; p = p->next) {\n printf("%i\\n", p->value);\n }\n}\n</code></pre>\n<p>When we're looking for the list tail, we can simplify by starting <code>p</code> at <code>head</code> rather than first assigning <code>NULL</code>:</p>\n<pre><code> Node *p = start;\n while (p->next) {\n p = p->next;\n }\n p->next = newnode;\n</code></pre>\n<p>In the main loop in <code>main()</code>, <code>n</code> shouldn't be declared in the <code>for</code> initializer, as it's not part of the loop control.</p>\n<p>If we define <code>main()</code> last, the definitions of the other functions can act as their declarations, so no need to forward-declare them.</p>\n<hr />\n<h1>Improved code</h1>\n<p>Note: I haven't addressed the issue mentioned above in "Efficiency".</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n/* number of nodes to create in list */\n#define N 5\n\ntypedef struct node {\n int value;\n struct node *next;\n} Node;\n\n/* Prompt on stdout, and read a number from stdin */\nint getinteger(void)\n{\n printf("Enter integer: ");\n fflush(stdout);\n\n int n;\n while (scanf("%i", &n) != 1) {\n if (feof(stdin)) {\n /* no point retrying! */\n fputs("Read failure\\n", stderr);\n exit(EXIT_FAILURE);\n }\n printf("Invalid input! Enter integer: ");\n fflush(stdout);\n scanf("%*[^\\n]"); /* discard rest of line */\n /* newline remains, but will be discarded by scanf("%i") */\n }\n\n return n;\n}\n\nvoid printlist(Node *p)\n{\n for (; p; p = p->next) {\n printf("%i\\n", p->value);\n }\n}\n\nvoid freelist(Node *p)\n{\n while (p) {\n Node *next = p->next;\n free(p);\n p = next;\n }\n}\n\n\nint main(void)\n{\n Node *start = NULL;\n\n for (int i = 0; i < N; ++i) {\n int n = getinteger();\n\n Node *newnode = malloc(sizeof *newnode);\n if (!newnode) {\n fputs("Allocation failure\\n", stderr);\n return EXIT_FAILURE;\n }\n\n newnode->value = n;\n newnode->next = NULL;\n\n if (!start) {\n start = newnode;\n } else {\n Node *p = start;\n while (p->next) {\n p = p->next;\n }\n p->next = newnode;\n }\n }\n\n printlist(start);\n freelist(start);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:54:52.213",
"Id": "447180",
"Score": "0",
"body": "Thank you very much for this feedback. I especially appreciate the integer checking and allocation error. I'm going to spend some time reviewing your feedback and incorporating changes into my program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T22:12:39.857",
"Id": "447186",
"Score": "2",
"body": "*In theory* malloc() can return a null pointer. In practice, MacOS and Linux both use memory overcommit, so malloc() won't fail except in highly unusual circumstances (eg. you're trying to allocate tens of terabytes of memory). Windows doesn't do overcommit, but the available swap space is usually so huge that by the time you run out, the user will have already rebooted the computer because it was getting unbearably slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:34:34.053",
"Id": "447242",
"Score": "0",
"body": "`scanf(\"%*[^\\n]\"); /* discard pending input */` is a slight misnomer as a `'\\n'` remains unconsumed. Not an issue for a following `scanf(\"%i\", &n)`, but `scanf(\"%*[^\\n]\")` is not a complete \"discard pending input\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:42:19.603",
"Id": "447427",
"Score": "0",
"body": "@Mark, you can avoid overcommit, either with a suitable `sysctl` (to fix it globally) or with `ulimit` (for a process tree). Even on a system with unlimited overcommit, failing to check system call return values is a bad habit that should be unlearned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:44:37.487",
"Id": "447429",
"Score": "0",
"body": "@chux, yes, if we had a read that didn't ignore leading whitespace, we'd need to also discard the newline (either by adding `%*c` to the format string or with a separate `getchar()`. Do you have a suggestion for a better comment that's not too verbose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:31:21.363",
"Id": "447469",
"Score": "0",
"body": "Follow `scanf(\"%*[^\\n]\");` with `scanf(\"%*1[\\n]\");` _or_ go the `fgets()` route."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:49:19.623",
"Id": "447470",
"Score": "0",
"body": "@chux, I think the new comment is more correct, without being over-long."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T09:35:23.497",
"Id": "229743",
"ParentId": "229738",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "229743",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T07:06:05.063",
"Id": "229738",
"Score": "10",
"Tags": [
"beginner",
"c",
"linked-list",
"pointers"
],
"Title": "C - Learning Linked Lists, Pointer Manipulation - Store some ints, print and free memory"
}
|
229738
|
<p>I have another thread called <a href="https://codereview.stackexchange.com/q/229264/209774">Digitizing paper label system with Python</a></p>
<p>I have added username and password class (class is called <code>login()</code>).</p>
<p>I'd like to hear some feedback about my class <code>login()</code> is the structure okay?
Should I change anything within my structure? Shall I make any other amendments, I will hear out any feedback.</p>
<p>You will see a lot of <code>grid_forget</code>, because I wasn't sure how to structure my Classes, roots and how to close login class and load main app after successful log in.</p>
<p>The login app is near the bottom.</p>
<pre><code>from tkinter import *
from tkinter import DISABLED, messagebox
import tkinter.ttk as ttk
import os
import glob
from PIL import Image, ImageTk, ImageGrab
from pathlib import Path
import pyautogui
# from openpyxl import load_workbook
class App():
def __init__(self,master):
notebook = ttk.Notebook(master)
notebook.pack(expand = 1, fill = "both")
#Frames
main = ttk.Frame(notebook)
manual = ttk.Frame(notebook)
notebook.add(main, text='Main-Screen')
notebook.add(manual, text='Manual')
#Check boxes
#Assigning Integers to variables
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
var4 = IntVar()
var5 = IntVar()
var6 = IntVar()
var7 = IntVar()
var8 = IntVar()
var9 = IntVar()
var10 = IntVar()
var11 = IntVar()
var12 = IntVar()
#Text boxes for initials
#Displaying checkboxes and assigning to variables
self.Checkbox1 = Checkbutton(main, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1)
self.Checkbox1.grid(column = 2, row = 1, sticky = W)
self.Checkbox2 = Checkbutton(main, text="May Contain Statement.", variable=var2)
self.Checkbox2.grid(column = 2, row = 2, sticky = W)
self.Checkbox3 = Checkbutton(main, text="Cocoa Content (%).", variable=var3)
self.Checkbox3.grid(column = 2, row = 3, sticky = W)
self.Checkbox4 = Checkbutton(main, text="Vegetable fat in addition to Cocoa butter", variable=var4)
self.Checkbox4.grid(column = 2, row = 4, sticky = W)
self.Checkbox5 = Checkbutton(main, text="Instructions for Use.", variable=var5)
self.Checkbox5.grid(column = 2, row = 5, sticky = W)
self.Checkbox6 = Checkbutton(main, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6)
self.Checkbox6.grid(column = 2, row = 6, sticky = W)
self.Checkbox7 = Checkbutton(main, text="Nutritional Information Visible", variable=var7)
self.Checkbox7.grid(column = 2, row = 7, sticky = W)
self.Checkbox8 = Checkbutton(main, text="Storage Conditions", variable=var8)
self.Checkbox8.grid(column = 2, row = 8, sticky = W)
self.Checkbox9 = Checkbutton(main, text="Best Before & Batch Information", variable=var9)
self.Checkbox9.grid(column = 2, row = 9, sticky = W)
self.Checkbox10 = Checkbutton(main, text="Net Weight & Correct Font Size.", variable=var10)
self.Checkbox10.grid(column = 2, row = 10, sticky = W)
self.Checkbox11 = Checkbutton(main, text="Barcode - Inner", variable=var11)
self.Checkbox11.grid(column = 2, row = 11, sticky = W)
self.Checkbox12 = Checkbutton(main, text="Address & contact details correct", variable=var12)
self.Checkbox12.grid(column = 2, row = 12, sticky = W)
##DISABLE ON CLICK##
def showstate(*args):
if var1.get() or var2.get() or var3.get() or var4.get() or var5.get() or var6.get() or var7.get() or var8.get() or var9.get() or var10.get() or var11.get() or var12.get():
self.user = Label(main, text = "")
self.user.grid(column = 2, row = 0, sticky = N)
var1.trace_variable("w", showstate)
var2.trace_variable("w", showstate)
var3.trace_variable("w", showstate)
var4.trace_variable("w", showstate)
var5.trace_variable("w", showstate)
var6.trace_variable("w", showstate)
var7.trace_variable("w", showstate)
var8.trace_variable("w", showstate)
var9.trace_variable("w", showstate)
var10.trace_variable("w", showstate)
var11.trace_variable("w", showstate)
var12.trace_variable("w", showstate)
##DISABLE ON CLICK##
#Send data
def var_states():
text_file = open("logfile.txt", "a")
text_file.write()
text_file.close()
# pyautogui.keyDown('alt')
# pyautogui.keyDown('printscreen')
# pyautogui.keyUp('printscreen')
# pyautogui.keyUp('alt')
self.img = ImageGrab.grabclipboard()
self.img.save('paste.jpg', 'JPEG')
self.dataSend = Button(main, text = "Send", command = var_states).grid(column = 1, row = 13, sticky = W)
###################################################################################################################################
##Load Image##
###################################################################################################################################
# Create a Tkinter variable
self.tkvar = StringVar(root)
# Directory
self.directory = "//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project"
self.choices = glob.glob(os.path.join(self.directory, "*- to sign.jpg"))
self.tkvar.set('...To Sign Off...') # set the default option
# Images
def change_dropdown():
imgpath = self.tkvar.get()
img = Image.open(imgpath)
img = img.resize((529,361))
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
#return path value
self.p = None
def func(value):
global p
self.p = Path(value)
print(self.p)
#widgets
self.msg1 = Label(main, text = "Choose here")
self.msg1.grid(column = 0, row = 0)
self.popupMenu = OptionMenu(main, self.tkvar, *self.choices, command = func)
self.popupMenu.grid(row=1, column=0)
self.display_label = label2 = Label(main, image=None)
self.display_label.grid(row=2, column=0, rowspan = 500)
self.open_button = Button(main, text="Open", command=change_dropdown)
self.open_button.grid(row=502, column=0)
###################################################################################################################################
##Tab 2 - Manual##
###################################################################################################################################
def open_doc():
os.system("start C:/Users/Eduards/Desktop/Portfolio")
self.Manual_Button = Button(manual, text = "Open Manual", command = open_doc)
self.Manual_Button.pack()
###################################################################################################################################
##USERS##
###################################################################################################################################
class login(Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = Label(self, text="Username")
self.label_password = Label(self, text="Password")
self.entry_username = Entry(self)
self.entry_password = Entry(self, show="*")
self.label_username.grid(row=0, sticky=E)
self.label_password.grid(row=1, sticky=E)
self.entry_username.grid(row=0, column=1)
self.entry_password.grid(row=1, column=1)
self.logbtn = Button(self, text="Login", command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clicked(self):
# print("Clicked")
username = self.entry_username.get()
password = self.entry_password.get()
# print(username, password)
if username == "ed" and password == "1":
self.label_username.grid_forget()
self.label_password.grid_forget()
self.entry_username.grid_forget()
self.entry_password.grid_forget()
self.logbtn.grid_forget()
self.pack_forget()
app = App(root)
if username == "nb" and password == "2":
self.label_username.grid_forget()
self.label_password.grid_forget()
self.entry_username.grid_forget()
self.entry_password.grid_forget()
self.logbtn.grid_forget()
self.pack_forget()
app = App(root)
root = Tk()
root.minsize(950, 450)
root.title("SIGN OFF LABELS")
lf = login(root)
# app = App(root)
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>NEVER use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tkinter import *\n</code></pre>\n\n<p>Instead, use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import tkinter as tk\n</code></pre>\n\n<p>or even better:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tkinter import Class1, Class2\n</code></pre>\n\n<p>This allows everyone reading your code (like the people answering your question) to easily see where what name is coming from, and makes it that much simpler for other people's input to come your way without having to ask clarifying questions where variable X is coming from.</p>\n\n<p>I'll be restricting myself to your login() class, since I'm not experienced with tkinter. I am, however, experienced with (Py)Qt, so I can offer some advice.</p>\n\n<h3>Naming</h3>\n\n<p>In Python, we name classes with PascalCase (aka TitleCase). It's also a widget of some kind, so put that in the name as well, to make it easier. login() looks like a function. I'd think something like <code>LoginWidget</code> or if it's more tkinter-like, <code>LoginFrame</code>.</p>\n\n<h3>Widget/Frame destruction</h3>\n\n<p>Practically, you're getting rid of your Login widget when it's function's done. Why don't you just delete the widget and create any widget depending on what you need to login for? Typically, this should be done in the widget/frame's <code>master</code>. If you kept all other references inside, you don't really have to think about deletion of it's instance variables if you just delete the entire thing. </p>\n\n<h3>Look up account data</h3>\n\n<p>Also DO change your <code>_login_btn_clicked()</code> method to look up the login data from elsewhere. Even if it's just a file named passwords.txt where you save it in plain text. It's no more unsafe than storing it directly in your code. </p>\n\n<p>Aside from that, it also avoids code repetition, like having the exact same result for two different accounts like you do.</p>\n\n<p>Given a passwords.txt which stores them like username:password (Can't say to often, but this is VERY unsafe):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def _login_btn_clicked(self):\n # print(\"Clicked\")\n username = self.entry_username.get()\n password = self.entry_password.get()\n\n # print(username, password)\n account_list = [line.split(\":\", maxsplit=1) for line in open(\"passwords.txt\")] \n # list of 2-tuples. Usersnames with colons inside not supported.\n accounts = {key: value.rstrip() for key, value in account_list} \n # Convert to dict[username] = password, and slices off the line ending. \n # Does not support passwords ending in whitespace.\n\n if accounts[username] == password:\n store_account_information_for_later_use()\n inform_master_that_I_am_obsolete()\n # app = App(root) # Should be done by self.master.\n else:\n notify_user_of_failure()\n</code></pre>\n\n<p>In the case that this login frame is a window instead of embedded into one, you can just close it an make a new window afterwards.</p>\n\n<p>Please do note that some of my invented function names describe more verbose what they should do, and that these names are to long for normal function names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T08:41:55.700",
"Id": "447098",
"Score": "0",
"body": "hi, when you said #Dont know what it does here at `app = App(root)` this basically opens the `App()` class after logged in. I will read through your feedback when I have time and get back to it asap. Thanks for your time in answering!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T08:43:54.707",
"Id": "447099",
"Score": "0",
"body": "Ah, ok. In that case, I'd put it in the same function/class that created the Login class itself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T07:55:05.313",
"Id": "229740",
"ParentId": "229739",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T07:30:22.973",
"Id": "229739",
"Score": "2",
"Tags": [
"python",
"tkinter"
],
"Title": "Username and Password application"
}
|
229739
|
<p>I've written a blog site using <code>python</code> and <a href="https://www.fullstackpython.com/flask.html" rel="nofollow noreferrer"><code>Flask</code></a>. It works a little like Reddit, but instead of having some anonymous users, there are <em>only</em> anonymous users. This site allows users to add posts (after being filtered, of course). I'd like feedback on a couple things:</p>
<ol>
<li><p>Is there any way I can better filter user input for <code>XSS</code>? I only check if the beginning or ending of each word is <code><</code> or <code>></code>, which can probably be bypassed fairly easily.</p></li>
<li><p>I store information about each post in a <code>json</code> file. Is this a good way to store this type of information?</p></li>
</ol>
<p>As always, feedback in any other areas is accepted and considered.</p>
<h1>File Structure</h1>
<pre><code>Blog
| __pycache__
| posts
...json files generated by users creating posts...
| templates
| index.html
| config.py (only thing in this file is SECRET_KEY)
| post.py
| server.py
</code></pre>
<h1>server.py</h1>
<pre><code>"""
Main Module for running and managing the blog
"""
import random
import json
import os
from flask import Flask, render_template, request, flash, redirect, url_for
from config import SECRET_KEY
from post import Post
APP = Flask(__name__)
APP.secret_key = SECRET_KEY
POSTS = "posts/"
@APP.route("/", methods=["GET", "POST"])
def index():
"""
Main Page, responsible for displaying posts and
adding new posts
"""
if request.method == "POST":
content = request.form['content']
new_post = Post(generate_user(), content)
if new_post.postable():
add_post(new_post)
else:
error = ""
if new_post.contains_profanity():
error += "Your post contains profanity! "
if new_post.over_max_length():
error += "Your post is over the max length! "
if new_post.contains_html():
error += "Your post contains html! "
flash(error)
return redirect(url_for("index"))
return render_template("index.html", post=get_posts())
def get_posts() -> list:
"""
Returns all the posts created
"""
files = os.listdir(POSTS)
posts = []
for file in files:
with open(f"{POSTS}{file}", "r") as user_post:
data = json.load(user_post)
posts.append(data)
return posts
def add_post(new_post) -> None:
"""
Adds a new post to the posts folder
"""
data = {
'USER': new_post.user,
'UNIQUE ID': new_post.unique_id,
'CONTENT': new_post.content,
'DATE POSTED': new_post.date_created
}
with open(f"{POSTS}{new_post.unique_id}.json", "w") as file:
json.dump(data, file, indent=4)
def generate_user() -> str:
"""
Returns a random number for assigning to an anonymous user
when they create a post
"""
return f"Anonymous#{random.randint(1_000_000, 9_999_999)}"
if __name__ == '__main__':
APP.run(debug=True, host="0.0.0.0", port=80)
</code></pre>
<h1>post.py</h1>
<pre><code>"""
This module is for the sole purpose of containing the
Post class
"""
import random
import datetime
class Post():
"""
Class for peoples posts
"""
def __init__(self, user, content):
self.user = user
self.unique_id = self.generate_unique_id()
self.content = content
self.max_characters = 5000
now = datetime.datetime.now()
end = "PM" if now.hour >= 12 else "AM"
self.date_created = f"{now.month}/{now.day}/{now.year} {now.hour}:{now.minute}:{now.second} {end}"
def generate_unique_id(self) -> int:
"""
Returns a unique id for this post
"""
return random.randint(100_000_000, 999_999_999)
def contains_profanity(self) -> bool:
"""
Returns a boolean based on if there is profanity
in the post. This checks against a VERY basic list
of profanity
"""
for word in self.content.split():
if word.lower() in ["foo", "bar", "word"]:
return True
return False
def over_max_length(self) -> bool:
"""
Returns a boolean based on if the post exceeds the
max limit allowed
"""
return len(self.content) > self.max_characters
def contains_html(self) -> bool:
"""
Returns a boolean if there is any html in the
post. This checks against a very basic list of
html, ones that are most common for XSS
"""
for word in self.content.split():
if word[0] == "<" or word[-1] == ">":
return True
return False
def postable(self) -> bool:
"""
Uses all of these class methods to determine if
this post is allowed to be posted
"""
return not self.contains_html() and \
not self.over_max_length() and \
not self.contains_profanity()
</code></pre>
<h1>index.html</h1>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<title>Blog</title>
<style type="text/css">
fieldset {
border-radius: 10px;
border-width: 5px;
}
input[type=text] {
border-color: yellow;
border-radius: 5px;
width: 150px;
height: 25px;
font-size: 17px;
}
body {
background: pink;
}
textarea {
min-height: 100px;
max-width: 500px;
min-width: 500px;
max-width: 1000px;
font-size: 16px;
border-radius: 3px;
}
button[type=submit] {
margin-top: 5px;
height: 40px;
width: 120px;
border-radius: 10px;
font-size: 20px;
background-color: yellow;
color: black;
letter-spacing: 1px;
border-color: black;
}
button[type=submit]:hover {
background-color: purple;
color: white;
cursor: pointer;
}
#user { font-size: 20px; }
#date { font-size: 15px; }
#content {
margin-top: 10px;
font-size: 14px;
}
</style>
</head>
<body>
<!-- Posts Start -->
{% for p in post %}
<fieldset>
<div id="user"><b>{{ p['USER'] }} - {{ p['DATE POSTED'] }}</b></div>
<div id="content">{{ p['CONTENT'] }}</div>
</fieldset>
{% endfor %}
<!-- Posts End -->
<!-- New Post Start -->
<form action="" method="post">
<fieldset>
<h3>Create New Post</h3>
<textarea placeholder="Enter Content Here" name="content"></textarea><br>
<button type="submit"><b>Post</b></button>
</fieldset>
</form>
<!-- New Post End -->
<!-- Errors Start -->
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
<!-- Errors End -->
</body>
</html>
</code></pre>
<h1>How the JSON data is stored</h1>
<pre><code>{
"USER": "Anonymous#8147466",
"UNIQUE ID": 766866833,
"CONTENT": "This is my post!",
"DATE POSTED": "9/27/2019 12:50:7 PM"
}
</code></pre>
<h1>Site after above post is made</h1>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<title>Blog</title>
<style type="text/css">
fieldset {
border-radius: 10px;
border-width: 5px;
}
input[type=text] {
border-color: yellow;
border-radius: 5px;
width: 150px;
height: 25px;
font-size: 17px;
}
body {
background: pink;
}
textarea {
min-height: 100px;
max-width: 500px;
min-width: 500px;
max-width: 1000px;
font-size: 16px;
border-radius: 3px;
}
button[type=submit] {
margin-top: 5px;
height: 40px;
width: 120px;
border-radius: 10px;
font-size: 20px;
background-color: yellow;
color: black;
letter-spacing: 1px;
border-color: black;
}
button[type=submit]:hover {
background-color: purple;
color: white;
cursor: pointer;
}
#user { font-size: 20px; }
#date { font-size: 15px; }
#content {
margin-top: 10px;
font-size: 14px;
}
</style>
</head>
<body>
<!-- Posts Start -->
<fieldset>
<div id="user"><b>Anonymous#8147466 - 9/27/2019 12:50:7 PM</b></div>
<div id="content">This is my post!</div>
</fieldset>
<!-- Posts End -->
<!-- New Post Start -->
<form action="" method="post">
<fieldset>
<h3>Create New Post</h3>
<textarea placeholder="Enter Content Here" name="content"></textarea><br>
<button type="submit"><b>Post</b></button>
</fieldset>
</form>
<!-- New Post End -->
<!-- Errors Start -->
<!-- Errors End -->
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T12:19:42.010",
"Id": "447121",
"Score": "0",
"body": "Do you have an example usage with this? It isn't immediately clear to me how this would produce the intended result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T16:53:09.933",
"Id": "447154",
"Score": "0",
"body": "@Mast I added the source code of the website after a post is made, if that makes anything more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:32:36.053",
"Id": "447160",
"Score": "0",
"body": "That's the result, but how is the function used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T21:23:05.883",
"Id": "447184",
"Score": "0",
"body": "@Mast I'm not quite sure what you mean. What function are you inquiring about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T10:10:49.060",
"Id": "447221",
"Score": "1",
"body": "@dfhwze That's why I edited my question removing the profanity, with Mast providing some sample words instead."
}
] |
[
{
"body": "<h2>Date formatting</h2>\n\n<pre><code>self.date_created = f\"{now.month}/{now.day}/{now.year} {now.hour}:{now.minute}:{now.second} {end}\"\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>from datetime import datetime\n...\ndatetime.now().strftime('%m/%d/%Y %I:%M:%S %p')\n</code></pre>\n\n<h2>Generators for logic</h2>\n\n<pre><code> for word in self.content.split():\n if word.lower() in [\"phooey\", \"shucks\", \"rascal\"]:\n return True\n return False\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return any(\n word.lower() in {'shut', 'the', 'front', 'door'}\n for word in self.content.split()\n)\n</code></pre>\n\n<p>Note the use of a <code>set</code> instead of a <code>list</code> for membership tests.</p>\n\n<h2>Boolean factorization</h2>\n\n<pre><code> return not self.contains_html() and \\\n not self.over_max_length() and \\\n not self.contains_profanity()\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return not (\n self.contains_html() or\n self.over_max_length() or\n self.contains_profanity()\n)\n</code></pre>\n\n<h2>Inline styles</h2>\n\n<p>You should really consider removing your styles from the <code>index</code> head and putting them into a separate <code>.css</code> file. Among other things, it'll improve caching behaviour.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T02:40:44.120",
"Id": "229773",
"ParentId": "229742",
"Score": "3"
}
},
{
"body": "<p>Your code looks okay to me. For your questions:</p>\n\n<ol>\n<li>Flask uses Jinja template engine, it already does XSS filter automatically for you. So you don't need to worry about that. Actually, implementing a XSS filter has a lot of things to concern, so just leave it to the template engine.</li>\n<li>For a toy app, storing data into a json file is fine. But in actual production environment, you should use a real database like mysql to handle this. Because once you've got a huge amount of data, reading all of them from a file would be very slow.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T09:35:34.330",
"Id": "229839",
"ParentId": "229742",
"Score": "0"
}
},
{
"body": "<p>I'd really made GET and POST routes into separate functions. Makes your project clearer as it grows.</p>\n\n<p>Instead of <code>error +=</code>, I'd made errors a list, and appended to that. It may be not an obvious win in your case, but imagine you will want some other way to separate errors in the future, eg, with HTML.\nAlso it would be much simpler, if <code>postable</code> could serve as a validation and returned reasons why it's not postable. Then there will be no need to check it twice.</p>\n\n<p>JSON data with spaces on key side is not JavaScript-friendly, so it's better be something like:</p>\n\n<pre><code>\"datePosted\": \"2019-09-27T12:50:07\"\n</code></pre>\n\n<p>Note also using ISO format: With front-end side library like Moment.js, it will be easy to turn it into \"N days ago\", to other timezone or to other format later.</p>\n\n<p><code>open(f\"{POSTS}{file}\", \"r\")</code> is not good practice from security point of view. Ensure the resulting path concatenation still lies within the directory it is intended to be. (See some answers here: <a href=\"https://stackoverflow.com/questions/6803505/does-my-code-prevent-directory-traversal\">https://stackoverflow.com/questions/6803505/does-my-code-prevent-directory-traversal</a> )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:24:09.527",
"Id": "229846",
"ParentId": "229742",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229773",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T08:34:07.520",
"Id": "229742",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"html5",
"flask"
],
"Title": "Blog with Python/Flask"
}
|
229742
|
<p>I'm trying to improve my Alternating Least Squares (ALS) model performance by testing using different model parameters, but the model performance is seemingly very low.</p>
<p>Since the Alternating Least Squares model is relatively different from other models under the evaluation perspective, I needed to set up my custom evaluation and cross-validation method in order for the GridSearchCV function to correctly work. To improve the performance, I tried to set up different param_grid and model to the testing function with apparently no results at all. My guess is that the custom parameters are not properly working. For reference, I looked at Jbochi's piece of code (<a href="https://gist.github.com/jbochi/2e8ddcc5939e70e5368326aa034a144e" rel="nofollow noreferrer">https://gist.github.com/jbochi/2e8ddcc5939e70e5368326aa034a144e</a>) to set up Discounted cumulative gain (DCG) for measuring my model score and the function Predefinedsplit from sklearn.model_selection (as you can see in the LeavePOutByGroup class) to set up the cv parameter.</p>
<pre class="lang-py prettyprint-override"><code>class LeavePOutByGroup():
def __init__(self, X, p=5, n_splits = 3):
self.X = X
self.p = p
self.n_splits = n_splits
test_fold = self.X.groupby("fullvisitorid").cumcount().apply(lambda x: int(x / p) if x < (n_splits * p) else -1)
self.s = PredefinedSplit(test_fold)
grid_search = GridSearchCV(rec_pipeline, param_grid,
cv=LeavePOutByGroup(train_set, p=5, n_splits=3),
scoring=ndcg_scorer, verbose=1)
grid_search.fit(train_set)
</code></pre>
<p>I expected the mean_test_score to significantly change by changing the model parameters, instead I got almost no improvements at all. This is what I got (the float shows the mean_test_score for each set of parameters tested with the ALS model):</p>
<pre class="lang-py prettyprint-override"><code>cvres = grid_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
print(mean_score, params)
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>0.012434668656604229 {'als__factors': 20, 'als__regularization': 0.001, 'matrix__confidence': 10}
0.011882640120018911 {'als__factors': 20, 'als__regularization': 0.001, 'matrix__confidence': 40}
0.01271910407436217 {'als__factors': 20, 'als__regularization': 0.0001, 'matrix__confidence': 10}
...
0.011947024379421394 {'als__factors': 100, 'als__regularization': 0.0001, 'matrix__confidence': 10}
0.010698034031201297 {'als__factors': 100, 'als__regularization': 0.0001, 'matrix__confidence': 40}
0.010091750744302954 {'als__factors': 100, 'als__regularization': 0.0001, 'matrix__confidence': 100}
</code></pre>
<p>My question is: is there any other approach I can try for solving the bad performance issue? What is your experience on that? Or should I just try another evaluation metric for my ALS model? If so, which one?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T02:23:33.700",
"Id": "447196",
"Score": "2",
"body": "I'm not immediately convinced that this should be closed. You would definitely need to add more code for this to be reviewable. Also, when you say performance... do you mean execution speed, or numerical performance? We regularly help with the former, but the latter wouldn't be as clearly on-topic."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:51:55.240",
"Id": "229748",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"machine-learning"
],
"Title": "Recommender system accuracy testing using GridSearchCV"
}
|
229748
|
<p>I am supposed to find the frequency of the unique array elements of a character array via a user defined function like <strong>int *unique(char *s)</strong>, which takes a pointer to a character and returns a pointer to a dynamically allocated array of integers. </p>
<p>There are some constraints. I cannot use additional array nor any array indexing. Only pointer arithmetic is allowed. My solution is as follows:</p>
<pre><code> int *uniqueCount(char *s)
{
int a=0,k,p;
for(k=0;*(s+k);k++)
{
for(p=k+1;*(s+p);p++)
{
if(*(s+k)==*(s+p)) break;
}
if(*(s+p)==0) a++;
}
int *arr,i=0;
arr=malloc(sizeof(int)*a);
for(k=0;*(s+k);k++)
{
*(arr+i)=1;
for(p=k+1;*(s+p);p++)
{
if(*(s+k)!='*'&&*(s+k)==*(s+p)){
*(s+p)='*';
*(arr+i)+=1;
}
}
if(i<a-1) i++;
else break;
}
return arr;
}
</code></pre>
<p>Some problems I face with my function:</p>
<p><strong>(i)</strong> How to use the function in an actual program, like receiving the returned integer pointer and printing values.</p>
<p><strong>(ii)</strong> I am changing the array element into <strong>"*"</strong> in second part of function. I want to avoid it.</p>
<p>I know that I've made a complex function difficult to comprehend.If there is a more optimized and simple solution, it would be helpful. </p>
<p>Thanks...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:05:22.990",
"Id": "447130",
"Score": "2",
"body": "This code is very difficult to review because it isn't indented properly. Is it possible for you to reformat the code? Your first problem makes the question off-topic because it lacks concrete context, and possibly because the code wasn't tested so it might be broken."
}
] |
[
{
"body": "<p><strong>Please</strong> improve the variable names - it's not at all obvious what <code>a</code>, <code>k</code> and <code>p</code> are (and conventionally, <code>p</code> is usually used for a small-scope pointer, not an integer).</p>\n\n<p><strong>Always</strong> check whether <code>malloc()</code> (or <code>calloc()</code>, or <code>realloc()</code>) returns a non-null pointer before dereferencing.</p>\n\n<p>The algorithm is so opaque that I'm not going to attempt to unravel it. It's nowhere near suitable for production use.</p>\n\n<p>BTW, it's misleading to claim that you don't use array indexing when there's clearly <code>*(arr+i)</code> in a couple of places and <code>*(s+p)</code> in a couple more. Just changing the syntax doesn't stop that being a cheat.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:06:49.090",
"Id": "447131",
"Score": "1",
"body": "I think the question is off-topic so I'm not sure an answer is appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:11:15.240",
"Id": "447132",
"Score": "1",
"body": "I felt there was enough to review, but it's not a strong conviction. Anyway, an answer won't stop the question being closed, so feel free to VTC there, @pacman"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:12:47.160",
"Id": "447133",
"Score": "0",
"body": "FYI, great review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:51:12.177",
"Id": "447178",
"Score": "2",
"body": "We should downvote this, but I'll make an exception https://codereview.meta.stackexchange.com/questions/8945/how-to-prevent-people-from-answering-off-topic-questions How else could this site see its first Lifeboat :p"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T14:05:32.750",
"Id": "229750",
"ParentId": "229749",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:56:57.153",
"Id": "229749",
"Score": "-5",
"Tags": [
"c",
"strings",
"pointers"
],
"Title": "Finding frequency of unique array elements by using single pointer"
}
|
229749
|
<h2>Problem Statement</h2>
<blockquote>
<p>Given an integer N, perform the following conditional actions:</p>
<ul>
<li>If N is odd, print Weird</li>
<li>If N is even and in the inclusive range of 2 to 5, print Not Weird</li>
<li>If N is even and in the inclusive range of 6 to 20, print Weird</li>
<li>If N is even and greater than 20, print Not Weird</li>
</ul>
<p>Complete the stub code provided in your editor to print whether or not
N is weird.</p>
<p><strong>Input Format:</strong> A single line containing a positive integer, N.</p>
<p><strong>Constraints:</strong> 1<=N<=100</p>
<p><strong>Output Format:</strong> Print Weird if the number is weird; otherwise, print
Not Weird.</p>
</blockquote>
<h2>My Solution</h2>
<pre><code>if(N%2!=0)
System.out.println("Weird");
else{
if(N>=2&&N<=5||N>20)
System.out.println("Not Weird");
else
System.out.println("Weird");
}
</code></pre>
<h2>Another Solution-</h2>
<pre><code>if(N%2==1)
System.out.println("Weird");
else
{
if(N>=2&&N<=5)
System.out.println("Not Weird");
else if(N<=20)
System.out.println("Weird");
else
System.out.println("Not Weird");
}
</code></pre>
<p>My question is, does one algorithm have better performance than the other, in other words, is there any advantage to using else if statements rather than logical operators. </p>
<p>P.S- I am new to coding in Java, and was just curious if there is an optimum way to write code that has better performance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T16:51:58.390",
"Id": "447153",
"Score": "1",
"body": "@dfhwze Thank you for the tip!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:01:20.720",
"Id": "447157",
"Score": "1",
"body": "_\"does one algorithm have better performance than the other\"_ No, any decent compiler would emit the same byte code for that."
}
] |
[
{
"body": "<p>As stated in the comments, this flow is simple enough for a compiler to optimize the code. So I wouldn't bother comparing performance between both methods. I would focus on readability and coding guidelines.</p>\n\n<h2>Conventions</h2>\n\n<p>You have customized formatting to somewhat align the <code>System.out.println</code> statements. While I consider this a form of art, it hurts readability. Keeping <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html\" rel=\"nofollow noreferrer\">conventions</a> in mind:</p>\n\n<ul>\n<li>A keyword followed by a parenthesis should be separated by a space.</li>\n<li>A blank space should not be used between a method name and its opening parenthesis.</li>\n<li>All binary operators except <code>.</code> should be separated from their operands by spaces.</li>\n<li>Be consistent in indentation size. Let's pick 4 characters.</li>\n<li>And a good reason to <a href=\"https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java\">prefer including curly braces</a> for if-statements.</li>\n</ul>\n\n\n\n<p>Solution 1</p>\n\n<pre><code>if (N % 2 != 0) {\n System.out.println(\"Weird\");\n}\nelse {\n if (N >=2 && N <= 5 || N > 20) {\n System.out.println(\"Not Weird\");\n }\n else {\n System.out.println(\"Weird\");\n }\n}\n</code></pre>\n\n<p>Solution 2</p>\n\n<pre><code>if (N % 2 == 1) {\n System.out.println(\"Weird\");\n}\nelse {\n if (N >= 2 && N <= 5) {\n System.out.println(\"Not Weird\");\n }\n else if (N <= 20) {\n System.out.println(\"Weird\");\n }\n else {\n System.out.println(\"Not Weird\");\n }\n}\n</code></pre>\n\n<p>Other formatting options might include using the <em>ternary operator</em> or combining conditions to only print each outcome once. I leave it up to you as an exercise to try these out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:20:53.720",
"Id": "229756",
"ParentId": "229753",
"Score": "2"
}
},
{
"body": "<p>In addition to the things dfhwze already mentioned:</p>\n\n<ol>\n<li>You should separate calculation and output. Even the shorter solution mentioned by dfhwze contains a repetition of the output code (<code>System.out.println</code>) and the output message (<code>\"Not weird\"</code>). Furthermore, thinking on to real world problems, code that only outputs something is really hard to unit-test.</li>\n</ol>\n\n<p>Thus, do something like:</p>\n\n<pre><code>private static boolean isWeird(int n) {\n return (n % 2 != 0) || (n >= 6 && n <= 20); // or however you want to do the calculation\n}\n\n... // and in main:\nboolean weird = isWeird(n);\nif (weird) {\n System.out.println(\"Weird\");\n}\nelse {\n System.out.println(\"Not Weird\");\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>One missing convention: variables should start with a lowecase character: <code>N</code> should be renamed to <code>n</code></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T07:52:48.307",
"Id": "229784",
"ParentId": "229753",
"Score": "3"
}
},
{
"body": "<p>Since you asked, I wouldn't think there would be any difference between using <code>else</code> vs <code>||</code>.</p>\n\n<p>But, related to that, and to add on to the other answers, is that code should normally be written for humans first, and only incidentally for computers.</p>\n\n<p>It takes only a bit of mental effort to reason that <code>(n % 2 != 0) || (n >= 6 && n <= 20)</code> fulfils the four bullet points given, but it's even easier to mentally verify that this code does, because it exactly mirrors the problem statement:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static boolean isWierd(int n) {\n\n if (n % 2 == 1) {\n return true;\n }\n\n if (2 <= n && n <= 5) {\n return false;\n }\n\n if (6 <= n && n <= 20) {\n return true;\n }\n\n return false;\n\n}\n</code></pre>\n\n<p>When somebody is hunting through thousands of lines to find where a bug enters the system, it might be that they're having to keep in their minds the state of a number of variables and the call stack, potentially for several different execution paths. It should be as simple as possible for them to look at the <code>isWierd</code> function, convince themselves that it is correct, and move on.</p>\n\n<p>And as with the other answers, the performance difference at this scale is likely to be either optimized away or be too small to matter (you can always come back to this if it does end up mattering). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T05:14:14.743",
"Id": "229890",
"ParentId": "229753",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T16:41:48.290",
"Id": "229753",
"Score": "2",
"Tags": [
"java",
"performance",
"beginner",
"comparative-review"
],
"Title": "Classifying integers as \"weird\" or \"not weird\""
}
|
229753
|
<h3>Merge Sort</h3>
<p>Merge Sort algorithm is a general-purpose comparison-based sorting algorithm.
Most implementations produce a stable sort, in which the order of equal elements is preserved.</p>
<hr>
<p>Just for practicing, I've implemented the merge sort algorithm copied below and I'd appreciate it if you'd like to review any part of it for any small or big changes/improvements.</p>
<h3>Code</h3>
<pre><code>from typing import List, TypeVar
import random
from scipy import stats
T = TypeVar("T")
def recursive_merge_sort(input_list: List[T]) -> List[T]:
"""
Recursive Merge Sort
-----------------------------------------------
Merge Sort is a Divide and Conquer algorithm.
It divides the input array in two halves,
calls itself for the two halves and then merges the two sorted halves.
The merge function is used for merging two halves.
Attributes:
- Time Complexity: O(N*Log N)
- Space Complexity: O(N)
- Stable Sort
"""
# Assigns the length of input list.
size_of_input_list = len(input_list)
# Creates a new list for sorted output list.
temp_output_list = [None] * size_of_input_list
# Sorts the input list.
recursive_sort(input_list, temp_output_list, 0, size_of_input_list - 1)
return temp_output_list
def recursive_sort(input_list: List[T], temp_output_list: List[T], first_index: int, last_index: int) -> List[T]:
"""
This method recursively sorts the divided sublists
"""
# Stops the recursion if there is only one element in the sublists.
if first_index == last_index:
return
# Otherwise, calculates the middle point.
mid_index = (first_index + last_index) // 2
# Then, calls the two sublists recursively.
recursive_sort(input_list, temp_output_list, first_index, mid_index)
recursive_sort(input_list, temp_output_list, mid_index + 1, last_index)
# Merges the two sublists.
merge_sublists(input_list, temp_output_list, first_index,
mid_index, mid_index + 1, last_index)
# Copies the sorted part into the temp_output_list.
copy_list(input_list, temp_output_list, first_index, last_index)
def merge_sublists(input_list: List[T], temp_output_list: List[T],
first_start_index: int, first_end_index: int,
second_start_index: int, second_end_index: int) -> List[T]:
"""
This method merges the two sorted sublists with three simple loops:
- If both sublists 1 and 2 have elements to be placed in the output merged list
- If sublists 1 has some elements left to be placed in the output merged list
- If sublists 2 has some elements left to be placed in the output merged list
e.g., sublist 1 [1, 3, 5, 7, 9]
e.g., sublist 2 [2, 4, 6, 8, 10, 12, 14]
- First while loop generates: [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10]
- Second while loop just passes, since no elements left from the first sublist.
- Third while loop generates: [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10, 12, 14]
"""
i = first_start_index
j = second_start_index
k = first_start_index
while i <= first_end_index and j <= second_end_index:
if input_list[i] <= input_list[j]:
temp_output_list[k] = input_list[i]
i += 1
else:
temp_output_list[k] = input_list[j]
j += 1
k += 1
while i <= first_end_index:
temp_output_list[k] = input_list[i]
i += 1
k += 1
while j <= second_end_index:
temp_output_list[k] = input_list[j]
j += 1
k += 1
def copy_list(input_list: List[T], temp_output_list: List[T], first_index: int, end_index: int) -> List[T]:
for i in range(first_index, end_index+1):
input_list[i] = temp_output_list[i]
if __name__ == "__main__":
# Creates a dash line string and a new line for in between the tests.
delimiter = "-" * 70 + "\n"
# Generates a random integer list.
TEST_LIST_INTEGER = random.sample(range(-100, 100), 15) * 3
print(f"""The unsorted integer array is:
{TEST_LIST_INTEGER}""")
print(delimiter)
# Generates a random float list.
TEST_LIST_FLOAT = stats.uniform(0, 100).rvs(45)
print(f"""The unsorted float array is:
{TEST_LIST_FLOAT}""")
print(delimiter)
# Sample float/integer test list for input.
INTEGER_FLOAT_INPUT = list(TEST_LIST_INTEGER + TEST_LIST_FLOAT)
# Sample float/integer test list for output.
INTEGER_FLOAT_OUTPUT = sorted(INTEGER_FLOAT_INPUT)
sorting_algorithms = [
("Recursive Merge Sort", recursive_merge_sort)
]
# Testing
for description, func in sorting_algorithms:
if (func(INTEGER_FLOAT_INPUT.copy()) == INTEGER_FLOAT_OUTPUT):
print(f"{description} Test was Successful.")
else:
print(f"{description} Test was not Successful.")
print(f"""{description} (Integer):
{func(TEST_LIST_INTEGER.copy())}""")
print(f"""{description} (Float):
{func(TEST_LIST_FLOAT.copy())}""")
print(delimiter)
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://www.geeksforgeeks.org/merge-sort/" rel="nofollow noreferrer">Merge Sort - Geeks for Geeks</a></li>
<li><a href="https://en.wikipedia.org/wiki/Merge_sort" rel="nofollow noreferrer">Merge Sort - Wiki</a></li>
</ul>
|
[] |
[
{
"body": "<h2>Type hints and the truth</h2>\n\n<pre><code>def recursive_sort(input_list: List[T], temp_output_list: List[T], first_index: int, last_index: int) -> List[T]:\n</code></pre>\n\n<p>This function actually returns <code>None</code>. Same with <code>merge_sublists</code> and <code>copy_list</code>.</p>\n\n<h2>Loop like a native</h2>\n\n<pre><code>while i <= first_end_index:\n temp_output_list[k] = input_list[i]\n i += 1\n k += 1\n</code></pre>\n\n<p>should at least be using <code>enumerate</code> on <code>input_list</code>, which will give you both <code>i</code> and the item from <code>input_list</code>. If you use the index from <code>enumerate</code> as an offset, you can avoid using <code>k</code> as well.</p>\n\n<p>All of that aside, you don't need to loop. Just do slice assignment; something like</p>\n\n<pre><code>temp_output_list[k: k+first_end_index-i] = input_list[i: i+first_end_index]\n</code></pre>\n\n<p>Many of your loops can use slices like that.</p>\n\n<h2>Variable names</h2>\n\n<p>No need to capitalize <code>INTEGER_FLOAT_INPUT</code> and similar lists. They aren't constants.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T15:19:51.730",
"Id": "447249",
"Score": "0",
"body": "Note that `input_list[i: i+first_end_index]` actually creates a copy of the slice of the input list. So it could sometimes lead to overhead in time / space usage. Meanwhile, using `itertools.islice` does not make copies but it would traverse from the beginning of the list until the starting index, therefore also adds overhead on running time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T02:11:22.040",
"Id": "229771",
"ParentId": "229754",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:16:57.990",
"Id": "229754",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"sorting",
"mergesort"
],
"Title": "Recursive Merge Sort Algorithm (Python)"
}
|
229754
|
<p>I have an HTTP endpoint for returning data directly from Azure Cosmos DB. The endpoint is basically a database access point (this seems like a common case). Since I'm returning the data unmodified, there's no need to deserialize it, even though I have an object for <code>Project</code> on the server that is used elsewhere. I'm wondering if there are any ways to make this code more efficient, or tighter.</p>
<pre class="lang-cs prettyprint-override"><code>[Route("")]
public async Task<IHttpActionResult> GetProjects()
{
await ValidateUser();
var cosmosDb = await Storage.GetCosmosDb();
var queryDefinition = new QueryDefinition($"SELECT * FROM projects project WHERE project.organization = '{CurrentUser.Organization}'");
var projectsQuery = cosmosDb.Containers[typeof(Project)]
.GetItemQueryStreamIterator(queryDefinition);
var projects = new JArray();
while (projectsQuery.HasMoreResults)
{
var responseMessage = await projectsQuery.ReadNextAsync();
if (!responseMessage.IsSuccessStatusCode)
{
return InternalServerError(new Exception(
$"Query item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}"));
}
using (var streamReader = new StreamReader(responseMessage.Content))
using (var jsonTextReader = new JsonTextReader(streamReader))
{
var project = JObject.Load(jsonTextReader);
((JArray)project["Documents"]).ForEach(projects.Add);
}
}
return Ok(projects);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T18:09:15.943",
"Id": "229758",
"Score": "2",
"Tags": [
"c#",
"http",
"asp.net-web-api",
"azure",
"azure-cosmosdb"
],
"Title": "Stream JSON from Azure Cosmos DB to browser in Web API"
}
|
229758
|
<p>I've been struggling to write a QuickSort algorithm to sort multiple columns of an Array for weeks. Finally, I decided to write a class that Implements mscorlib.IComparer and it has exceeded my expectations. </p>
<p>Ironically, my testing reveals that mscorlib.ArrayList itself uses a QuickSort algorithm. I concluded this by studying the order in which items were compared. </p>
<p><a href="https://drive.google.com/open?id=1JxlSHZMXhlM4S6ptXXVsOs5W07FC7LAt" rel="nofollow noreferrer">Download File</a></p>
<p>This code will add then mscorlib reference to your project. It is interesting that the reference description is <strong>Common Language Runtime Library</strong>.</p>
<blockquote>
<pre><code> ThisWorkbook.VBProject.References.AddFromGuid "{BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}", 1, 0
</code></pre>
</blockquote>
<p>This simple test demonstrates how to use the class.</p>
<pre><code>Sub SimpleTest()
' Initialize Sorter and add 3 columns with mixed Sort Orders
Dim Sorter As New DataManager
Sorter.AddColumn 3, xlDescending
Sorter.AddColumn 1, xlAscending
Sorter.AddColumn 4, xlAscending
' Fill Array of Values
Dim Values
Values = Range("A1").CurrentRegion.Value
' Test if the values are correctly sorted
Debug.Print "Before: "; Sorter.isSorted(Values:=Values, HasHeaders:=True)
'Actual Usage
Sorter.Sort Values:=Values, HasHeaders:=True
' Stop
' Test if the values are correctly sorted
Debug.Print "After: "; Sorter.isSorted(Values:=Values, HasHeaders:=True)
Workbooks.Add
Range("A1").Resize(UBound(Values), 4) = Values
End Sub
</code></pre>
<p>Class: DataManager</p>
<pre><code>Attribute VB_Name = "DataManager"
Attribute VB_PredeclaredId = False
Option Explicit
Implements mscorlib.IComparer
Private Type Members
Values As Variant
End Type
Private m As Members
Private Type ColumnParameters
ColumnIndex As Long
Compare As VbCompareMethod
SortOrder As XlSortOrder
End Type
Private Columns() As ColumnParameters
Private Type SortVariables
c As Long
Index As Long
r As Long
list As New ArrayList
Values As Variant
End Type
Private Type isSortedVariables
r As Long
result As Long
End Type
Public Sub AddColumn(ByVal ColumnIndex As Long, Optional ByVal SortOrder As XlSortOrder = xlAscending, Optional Compare As VbCompareMethod = VbCompareMethod.vbBinaryCompare)
If ColumnExists(ColumnIndex) Then
Err.Raise Number:=vbObjectError + 513, Description:="Column Exists"
End If
ReDim Preserve Columns(0 To ColumnCount)
With Columns(ColumnCount - 1)
.ColumnIndex = ColumnIndex
.Compare = .Compare
.SortOrder = SortOrder
End With
End Sub
Public Function ColumnExists(ByVal ColumnIndex As Long) As Boolean
Dim n As Long
For n = 0 To ColumnCount - 1
With Columns(n)
If .ColumnIndex = ColumnIndex Then
ColumnExists = True
Exit Function
End If
End With
Next
End Function
Private Function GetColumn(ByVal ColumnIndex As Long) As ColumnParameters
If ColumnExists(ColumnIndex) Then
Dim n As Long
For n = 0 To ColumnCount - 1
With Columns(n)
If .ColumnIndex = ColumnIndex Then
GetColumn = Columns(n)
Exit Function
End If
End With
Next
End If
End Function
Public Function IComparer_Compare(ByVal X As Variant, ByVal Y As Variant) As Long
Dim n As Long, result As Long
Dim s1 As Variant, s2 As Variant
For n = 0 To ColumnCount - 1
With Columns(n)
s1 = m.Values(X, .ColumnIndex)
s2 = m.Values(Y, .ColumnIndex)
If (IsDate(s1) And IsDate(s2)) Then
If DateValue(s1) < DateValue(s2) Then
result = -1
ElseIf DateValue(s1) > DateValue(s2) Then
result = 1
End If
ElseIf (IsNumeric(s1) And IsNumeric(s2)) Then
If Val(s1) < Val(s2) Then
result = -1
ElseIf Val(s1) > Val(s2) Then
result = 1
End If
Else
result = StrComp(s1, s2, .Compare)
End If
If .SortOrder = xlDescending Then result = result * -1
If result <> 0 Then Exit For
End With
Next
IComparer_Compare = result
End Function
Public Function isSorted(ByRef Values, Optional ByVal HasHeaders As Boolean) As Boolean
Dim h As isSortedVariables
m.Values = Values
For h.r = IIf(HasHeaders, LBound(Values) + 1, LBound(Values)) To UBound(Values) - 1
h.result = IComparer_Compare(h.r, h.r + 1)
If h.result > 0 Then
Erase m.Values
Exit Function
End If
Next
Erase m.Values
isSorted = True
End Function
Public Sub Sort(ByRef Values, Optional ByVal HasHeaders As Boolean)
m.Values = Values
Dim h As SortVariables
For h.Index = LBound(Values) To UBound(Values)
h.list.Add CStr(h.Index)
Next
h.list.Sort_2 Me
If HasHeaders Then
h.list.RemoveAt h.list.IndexOf(CStr(LBound(Values)), 0)
h.list.Insert 0, CStr(LBound(Values))
End If
ReDim h.Values(LBound(Values) To UBound(Values), LBound(Values, 2) To UBound(Values, 2))
For h.r = LBound(Values) To UBound(Values)
h.Index = h.list(h.r - 1)
For h.c = LBound(Values, 2) To UBound(Values, 2)
h.Values(h.r, h.c) = Values(h.Index, h.c)
Next
Next
Values = h.Values
Erase m.Values
End Sub
Public Sub ColumnClear()
Erase Columns
End Sub
Public Function ColumnCount() As Long
If (Not Not Columns) <> 0 Then ColumnCount = UBound(Columns) + 1
End Function
</code></pre>
<hr>
<h2>Module: UnitTest</h2>
<pre><code>Attribute VB_Name = "UnitTest"
Option Explicit
Public Enum OrderColumns
[Row ID] = 1
[Order ID]
[Order Date]
[Ship Date]
[Ship Mode]
[Customer ID]
[Customer Name]
[Segment]
[Country]
[City]
[State]
[Postal Code]
[Region]
[Product ID]
[Category]
[Sub-Category]
[Product Name]
[Sales]
[Quantity]
[Discount]
[Profit]
End Enum
Private DeleteTestWorkbooks As Boolean
Private Type TestResults
Description As String
ElaspseTime As String
n As Long
WasSorted As Boolean
Passed As Boolean
RowCount As Long
Sorter As New DataManager
Stopwatch As New Stopwatch
Values As Variant
End Type
Private Sub AddTestWorkbook(ByVal Description As String, Values)
Workbooks.Add
Range("A1").Value = Description
Range("A3").Resize(UBound(Values), UBound(Values, 2)).Value = Values
Columns.AutoFit
End Sub
Private Sub CloseActiveTestWorkbook()
If Len(ActiveWorkbook.Path) = 0 Then ActiveWorkbook.Close False
End Sub
Private Sub CloseTestWorkbooks()
Application.ScreenUpdating = False
Dim wb As Workbook
For Each wb In Workbooks
If Len(wb.Path) = 0 Then wb.Close False
Next
End Sub
Private Function getValues(ByVal RowCount As Long)
If RowCount = 0 Then
getValues = ThisWorkbook.Worksheets("Data").Range("A1").CurrentRegion.Value
Else
getValues = ThisWorkbook.Worksheets("Data").Range("A1").CurrentRegion.Resize(RowCount).Value
End If
End Function
Private Function GetTestResults(ByVal Description As String, ByVal RowCount As Long, DoAddTestWorkbook As Boolean, ParamArray ColumnOrderPairs()) As TestResults
Dim h As TestResults
h.Description = Description
Application.ScreenUpdating = False
For h.n = 0 To UBound(ColumnOrderPairs) - 1 Step 2
h.Sorter.AddColumn ColumnOrderPairs(h.n), ColumnOrderPairs(h.n + 1)
Next
h.Values = getValues(RowCount)
h.RowCount = UBound(h.Values)
h.WasSorted = h.Sorter.isSorted(h.Values, True)
h.Stopwatch.Start
h.Sorter.Sort h.Values, True
h.Stopwatch.Start
h.ElaspseTime = h.Stopwatch.ElaspseTimeToString(2)
h.Passed = h.Sorter.isSorted(h.Values, True)
If DoAddTestWorkbook Then AddTestWorkbook Description, h.Values
GetTestResults = h
End Function
Private Sub TestSorter(Optional ByVal RowCount As Long, Optional ByVal DoAddTestWorkbook As Boolean)
Const a = 12, b = 21, c = 33, d = 41
' RowCount = 0 will process all rows
Debug.Print
Debug.Print "RowCount"; Tab(a); "Time"; Tab(b); "Was Sorted"; Tab(c); "Passed"; Tab(d); "Description"
With GetTestResults("[Ship Date], xlAscending", RowCount, DoAddTestWorkbook, [Ship Date], xlAscending)
Debug.Print .RowCount; Tab(a); .ElaspseTime; Tab(b); .WasSorted; Tab(c); .Passed; Tab(d); .Description
End With
With GetTestResults("[Order Date], xlAscending, State, xlAscending, City, xlAscending", RowCount, DoAddTestWorkbook, [Order Date], xlAscending, State, xlAscending, City, xlAscending)
Debug.Print .RowCount; Tab(a); .ElaspseTime; Tab(b); .WasSorted; Tab(c); .Passed; Tab(d); .Description
End With
With GetTestResults("9,1,2,3,4,5,6,7,8", RowCount, DoAddTestWorkbook, 9, xlAscending, 1, xlAscending, 2, xlAscending, 3, xlAscending, 4, xlAscending, 5, xlAscending, 6, xlAscending, 7, xlAscending, 8, xlAscending)
Debug.Print .RowCount; Tab(a); .ElaspseTime; Tab(b); .WasSorted; Tab(c); .Passed; Tab(d); .Description
End With
End Sub
Private Sub TestTimes()
TestSorter "1,000", False
TestSorter "10,000", False
TestSorter "35,000", False
TestSorter "70,000", False
TestSorter 0, False
End Sub
</code></pre>
<h2>Results</h2>
<h2><a href="https://i.stack.imgur.com/D5d57.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D5d57.png" alt="Immediate Window"></a></h2>
<p>I am 99%c certain that the data is being sorted properly because the second UnitTest.TestSorter test is in the same order that I sorted the worksheet before I ran the test. It is also the only test that shows the data was sorted properly before applying DataManaget.Sort.</p>
<p>The worksheet was sort one column at a time in ascending order: City, State and Order Date. The columns are added in reverse order: Order Date, State, and City by design.</p>
<blockquote>
<pre><code>With GetTestResults("[Order Date], xlAscending, State, xlAscending, City, xlAscending", RowCount, DoAddTestWorkbook, [Order Date], xlAscending, State, xlAscending, City, xlAscending)
Debug.Print .RowCount; Tab(a); .ElaspseTime; Tab(b); .WasSorted; Tab(c); .Passed; Tab(d); .Description
End With
</code></pre>
</blockquote>
<p>As always, I would appreciate any feedback. Did I miss anything. Are my tests off? Is there a better way to test it?</p>
<blockquote class="spoiler">
<p> I'm sure that I will get some interesting comments on my use of custom Types to separate the variable declaration from the subroutine body. The idea comes from C++ usage of a header files. It is more an experiment than anything but I really really like it. The big advantage is that it reduces the variable declarations to a single simple declaration. The big drawback is it makes it hard to eliminate unused variables. Eh..I don;t know. Big declaration blocks suck and IMO declare as and where needed really suck. I'll probably get a million downvotes for this one. Ughh..Maybe I will get lucky and nobody will notice.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:27:14.070",
"Id": "229762",
"Score": "3",
"Tags": [
"vba",
"sorting"
],
"Title": "DataManager Class: Sorts Array by 1 or More Dynamically Added Columns in Ascending or Descending Order"
}
|
229762
|
<h3>Merge Sort</h3>
<p>Merge Sort algorithm is a general-purpose comparison-based sorting algorithm.
Most implementations produce a stable sort, in which the order of equal elements is preserved. </p>
<p>Here, our method is bottom-up merge sort algorithm, which treats the list as an array of <code>n</code> sublists of size 1, and iteratively doubles the size, sorts and merges the sublists.</p>
<hr>
<p>Just for practicing, I've implemented the iterative version of merge sort algorithm, copied below, and I'd appreciate it if you'd like to review any part of it for any small or big changes/improvements.</p>
<h3>Code</h3>
<pre><code>import random
from typing import TypeVar, List
from scipy import stats
T = TypeVar('T')
def iterative_merge_sort(input_list: List[T]) -> List[T]:
"""
Iterative Bottom Up Merge Sort
-----------------------------------------------
Merge Sort is a Divide and Conquer algorithm.
It divides the input array in two halves,
calls itself for the two halves and then merges the two sorted halves.
The merge function is used for merging two halves.
In this algorithm, we'd start from the smallest window size of 1
and double up the window size in each level until we'd reach to the
last level, which would be the size of input list.
Attributes:
- Time Complexity: O(N*Log N)
- In each level, there are O(N) comparisons
- There are O(Log N) levels
- Space Complexity: O(N) it is not an in-place sort
- Stable Sort
"""
# Assigns the length of input list.
size_of_input = len(input_list)
# Creates a new list for sorted output list.
temp_output_list = size_of_input * [None]
# Starts from the window size 1 and doubles up
window_size = 1
while window_size <= size_of_input - 1:
sort_in_level(input_list, temp_output_list, window_size, size_of_input)
window_size = 2 * window_size
return temp_output_list
def sort_in_level(input_list: List[T], temp_output_list: List[T],
window_size: int, size_of_input: int) -> List[T]:
"""
In this method we would assign four indices for start and end indices of two sublists:
- Starting Index for the first sublist
- Ending Index for the first sublist
- Starting Index for the second sublist
- Ending Index for the second sublist
Then, we'd do the divide and merge
"""
# Assigns the Starting Index of the first sublist to 0.
first_start_index = 0
while first_start_index + window_size <= size_of_input - 1:
first_end_index = first_start_index + window_size - 1
second_start_index = first_start_index + window_size
second_end_index = second_start_index + window_size - 1
# In case, the Second Ending Index went over the limit, which is the length of input list.
if second_end_index >= size_of_input:
second_end_index = size_of_input - 1
# Merges the two sublists
merge_sublists(input_list, temp_output_list, first_start_index,
first_end_index, second_start_index, second_end_index)
# Increments the Starting Index for the first sublist for the next sublist merging
first_start_index = second_end_index + 1
# In case, any other element would be left, it'd be placed in the temp output list
for i in range(first_start_index, size_of_input):
temp_output_list[i] = input_list[i]
# Copies to the sorted part of the output list.
copy_sorted_list(input_list, temp_output_list, size_of_input)
def merge_sublists(input_list: List[T], temp_output_list: List[T],
first_start_index: int, first_end_index: int,
second_start_index: int, second_end_index: int) -> List[T]:
"""
This method would merges the sublists using three simple while loops:
- In the first while, we'd continue until the min length in between the two sublists.
- In the second while, we'd continue if any element would be left from the sublist 1.
- In the third while, we'd continue if any element would be left from the sublist 2.
e.g., sublist 1 [1, 3, 5, 7, 9]
e.g., sublist 2 [2, 4, 6, 8, 10, 12, 14]
- First while loop generates: [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10]
- Second while loop just passes, since no elements left from the first sublist.
- Third while loop generates: [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10, 12, 14]
"""
# Assigns the Sublist 1 and temp output list indices (i, k)
i = k = first_start_index
# Assigns the Sublist 2 index (j)
j = second_start_index
# For if the size of smallest sublists:
while i <= first_end_index and j <= second_end_index:
# If the Sublist 1 element is smaller
if input_list[i] <= input_list[j]:
# Places the Sublist 1 element in the temp output list
temp_output_list[k] = input_list[i]
# Increments the Sublist 1
i += 1
else:
# Places the Sublist 2 element in the temp output list
temp_output_list[k] = input_list[j]
# Increments the Sublist 2
j += 1
# Increments the temp output list
k += 1
# For if any element would be left in Sublist 1
while i <= first_end_index:
# Copies the Sublist 1 element in the temp output list
temp_output_list[k] = input_list[i]
# Increments the Sublist 1
i += 1
# Increments the temp output list
k += 1
# For if any element would be left in Sublist 2
while j <= second_end_index:
# Copies the Sublist 2 element in the temp output list
temp_output_list[k] = input_list[j]
# Increments the Sublist 2
j += 1
# Increments the temp output list
k += 1
def copy_sorted_list(input_list, temp_output_list, size_of_input):
"""
This method copies the sorted temp output into the input list
"""
for i in range(size_of_input):
input_list[i] = temp_output_list[i]
if __name__ == "__main__":
# Creates a dash line string and a new line for in between the tests.
delimiter = "-" * 70 + "\n"
# Generates a random integer list.
TEST_LIST_INTEGER = random.sample(range(-100, 100), 15) * 3
print(f"""The unsorted integer array is:
{TEST_LIST_INTEGER}""")
print(delimiter)
# Generates a random float list.
TEST_LIST_FLOAT = stats.uniform(0, 100).rvs(45)
print(f"""The unsorted float array is:
{TEST_LIST_FLOAT}""")
print(delimiter)
# Sample float/integer test list for input.
INTEGER_FLOAT_INPUT = list(TEST_LIST_INTEGER + TEST_LIST_FLOAT)
# Sample float/integer test list for output.
INTEGER_FLOAT_OUTPUT = sorted(INTEGER_FLOAT_INPUT)
sorting_algorithms = [
("Iterative Merge Sort", iterative_merge_sort)
]
# Testing
for description, func in sorting_algorithms:
if (func(INTEGER_FLOAT_INPUT.copy()) == INTEGER_FLOAT_OUTPUT):
print(f"{description} Test was Successful.")
else:
print(f"{description} Test was not Successful.")
print(f"""{description} (Integer):
{func(TEST_LIST_INTEGER.copy())}""")
print(f"""{description} (Float):
{func(TEST_LIST_FLOAT.copy())}""")
print(delimiter)
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://www.geeksforgeeks.org/iterative-merge-sort/" rel="nofollow noreferrer">Iterative Merge Sort - Geeks for Geeks</a></li>
<li><a href="https://www.geeksforgeeks.org/merge-sort/" rel="nofollow noreferrer">Merge Sort - Geeks for Geeks</a></li>
<li><a href="https://en.wikipedia.org/wiki/Merge_sort" rel="nofollow noreferrer">Merge Sort - Wiki</a></li>
<li><a href="http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/7-Sort/merge-sort5.html" rel="nofollow noreferrer">The Bottom-up Merge Sort Algorithm - Emory</a></li>
</ul>
|
[] |
[
{
"body": "<p>Docstrings are not comments; they exist to help the caller properly use the method.</p>\n\n<p>Consider:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> import math\n>>> help(math.log)\nHelp on built-in function log in module math:\n\nlog(...)\n log(x, [base=math.e])\n Return the logarithm of x to the given base.\n\n If the base not specified, returns the natural logarithm (base e) of x.\n\n>>> \n</code></pre>\n\n<p>This tells me how to use the function. The method used to calculate the logarithm is unimportant. It could be using a Taylor-series expansion; dunno, don't care, and it didn't tell me.</p>\n\n<p>Now consider:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(iterative_merge_sort)\nHelp on function iterative_merge_sort in module __main__:\n\niterative_merge_sort(input_list: List[~T]) -> List[~T]\n Iterative Bottom Up Merge Sort\n -----------------------------------------------\n Merge Sort is a Divide and Conquer algorithm.\n It divides the input array in two halves,\n calls itself for the two halves and then merges the two sorted halves.\n The merge function is used for merging two halves.\n\n In this algorithm, we'd start from the smallest window size of 1\n and double up the window size in each level until we'd reach to the\n last level, which would be the size of input list.\n\n Attributes:\n - Time Complexity: O(N*Log N)\n - In each level, there are O(N) comparisons\n - There are O(Log N) levels\n - Space Complexity: O(N) it is not an in-place sort\n - Stable Sort\n\n>>> \n</code></pre>\n\n<p>Which parts of that help description are \"helpful\" to someone who wants to use this code?</p>\n\n<ul>\n<li><code>Iterative Bottom Up Merge Sort</code>? Nope - implementation detail.</li>\n<li><code>Merge Sort is a Divide and Conquer algorithm ... used for merging two halves.</code>? Nope - implementation details.</li>\n<li><code>In this algorithm ... the size of the input list</code>? Nope. Implementation details.</li>\n<li><code>Time Complexity: O(N*Log N)</code>? <strong>YES</strong>\n\n<ul>\n<li><code>In each level, there are O(N) comparisons</code>? Nope. Implementation detail.</li>\n<li><code>There are O(Log N) levels</code>? Nope. Implementation detail.</li>\n</ul></li>\n<li><code>Space Complexity: O(N) it is not an in-place sort</code>? <strong>YES</strong></li>\n<li><code>Stable Sort</code>? <strong>YES</strong></li>\n</ul>\n\n<p>Unanswered questions:</p>\n\n<ul>\n<li>Is the sorted list in ascending or descending order?</li>\n<li>Which comparison operation(s) must be defined on the elements?</li>\n</ul>\n\n<p>Docstring should be used to describe to the user how to use the method, any requirements or preconditions, and perhaps things like what time/space resources are required. Ie)</p>\n\n<pre><code>def iterative_merge_sort(input_list: List[T]) -> List[T]:\n \"\"\"\n Returns a new list of elements in ascending order; the input list is not modified.\n\n The list elements must implement the `<=` operator (`__le__`). The sort is stable;\n the order of elements which compare as equal will be unchanged.\n\n Complexity: Time: O(N*Log N) Space: O(N)\n \"\"\"\n</code></pre>\n\n<p>Implementation details, (which would be important for someone who is reviewing, maintaining or modifying the code) should be left as comments.</p>\n\n<hr>\n\n<p>See <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">sphinx-doc.org</a> for one utility which can extract <code>\"\"\"docstrings\"\"\"</code> to build documentation in HTML/PDF/HLP/... formats.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T22:46:58.357",
"Id": "229767",
"ParentId": "229765",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229767",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T21:57:45.363",
"Id": "229765",
"Score": "3",
"Tags": [
"python",
"beginner",
"algorithm",
"sorting",
"mergesort"
],
"Title": "Iterative Merge Sort Algorithm (Python)"
}
|
229765
|
<p>I've been on a <a href="https://projecteuler.net/archives" rel="nofollow noreferrer">Project Euler</a> spree and I've been solving problems and as you might know, many of them require you to use prime numbers. I've been using the following code to generate and store primes in a vector, but was wondering if there is any non-obvious speed-ups that will make a large difference on the runtime of the generation.</p>
<pre><code>// Generate the primes upto N using the Sieve of Eratosthenes.
template<typename T>
std::vector<T> generatePrimes(T n) {
std::vector<T> result = std::vector<T>();
if(n < 2) {
return result;
}
std::vector<int> input(n + 1, 1);
// Calculates the upper limit of the numbers to check.
T sqrtN = (T)sqrt(n);
// Iterate till the square root.
for(T i = 2; i <= sqrtN; i++) {
if(!input[i]) {
continue;
}
// Multiples are marked false.
for(T j = i * i; j <= n; j += i) {
input[j] = 0;
}
}
// Add to result vector.
result.push_back(2);
for(T i = 3; i <= n; i += 2) {
if(input[i]) {
result.push_back(i);
}
}
return result;
}
</code></pre>
<p>And it is called like so:</p>
<pre><code>vector<unsigned int> primes = generatePrimes<unsigned int>(10'000);
</code></pre>
<p>Is there any other way to speed this up? Before I had changed a line where I create the <code>input</code> vector to <code>int</code> from <code>bool</code> and it resulted in a nice 2.3x speed increase. <a href="http://quick-bench.com/W3TOPt110oMDAuy-29WldgqvOhc" rel="nofollow noreferrer">See here for benchmark.</a></p>
|
[] |
[
{
"body": "<p>A few things to consider:</p>\n\n<p>Is having the function generic really necessary? Why not just make the data type <code>unsigned long long</code> instead? This way you can do some bounds checking.</p>\n\n<p>I would suggest using a <code>bitset</code> to hold the raw data would be more efficient than using 32 bits to represent each 1 or 0.</p>\n\n<p>All primes are odd except for <code>2</code>. If you add <code>2</code> to the <code>result</code> vector, you can start the outer loop at 3 and increment by 2.</p>\n\n<p>Since the outer loop will only be odd numbers the start of the inner loop will also be odd. Therefore in order to keep hitting the odd number multiples you can increment by <code>i*2</code>.</p>\n\n<p>You can shorten the second loop by adding to the vector every time you find a prime in the outer loop. This way the second loop can start where the outer loop finishes.</p>\n\n<p>There is also another algorithm you can use that is more highly optimised for making a list of primes, mind you it's also more complicated( sorry I can't remember the name off hand)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T12:12:02.560",
"Id": "447224",
"Score": "0",
"body": "Could you please explain the second to last paragraph a bit? Having a bit of trouble parsing what you are trying to say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T12:31:25.410",
"Id": "447225",
"Score": "0",
"body": "Instead of starting the second loop at the beginning, use the outer loop to add all the primes up to sqrtN. The second loop starts at sqrtN + 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T16:29:14.490",
"Id": "447255",
"Score": "0",
"body": "The second loop as in the inner loop, or the second loop under the comment // Add to result vector?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T16:39:56.033",
"Id": "447256",
"Score": "0",
"body": "Also on the topic of `std::bitset` but iirc it was _slower_ to use than using a vector of primes, I tried it with `vector<bool>` which is implemented using `std::bitset` iirc. Also starting the second loop at sqrt(n) + 1 has no guarantee that it will be an odd number to start with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:55:06.413",
"Id": "447270",
"Score": "0",
"body": "@Rietty - Not the inner loop the second loop where the primes are added. You can use a simple one line algorithm to adjust the start to the next odd number(`x += (x+1)%2`). If `x` is even it will add 1 to make it odd, otherwise it will add 0 and leave it the same."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T02:41:14.937",
"Id": "229774",
"ParentId": "229768",
"Score": "4"
}
},
{
"body": "<p>You can make it go quite a bit faster by using wheel factorization to eliminate processing or storing multiples of small primes. As @tinstaaf said, you can easily eliminate the even numbers and deal with 2 as special case when you're almost done. </p>\n\n<p>You can consider an odds-only sieve as the first level of wheel factorization. A mod 6 wheel eliminate multiple of 2 and 3, a mod 30 wheel eliminates multiples of 2, 3, and 5, and is a sweet spot. If you look at numbers starting with 7 and skip multiples of 2, 3, and 5, only 8 out of the next 30 can possibly be prime. Since there are 8 bits in a byte, one byte can represent 30 prime candidates so you can squeeze a lot of data about primes into a small bit array. </p>\n\n<p>But prime wheels beyond odds-only are more complex. <a href=\"https://en.wikipedia.org/wiki/Wheel_factorization\" rel=\"nofollow noreferrer\">Wikipedia</a> has a good introduction to the subject.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:44:02.103",
"Id": "447280",
"Score": "0",
"body": "That implementation is a bit complicated to glean the basic concept of, but I'll look more into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T13:32:43.727",
"Id": "448684",
"Score": "0",
"body": "@Rietty you're right about the complexity of Kim's primesieve. [Wikipedia](https://en.wikipedia.org/wiki/Wheel_factorization) has a better intoduction to wheel factorization. But if your totally obsessed with the subject like me at the moment, Kim Walish's doc on the algorithms is fantastic, in my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T13:42:56.633",
"Id": "448686",
"Score": "0",
"body": "@Rietty edited my answer above to provide the Wikipedia link. It's too late to change my comment :-/ I'm still very much a code review noob."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:00:48.967",
"Id": "229817",
"ParentId": "229768",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T00:35:31.343",
"Id": "229768",
"Score": "1",
"Tags": [
"c++",
"primes",
"c++17",
"sieve-of-eratosthenes"
],
"Title": "Optimizing the Sieve of Eratosthenes for prime generation"
}
|
229768
|
<p>I'd like to learn how I can optimize the following byte extension methods. </p>
<p>I'm targeting .NET Standard 2.0 but I'm curious if there are any ways to go about some of this functionality using features available in 2.1 (like <code>Span<T></code>).</p>
<p>I feel like the <code>ShiftRight</code>, <code>byte.HasSamePrefix</code>, <code>byte[].HasSamePrefix</code> methods could be improved.</p>
<pre><code>using System;
namespace SharpTorrent.Dht.Extensions
{
/// <summary>
/// This class provides static extension methods for the byte type.
/// </summary>
public static class ByteExtensions
{
/// <summary>
/// Determine if the bit at the provided index is set (indexed from left-to-right).
/// </summary>
/// <param name="value">The byte whose index to check.</param>
/// <param name="index">The bit index to check.</param>
/// <returns>The mutated byte value</returns>
public static bool IsBitSetAtIndex(
this byte value
, byte index
) => index > 7
? throw new IndexOutOfRangeException("Index must be between 0 and 7 inclusive.")
: (value & (1 << 7 - index)) != 0;
/// <summary>
/// Set the bit value at the provided index (indexed from left-to-right).
/// </summary>
/// <param name="value">The byte value whose bit to set.</param>
/// <param name="index">The index of the bit to set.</param>
/// <returns>The mutated byte value</returns>
public static byte SetBitAtIndex(
this byte value
, byte index
) => index > 7
? throw new IndexOutOfRangeException("Index must be between 0 and 7 inclusive.")
: (byte) (value | (1 << 7 - index));
/// <summary>
/// Clear the bit value at the provided index (indexed from left-to-right).
/// </summary>
/// <param name="value">The byte value whose bit to clear.</param>
/// <param name="index">The index of the bit to clear.</param>
/// <returns>The mutated byte value</returns>
public static byte ClearBitAtIndex(
this byte value
, byte index
) => index > 7
? throw new IndexOutOfRangeException("Index must be between 0 and 7 inclusive.")
: (byte) (value & ~(1 << 7 - index));
/// <summary>
/// Toggle the bit value at the provided index (indexed from left-to-right).
/// </summary>
/// <param name="value">The byte value whose bit to toggle.</param>
/// <param name="index">The index of the bit to toggle.</param>
/// <returns>The mutated byte value</returns>
public static byte ToggleBitAtIndex(
this byte value
, byte index
) => index > 7
? throw new IndexOutOfRangeException("Index must be between 0 and 7 inclusive.")
: (byte) (value ^ (1 << 7 - index));
/// <summary>
/// Shift the bits of the provided byte array right by the provided distance. Bits will shift across byte
/// boundaries in the array. Zero will be shifted in from the left. The sign of the byte array isn't considered.
/// </summary>
/// <param name="bytes">The byte array to shift.</param>
/// <param name="distance">The distance to shift the bits.</param>
/// <returns>The shifted byte array.</returns>
public static byte[] ShiftRight(
this byte[] bytes
, uint distance = 1
)
{
// For each index distance to shift the bits.
for (var d = 0; d < distance; d++)
{
// For every byte in the array (MSB <- LSB).
for (var i = bytes.Length - 1; i >= 0; i--)
{
// Shift the current index right by one bit.
bytes[i] = (byte) (bytes[i] >> 1);
// Set the most significant bit if necessary.
if (i >= 1 && (bytes[i - 1] & 0x01) != 0)
{
bytes[i] |= (byte) (bytes[i] | 0x80);
}
}
}
return bytes;
}
/// <summary>
/// Mask off the the nth bit position of the byte starting from the left. Indexing is 0-based.
///
/// e.g. A value of 0xFF will produce the following:
///
/// 11111111 (0) -> 01111111
/// 11111111 (1) -> 00111111
/// 11111111 (2) -> 00011111
/// 11111111 (3) -> 00001111
/// 11111111 (4) -> 00000111
/// 11111111 (5) -> 00000011
/// 11111111 (6) -> 00000001
/// 11111111 (7) -> 00000000
/// </summary>
/// <param name="value">The byte to mask.</param>
/// <param name="maskIndex"></param>
/// <returns>The masked byte value.</returns>
public static byte MaskLeft(this byte value, byte maskIndex) => (byte) (value & (0xFF >> (maskIndex + 1)));
/// <summary>
/// Mask off the the nth bit position of the byte starting from the right. Indexing is 0-based.
///
/// e.g. A value of 0xFF will produce the following:
///
/// 11111111 (0) -> 11111110
/// 11111111 (1) -> 11111100
/// 11111111 (2) -> 11111000
/// 11111111 (3) -> 11110000
/// 11111111 (4) -> 11100000
/// 11111111 (5) -> 11000000
/// 11111111 (6) -> 10000000
/// 11111111 (7) -> 00000000
/// </summary>
/// <param name="value"></param>
/// <param name="maskIndex"></param>
/// <returns></returns>
public static byte MaskRight(this byte value, byte maskIndex) => (byte) (value & (0xFF << (maskIndex + 1)));
/// <summary>
/// Determine if two bytes share a common prefix from left-to-right. Indexing is 0-based.
/// </summary>
/// <param name="value">The first value.</param>
/// <param name="second">The value to compare against.</param>
/// <param name="bitIndex">The prefix index to check up to.</param>
/// <returns>Whether or not the two bytes share a matching prefix.</returns>
/// <exception cref="IndexOutOfRangeException">Thrown when a bit index greater than 7 is provided.</exception>
public static bool HasSamePrefix(this byte value, byte second, byte bitIndex)
{
if (bitIndex > 7)
{
throw new IndexOutOfRangeException("Index must be between 0 and 7 inclusive.");
}
if (bitIndex == 7)
{
return value.IsBitSetAtIndex(7) == second.IsBitSetAtIndex(7);
}
var maskIndex = (byte) (6 - bitIndex);
return value.MaskRight(maskIndex) == second.MaskRight(maskIndex);
}
/// <summary>
/// Determine if the byte arrays share a common prefix from left-to-right. Indexing is 0-based.
/// </summary>
/// <param name="first">The first byte array.</param>
/// <param name="second">The byte array to compare against.</param>
/// <param name="bitIndex">The bit index to check up to.</param>
/// <returns></returns>
/// <exception cref="IndexOutOfRangeException">
/// Thrown when the bit index is greater than the number of bits in the smallest byte array.
/// </exception>
public static bool HasSamePrefix(
this byte[] first
, byte[] second
, int bitIndex
)
{
var maxIndex = Math.Min(first.Length, second.Length) - 1;
var endByteIndex = bitIndex / 8;
var byteIndex = 0;
if (endByteIndex > maxIndex)
{
throw new IndexOutOfRangeException("Bit index exceeds bit index of smallest array.");
}
for (; byteIndex < endByteIndex; byteIndex++)
{
if (first[byteIndex] != second[byteIndex])
{
return false;
}
}
return first[byteIndex].HasSamePrefix(
second[byteIndex]
, (byte) (7 - bitIndex % 8)
);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:39:02.160",
"Id": "447976",
"Score": "1",
"body": "I have rolled back your last edit. Please do not add the updated code to the question as it's getting confusing this way. You should post a self-answer instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:43:04.453",
"Id": "447977",
"Score": "0",
"body": "This updated code was @harold solution but cleaned up. I want to avoid taking credit for someone else's answer. I think removing the code actually hurts others who are looking for a solution as now they must roll their own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:45:04.150",
"Id": "447978",
"Score": "1",
"body": "Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) - _**Do not add an improved version of the code** after receiving an answer. Including revised versions of the code makes the question confusing, especially if someone later reviews the newer code._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:45:59.667",
"Id": "447979",
"Score": "1",
"body": "_**Posting a self-answer.** If you want to show everyone how you improved your code, but don't want to ask another question, then post an answer to your own question. Self-answers are acceptable on Stack Exchange sites, and even encouraged_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:46:28.190",
"Id": "447980",
"Score": "0",
"body": "Okay, thank you for the reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:17:29.077",
"Id": "447997",
"Score": "1",
"body": "BTW about the now removed code, I'm pretty sure you *can't* skip zeroing out the \"top\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:25:03.297",
"Id": "447998",
"Score": "0",
"body": "Yikes, I missed this. My unit test was to shift a single true bit across from left to right and assert the value is true at the new position. It's not checking that all other bits are zeroed out. I'll need to fix this and add that test. Thanks!"
}
] |
[
{
"body": "<p><code>ShiftRight</code> does not need to be a series of shift-by-1 operations.</p>\n\n<p>An other approach is:</p>\n\n<ol>\n<li>shift whole bytes, by a distance of <code>distance / 8</code></li>\n<li>shift the bytes by <code>distance % 8</code>, while shifting in bits from the next byte</li>\n</ol>\n\n<p>I have to be a little careful here because you used an unsual byte order (lowest order byte <em>last</em>) and you're doing this in-place. Here's an attempt (not debugged):</p>\n\n<pre><code>// move bytes to shift by multiples of 8\nint byteDistance = (int)(distance / 8);\nfor (int i = bytes.Length - 1; i >= byteDistance; i--)\n{\n bytes[i] = bytes[i - byteDistance];\n}\n// zero out the \"top\" of the array\nfor (int i = byteDistance - 1; i >= 0; i--)\n{\n bytes[i] = 0;\n}\n\n// bit-granular shift by the remainder of the distance\nint bitShift = (int)(distance % 8);\nfor (int i = bytes.Length - 1; i >= 1; i--)\n{\n int twoBytes = bytes[i] | (bytes[i - 1] << 8);\n bytes[i] = (byte)(twoBytes >> bitShift);\n}\nbytes[0] >>= bitShift;\n</code></pre>\n\n<p>Some variants may be interesting:</p>\n\n<ul>\n<li>The last loop can iterate less, stopping at the part of the array that was left zero by the byte-granular shift.</li>\n<li>The last loop could be unrolled, packing more bytes into an <code>int</code> and making \"better use\" of the integer shift. </li>\n<li>With <code>Span<T></code> and primarily targeting 64bit, we could <code>MemoryMarshal.Cast</code> the <code>Span<byte></code> to an <code>Span<uint></code>, then do a similar thing as above but with two <code>uint</code> in an <code>ulong</code> rather than two <code>byte</code> in an <code>int</code>. It takes some care with arrays with length not a multiple of 4, of course.</li>\n</ul>\n\n<p>Notable <em>non</em>-possibility:</p>\n\n<ul>\n<li>An other new thing in Standard 2.1 thing is <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.numerics.vector?view=netstandard-2.1\" rel=\"nofollow noreferrer\">System.Numerics.Vector</a>, but it still lacks bit-shifts (I've heard they will probably be added someday), so it can't be used for this, even though the hardware can do it.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T00:36:25.417",
"Id": "447410",
"Score": "0",
"body": "Oh, thank you for sharing your solution. I spent hours looking at this method and would've never thought to combine bytes using an int or shift over multiples of 8. I stepped through it on paper the other night and it makes perfect sense. Thank you for also expanding on variations and for going into Vector and Span."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T12:06:16.140",
"Id": "229794",
"ParentId": "229770",
"Score": "3"
}
},
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>The postfix <code>AtIndex</code> is too verbose. You don't have any other operations like <code>AtMask</code> or anything and the <code>index</code> is provided as argument. So I would prefer <code>IsBitSet</code> over <code>IsBitSetAtIndex</code> etc.</li>\n<li>The index is sometimes a <code>byte</code>, sometimes a <code>uint</code>. I would not bother with such level of (over-)engineered type picks. Stick with the common type for an index <code>int</code>. You can always add argument checks for bounds.</li>\n<li>You can replace <code>1 << 7 - index</code> with <code>1 << index</code> in your operations. This is written more compactly and is a well known bit operation technique. Right-to-left indexes are more common in bitwise systems.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T05:37:58.443",
"Id": "447319",
"Score": "0",
"body": "Thank you for your feedback. I've implemented your first two recommended changes. As for the third recommendation, given an index of 0 would produce the following `1 << 7 - 0` (10000000) and `1 << 0` (00000001). My intention was for bits to be indexed from left-to-right. For example, in the method `IsBitSet` providing an index of 0 would check if the first bit on the left side of the byte is set. Is it more common to index from right-to-left when dealing with bitwise operations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T07:37:52.923",
"Id": "447325",
"Score": "2",
"body": "I did expect right-to-left: https://math.stackexchange.com/questions/891445/why-binary-is-read-right-to-left. But if you want to change the direction, I don't see a real issue. Just make sure to document your specification."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:23:32.353",
"Id": "229797",
"ParentId": "229770",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229794",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T01:58:38.920",
"Id": "229770",
"Score": "3",
"Tags": [
"c#",
"bitwise",
".net-2.0"
],
"Title": "Byte extension methods for common bitwise operations"
}
|
229770
|
<p>QuickSort is a Divide and Conquer algorithm, which picks an element as "pivot" and partitions a given list around the pivot. There are many different versions of Quick Sort, as to how to pick a pivot in different ways: </p>
<ul>
<li>Always pick first element as pivot (implemented below)</li>
<li>Always pick last element as pivot</li>
<li>Pick a random element as pivot</li>
<li>Pick median as pivot</li>
</ul>
<hr>
<p>Just for practicing, I've implemented the quick sort algorithm, and if you'd like to review it and provide any change/improvement recommendations, please do so, and I appreciate that.</p>
<h3>Code</h3>
<pre><code>import random
from typing import TypeVar, List
from scipy import stats
T = TypeVar('T')
def quick_sort(input_list: List[T]) -> List[T]:
""""
Returns an ascendingly sorted list;
Input variable is an integer or float array;
Theoretical Complexity: O(N*Log N) Time and O(N) Memory
"""
sort(input_list, 0, len(input_list) - 1)
return input_list
def sort(input_list: List[T], start_index: int, end_index: int) -> None:
"""Recursively sorts the two pivot-divided sublists;"""
if start_index >= end_index:
return
pivot_index = partition(input_list, start_index, end_index)
sort(input_list, start_index, pivot_index - 1)
sort(input_list, pivot_index + 1, end_index)
def partition(input_list: List[T], start_index: int, end_index: int) -> int:
"""
Returns the end index; Partitions a list into two sublists;
"""
pivot = input_list[start_index]
i, j = start_index + 1, end_index
while i <= j:
while input_list[i] < pivot and i < end_index:
i += 1
while input_list[j] > pivot:
j -= 1
if i < j:
temp = input_list[i]
input_list[i] = input_list[j]
input_list[j] = temp
i += 1
j -= 1
else:
break
input_list[start_index] = input_list[j]
input_list[j] = pivot
return j
if __name__ == "__main__":
# Creates a dash line string and a new line for in between the tests.
delimiter = "-" * 70 + "\n"
# Generates a random integer list.
test_list_integer = random.sample(range(-100, 100), 15) * 3
print(f"""The unsorted integer array is:
{test_list_integer}""")
print(delimiter)
# Generates a random float list.
test_list_float = stats.uniform(0, 100).rvs(45)
print(f"""The unsorted float array is:
{test_list_float}""")
print(delimiter)
# Sample float/integer test list for input.
integer_float_input = list(test_list_integer + test_list_float)
# Sample float/integer test list for output.
integer_float_output = sorted(integer_float_input)
sorting_algorithms = [
("Quick Sort", quick_sort)
]
# Testing
for description, func in sorting_algorithms:
if (func(integer_float_input.copy()) == integer_float_output):
print(f"{description} Test was Successful.")
else:
print(f"{description} Test was not Successful.")
print(f"""{description} (Integer):
{func(test_list_integer.copy())}""")
print(f"""{description} (Float):
{func(test_list_float.copy())}""")
print(delimiter)
</code></pre>
<h3>Reference</h3>
<ul>
<li><a href="https://www.geeksforgeeks.org/quick-sort/" rel="nofollow noreferrer">Quick Sort - Geeks for Geeks</a></li>
<li><a href="https://en.wikipedia.org/wiki/Quicksort" rel="nofollow noreferrer">Quick Sort - Wiki</a></li>
</ul>
|
[] |
[
{
"body": "<p>I'm all for providing <em>docstring</em>s.<br>\nI doubt the docstrings presented are helpful as can be for someone not familiar with the quicksort algorithm:</p>\n\n<ul>\n<li><p><em>Returns an ascendingly sorted list;</em><br>\nis this a new one or the one provided as input?<br>\n(A method docstring should start with <a href=\"https://www.python.org/dev/peps/pep-0257/#id16\" rel=\"nofollow noreferrer\"><code>a phrase ending in a period [prescribing the] method's effect as a command (\"Do this\", \"Return that\"), not as a description</code></a>)</p></li>\n<li><p><em>Input variable is an integer or float array;</em><br>\ndoesn't it work for strings?<br>\nthe <a href=\"https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences\" rel=\"nofollow noreferrer\">python tutorial</a> names <em>list</em>s and <em>tuple</em>s as <code>standard sequence data type</code>s - what <em>is</em> an <a href=\"https://docs.python.org/3/library/array.html#module-array\" rel=\"nofollow noreferrer\"><code>array</code></a>?<br>\n(The type hint does give a hint as to the intended meaning - I do not have a helpful intuition about python type hinting in general and \"interaction\" with docstrings in particular.)</p></li>\n<li><p><em>Theoretical Complexity: O(N×Log N) Time and O(N) Memory</em><br>\nWithout further qualification of the bounds claimed, I expect them to be worst case bounds.</p></li>\n<li><p><em>Recursively sorts the two pivot-divided sublists;</em><br>\nlooking at the method interface, only, I don't see <em>two sublists</em><br>\n(which happens to be the first thing I hope for in a method docstring - <a href=\"https://www.python.org/dev/peps/pep-0257/#id17\" rel=\"nofollow noreferrer\"><code>The docstring for a function or method should summarize its behavior and document its arguments, …</code></a> does not stress this.)</p></li>\n</ul>\n\n<p>There are several things not quite <em>pythonic</em> in the code presented</p>\n\n<ul>\n<li>a swap of <code>a</code> and <code>b</code> is typically denoted using implied lists:<br>\n<code>a, b = b, a</code></li>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#common-sequence-operations\" rel=\"nofollow noreferrer\">Concatenating immutable sequences always results in a new object</a> of the same type as both sequences (the type of the first operand if not same types(?)) - not seeing the intention in enclosing <code>test_list_integer + test_list_float</code> in <code>list()</code></li>\n</ul>\n\n<p>I prefer </p>\n\n<pre><code>if not <condition>:\n <get out of here>\n<operate>\n</code></pre>\n\n<p>over</p>\n\n<pre><code>if <condition>:\n <operate>\nelse:\n <get out of here>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T12:34:55.570",
"Id": "447226",
"Score": "0",
"body": "I'd stress the first point even more by saying that a return value imply a new object, since modifying it in place does not invalidate the reference held by the caller. But here, the input is modified in place AND returned, which is confusing at best if not error prone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:41:17.017",
"Id": "447244",
"Score": "0",
"body": "*Concatenating immutable sequences always results in a new object* This also applies to lists, which is the case here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T05:08:44.533",
"Id": "229777",
"ParentId": "229772",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T02:34:15.737",
"Id": "229772",
"Score": "3",
"Tags": [
"python",
"beginner",
"algorithm",
"sorting",
"quick-sort"
],
"Title": "Quick Sort Algorithm (Python)"
}
|
229772
|
<p>I wrote a FizzBuzz program to get comfortable with C++. I haven't learned any languages before this, but I'm doing this on my own. I learned <code>if</code>, <code>for</code>, <code>std::cout</code>, and some operators. I wrote several questions below, but if that isn't allowed I can revise.</p>
<p>Program uses nested for loops to evaluate whether a quotient is a equivalent to an integer.</p>
<p>Questions</p>
<ol>
<li><p>Any problems with my variable names? Commenting? White space usage?</p></li>
<li><p>Instead of evaluating comparisons every time the main counter increments, would it be faster to store all possible increments in a "list" of some kind and then do my comparisons with elements in that list? Collating multiples of multiples within a list would require searching for that element within a list, which could be costly.</p></li>
<li><p>Would a straight forward counting approach or a list approach be faster for <em>n</em> counter values greater than a few digits? i.e. finding all multiples up to 100,000 or 1,000,000.</p></li>
<li><p>I realize after writing this that I could have used modulus <code>%</code>. However, modulus would only account for integer multiples, correct? (i.e. I would not be able to use "3.5" as one of my multiples.)</p></li>
<li><p>To add to the above, I want to run this algorithm using floats instead of integers (e.g. multiples of fractions, or PI to several digits out), and I want to count out to some arbitrary limit using appropriate intervals (e.g. +0.5, +0.001). Regardless of my approach, are these types of evaluations inextricably linked to issues with float precision (imprecision)?</p></li>
<li><p>This question is off-topic (sorry), but how much of a problem in coding is the issue of organization in code? I ask because I didn't need to use the variables <code>int passFizz</code> and <code>int passBuzz</code> because I could have used <code>int checkFizzBuzz</code> in their places instead. However, if I were to add dozens of multiples to check for, I'd think that using a single global variable would be organizationally poor.</p></li>
</ol>
<pre><code>#include <iostream>
// Prints numbers "1" through "100" as integers.
// Every multiple of "3" is printed as "Fizz".
// Every multiple of "5" is printed as "Buzz".
// Every common multiple of "3" and "5" is printed as "FizzBuzz".
// for loops evaluate whether a quotient is an integer.
int main()
{
float counterMain = 1;
// factorMain will be set to the multiples for Fizz or "Buzz.
float factorMain = 0;
// factorTest "tests" factorMain to see if it is an integer factor of counterMain.
float factorTest = 1;
// factorLimit sets the divisor (factor) upper limit (only one other factor in this case).
// factorLimit is a quotient of factorMain and factorTest.
float factorLimit = 0;
int passFizz = 0;
int passBuzz = 0;
// counterMain gets printed at the end if nothing is passed to checkFizzBuzz.
for(counterMain = 1; counterMain <= 100; ++counterMain)
{
// Resets pass check.
passFizz = 0;
passBuzz = 0;
// "Fizz" value set here.
factorMain = 3;
// Sets the divisor upper limit as a quotient of counterMain.
factorLimit = counterMain / factorMain;
//factorTest counts to the divisor upper limit.
for(factorTest = 1; factorTest <= factorLimit; ++factorTest)
{
// Tests if factorTest is an integer quotient of counterMain divided by factorMain.
if(factorTest == factorLimit)
{
// Passes 1 to passFizz if factorMain is an integer.
passFizz = 1;
// Sets factorTest to for loop exit condition.
factorTest = factorLimit;
}
}
// "Buzz" value is set here.
factorMain = 5;
factorLimit = counterMain / factorMain;
// Copy of the above for loop but passes 2 to passBuzz instead.
for(factorTest = 1; factorTest <= factorLimit; ++factorTest)
{
if(factorTest == factorLimit)
{
passBuzz = 2;
factorTest = factorLimit;
}
}
// Fizz-Buzz pass check, then prints out.
int checkFizzBuzz = (passFizz + passBuzz);
// Value of 0 means no factors were found, prints counterMain value instead.
if(checkFizzBuzz == 0)
{
std::cout << counterMain;
}
if(checkFizzBuzz == 1)
{
std::cout << "Fizz";
}
if(checkFizzBuzz == 2)
{
std::cout << "Buzz";
}
if(checkFizzBuzz == 3)
{
std::cout << "FizzBuzz";
}
std::cout << "\n";
// Return to counterMain for loop.
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T06:41:15.850",
"Id": "447201",
"Score": "0",
"body": "Program is far more complicated than it needs to be. Did you check its output? Does it run correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T06:43:31.173",
"Id": "447202",
"Score": "0",
"body": "`I realize after writing this that I could have used modulus %. However, modulus would only account for integer multiples, correct? (i.e. I would not be able to use \"3.5\" as one of my multiples.)` You realize that point of FizzBuzz is to give a simple test to screen out programmers who can't code at all? Your added complication seems to miss that point entirely. https://blog.codinghorror.com/why-cant-programmers-program/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T07:35:20.630",
"Id": "447205",
"Score": "1",
"body": "@markspace Some people like to make it a bit more interesting, nothing wrong with that. Wrote an [overly complicated version](https://codereview.stackexchange.com/q/91651/52915) myself once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:25:18.693",
"Id": "447277",
"Score": "0",
"body": "@markspace All questions to Code Review must contain working code. There are a number of online compilers to test with. See https://stackoverflow.com/questions/567682/online-compilers-runtime-for-java-c-python-and-objc."
}
] |
[
{
"body": "<p>The first thing I'd suggest is to learn to put algorithms in separate functions. This allows your maintenance to be much simpler. If a change is needed, as long as the parameters and the return type don't change, you don't have to worry about the rest of the program.</p>\n\n<p>If you want to use different types with your algorithm, one way to go is to use generics. The main caveat to this is that checking that the type used is appropriate(i.e. using strings would throw an error), becomes very complicated.</p>\n\n<p>One of the most common mistakes people who are learning this algorithm make, is checking 3 times, once for each factor then both factors combined. if you check for both factors back to back this will automatically give you the combined factor.</p>\n\n<p>You are using <code>int</code> to indicate a valid factor. It would make more sense to use a <code>bool</code>.</p>\n\n<p>Putting it all together, it can be simplified very greatly. Something like this would work:</p>\n\n<pre><code>template<typename T>\nvoid FizzBuzz(T start, T end, T factor1, T factor2, T step)\n{\n for (T i = start; i < end; i += step)\n {\n bool fizz = (i % factor1) == 0;\n bool buzz = (i % factor2) == 0;\n if (!fizz && !buzz)\n {\n cout << i << '\\n';\n }\n else\n {\n if (fizz)\n {\n cout << \"Fizz\";\n }\n if (buzz)\n {\n cout << \"Buzz\";\n }\n cout << '\\n';\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T22:09:32.347",
"Id": "447305",
"Score": "0",
"body": "I agree that finding a way to use my algorithm as a template would be organizationally simpler.\n\nI would like to add that the cost-benefit curve for checking two factors at once falls below the curve for checking factors independently, the greater the counting number becomes (e.g. counting to 1,000,000). This algorithm uses a per-factor divisor upper limit to reduce the number needed to count to. However, I agree that adding more to-be-checked factors would require a case-by-case analysis."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T22:14:15.140",
"Id": "447306",
"Score": "0",
"body": "While `bool` seems preferred to my summed `int` approach, wouldn't the return \"all are zero\" `(!fizz && !buzz)` be more efficient at run time if it were coded as discrete evaluations? Isn't my initial approach of listing named variables considered essentially the same as discretely listing elements in a list, outside of list form? \nDoes the `else` have value here? The following `if`s will run anyway since boolean comparisons can only evaluate to either `true` or `false`, therefore the following statements will run as if the previous `if` had passed `0` anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:37:20.980",
"Id": "229815",
"ParentId": "229778",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T05:12:16.517",
"Id": "229778",
"Score": "3",
"Tags": [
"c++",
"performance",
"beginner",
"fizzbuzz"
],
"Title": "Beginner FizzBuzz"
}
|
229778
|
<p>I programmed a few things in java and now I'm learning C#. I've been doing exercises from Codility.</p>
<p>The first 3 or 4 were very difficult to me but now I guess I've got the hang of it. This site helped a lot at improving my style and the things I now think I should be looking at before contenting myself with the final code. I comment a lot less than previous posts because I guess the names and the constants are self explanatory. </p>
<ul>
<li>Are there still things to improve in my code in easy exercises like this?</li>
</ul>
<p>Task score: 100%</p>
<p>Detected time complexity: $O(N)\$</p>
<blockquote>
<p><strong><em>Task description</em></strong></p>
<hr>
<p>A non-empty array A consisting of N integers is given. The consecutive
elements of array A represent consecutive cars on a road.</p>
<p>Array A contains only 0s and/or 1s:</p>
<p>0 represents a car traveling east, 1 represents a car traveling west.
The goal is to count passing cars. We say that a pair of cars (P, Q),
where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q
is traveling to the west.</p>
<p>For example, consider array A such that:</p>
<p>A[0] = 0<br>
A[1] = 1<br>
A[2] = 0<br>
A[3] = 1<br>
A[4] = 1
We have five
pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).</p>
<p>Write a function:</p>
<p>class Solution { public int solution(int[] A); }</p>
<p>that, given a non-empty array A of N integers, returns the number of
pairs of passing cars.</p>
<p>The function should return −1 if the number of pairs of passing cars
exceeds 1,000,000,000.</p>
<p>For example, given:</p>
<p>A[0] = 0<br>
A[1] = 1<br>
A[2] = 0<br>
A[3] = 1<br>
A[4] = 1
the function should return 5, as explained above.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N is an integer within the range [1..100,000]; each element of array A
is an integer that can have one of the following values: 0, 1.</p>
</blockquote>
<p>And this is my solution, please note that if 1000000000+ passing cars are counted, then the return value of the function should be -1. I had to check for overflows, because one of the tests returned a huge negative number if overflowing, also if overflow occurs before 1000000000 (I don't know if an int holds that number), then it would stop counting sooner, hence than try/catch block improves performance(?).</p>
<pre><code>public static int GetNumberOfPassingCars( int[] passingCars )
{
const int OVERFLOW = -1 ;
const int EAST = 0 ;
const int WEST = 1 ;
int carTravelingEast = 0, pairOfPassingCars = 0;
foreach( var passingCar in passingCars )
{
if ( passingCar == EAST )
{
++carTravelingEast;
}
else if ( passingCar == WEST )
{
try
{
pairOfPassingCars = checked( pairOfPassingCars + carTravelingEast );
if ( pairOfPassingCars > 1000000000 )
{
return OVERFLOW;
}
}
catch( OverflowException )
{
return OVERFLOW;
}
}
}
return pairOfPassingCars;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T23:16:50.433",
"Id": "447311",
"Score": "1",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)"
}
] |
[
{
"body": "<h2>Overflow averted</h2>\n\n<p>Performance of your algorithm is optimal since you iterate the input just once in <span class=\"math-container\">\\$O(n)\\$</span> time complexity. There is a way to avoid the <code>checked</code> overflow guard. Noone forces you to use <code>int</code> to perform the arithmetic in the method body.</p>\n\n<blockquote>\n<pre><code>int carTravelingEast = 0, pairOfPassingCars = 0;\n</code></pre>\n</blockquote>\n\n<p>Using <code>uint</code> with a max value of <span class=\"math-container\">\\$4,294,967,295\\$</span> would never overflow, since:</p>\n\n<ul>\n<li><code>carTravelingEast</code> can never be more than <code>int</code>'s max value <span class=\"math-container\">\\$2,147,483,647\\$</span> (because of the length of an array is capped)</li>\n<li>the maximum value <span class=\"math-container\">\\$3,147,483,647\\$</span> as the sum of the custom threshold of one billion + int's max value could never exceed uint's max value (and we exit early on reaching one billion)</li>\n</ul>\n\n<h2>Code Conventions</h2>\n\n<ul>\n<li>Don't use UPPERCASE variable names for constants; use PascalCase instead.</li>\n<li>Use white space according to <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions\" rel=\"nofollow noreferrer\">Conventions</a>.\n\n<ul>\n<li><code>GetNumberOfPassingCars( int[] passingCars )</code> -> <code>GetNumberOfPassingCars(int[] passingCars)</code></li>\n<li><code>foreach( var passingCar in passingCars )</code> -> <code>foreach (var passingCar in passingCars)</code></li>\n</ul></li>\n<li>Use plural name for a variable that represents multiple objects: <code>pairOfPassingCars</code> -> <code>pairsOfPassingCars</code>.</li>\n<li>Use a constant to avoid magic numbers; <code>const uint maxLimit = 1000000000;</code>.</li>\n<li>Throw <code>ArgumentNullException</code> when mandatory arguments are null in public methods.</li>\n</ul>\n\n<hr>\n\n<h2>Code Refactored</h2>\n\n<pre><code>public static int GetNumberOfPassingCars(int[] passingCars)\n{\n if (passingCars == null) throw new ArgumentNullException(nameof(passingCars));\n\n const int Overflow = -1;\n const int East = 0;\n const int West = 1;\n const uint maxLimit = 1000000000;\n uint carsTravelingEast = 0, pairsOfPassingCars = 0;\n\n foreach (var passingCar in passingCars)\n {\n if (passingCar == East)\n {\n ++carsTravelingEast;\n }\n else if (passingCar == West)\n { \n pairsOfPassingCars += carsTravelingEast;\n if (pairsOfPassingCars > maxLimit)\n {\n return Overflow;\n }\n }\n }\n\n return (int)pairsOfPassingCars;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:02:08.843",
"Id": "447236",
"Score": "0",
"body": "I appreciate the comments. So thanks for that, although codility's compiler throws the following error:\n\"Solution.cs(32,16): error CS0266: Cannot implicitly convert type `uint' to `int'. An explicit conversion exists (are you missing a cast?)\"\nAfter that, adding the cast (int), does pass the tests with 100% final score. The other thing I don't get is why would you throw an ArgumentNullException when just returning that 0 pairsOfPassingCars have been found is OK, and the foreach wouldn't even have to iterate through an empty array? so, no improvement in performance, nor result. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:12:02.013",
"Id": "447238",
"Score": "0",
"body": "I was editing (I'm new so I forget about pressing Shift+Enter, when trying to nbsp). \nNot an important error at all! And of course, I like another point of view (otherwise, why posting here?), and tool for handling overflows :-) \nIf there's another way of doing it (according to the uint part), then I totally get it. My question is, is that way better? I mean you say I can avoid Checked... should I? and why?\nAnd the ArgumentNullException I think is unneeded in this context, even though if in general it's a good practice I should follow, then I get it too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:25:05.023",
"Id": "447240",
"Score": "1",
"body": "I'm sticking to this version of the code. Hope it helps you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:29:03.973",
"Id": "447241",
"Score": "1",
"body": "It did. Considering the fact that overflow checking was unnecessary, made me realize code was perfectly fine without it when I moved `if ( pairOfPassingCars > 1000000000 ) { return OVERFLOW; }` up. It used to be at the bottom, and returned OVERFLOW if that was true, or pairsOfPassingCars otherwise... That's what made me check"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T08:26:09.783",
"Id": "229785",
"ParentId": "229779",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229785",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T05:27:56.843",
"Id": "229779",
"Score": "2",
"Tags": [
"c#",
"performance",
"beginner",
"programming-challenge",
"array"
],
"Title": "Codility's count passing cars in opposite directions in C#"
}
|
229779
|
<p>I generate a set of data based off every combination of inputs. The source range that's inputs requires headers to identify the parameters. In its present state I'm not content as it's not as straightforward as I'd like it to be. Specifically the module variables can be cleaned up but I'm not seeing how.</p>
<p>A simple example with 2 columns</p>
<pre><code>---------------------
| Column1 | Column2 |
|---------|---------|
| A | 1 |
| B | 2 |
| C | 3 |
---------------------
</code></pre>
<p>generates</p>
<pre><code>---------------------
| Column1 | Column2 |
|---------|---------|
| A | 1 |
| A | 2 |
| A | 3 |
| B | 1 |
| B | 2 |
| B | 3 |
| C | 1 |
| C | 2 |
| C | 3 |
---------------------
</code></pre>
<p>Adding a 3 column input table</p>
<pre><code>-------------------------------
| Column1 | Column2 | Column3 |
|---------|---------|---------|
| A | 1 | F1 |
| B | 2 | F2 |
| C | 3 | F3 |
| | | F4 |
-------------------------------
</code></pre>
<p>generates</p>
<pre><code>-------------------------------
| Column1 | Column2 | Column3 |
|---------|---------|---------|
| A | 1 | F1 |
| A | 1 | F2 |
| A | 1 | F3 |
| A | 1 | F4 |
| A | 2 | F1 |
. . . . . . . . . . . . . . .
| C | 2 | F4 |
| C | 3 | F1 |
| C | 3 | F2 |
| C | 3 | F3 |
| C | 3 | F4 |
-------------------------------
</code></pre>
<p>and so on.</p>
<p>The class module <code>InputColumn</code> is used to help compartmentalize the logic for each column and its corresponding max depth being equivalent to <code>CountOfValues</code>.</p>
<pre><code>'@PredeclaredId
'@Folder("ParametricSweep.Model")
Option Explicit
Private Type THelper
ColumnIndex As Long
Values As Variant
Identifier As String
End Type
Private this As THelper
Public Property Let Values(ByVal Value As Variant)
this.Values = Value
End Property
Public Property Get Values() As Variant
Values = this.Values
End Property
Public Property Get CountOfValues() As Long
CountOfValues = UBound(Values) - LBound(Values) + 1
End Property
Public Property Let Identifier(ByVal Value As String)
this.Identifier = Value
End Property
Public Property Get Identifier() As String
Identifier = this.Identifier
End Property
Public Function Self() As InputColumn
Set Self = Me
End Function
Public Function Create(ByVal ColumnIndex As Long, ByVal sourceArea As Range) As InputColumn
Dim populatedCells As Range
Set populatedCells = sourceArea.SpecialCells(XlCellType.xlCellTypeConstants)
With New InputColumn
.Identifier = populatedCells(1, 1).Value2
.Values = Application.WorksheetFunction.Transpose(populatedCells.Offset(1).Resize(populatedCells.Rows.Count - 1).Value2)
Set Create = .Self
End With
End Function
</code></pre>
<p>The sweep of values is generated by populating the <code>inputColumns()</code> array then stepping into <code>PopulateArray 1</code> for the first (topmost) level. After the call to <code>PopulateArray</code> it recursively descends one level deeper until it's populating the last column. As each loop returns it increments the array <code>recursionInputColumnPopulationIndex()</code> that identifies which element should populated for the corresponding recursion depth.</p>
<pre><code>Option Explicit
Private parentArray() As Variant
Private inputColumns() As InputColumn
Private maxRecursionDepth As Long
Private recursionInputColumnPopulationIndex() As Long
Private populationRow As Long
Public Sub TestRecursive()
Dim foo As Variant
foo = RecursiveParametricSweep(Sheet1.Range("C5").CurrentRegion, True)
Dim bar As Variant
bar = RecursiveParametricSweep(Sheet1.Range("C16").CurrentRegion, False)
End Sub
Public Function RecursiveParametricSweep(ByVal inputSourceArea As Range, ByVal includeHeader As Boolean) As Variant
maxRecursionDepth = inputSourceArea.Columns.Count
ReDim inputColumns(1 To maxRecursionDepth)
ReDim recursionInputColumnPopulationIndex(1 To maxRecursionDepth)
PopulateInputColumns inputSourceArea
Dim rowCount As Long
rowCount = GetRowCount(inputColumns)
If includeHeader Then
ReDim parentArray(0 To rowCount, 1 To maxRecursionDepth)
Dim headerRow As Long
headerRow = LBound(parentArray)
Dim headerColumn As Long
For headerColumn = LBound(inputColumns) To UBound(inputColumns)
parentArray(headerRow, headerColumn) = inputColumns(headerColumn).Identifier
Next
populationRow = LBound(parentArray) + 1
Else
ReDim parentArray(1 To rowCount, 1 To maxRecursionDepth)
populationRow = LBound(parentArray)
End If
PopulateArray 1, includeHeader
RecursiveParametricSweep = parentArray
End Function
Private Sub PopulateArray(ByVal recursionDepth As Long, ByVal includeHeader As Boolean)
Dim populateElementCount As Long
For populateElementCount = 1 To inputColumns(recursionDepth).CountOfValues
If recursionDepth < maxRecursionDepth Then
PopulateArray recursionDepth + 1, includeHeader
recursionInputColumnPopulationIndex(recursionDepth) = recursionInputColumnPopulationIndex(recursionDepth) + 1
Else
Dim columnPopulationIndex As Long
For columnPopulationIndex = recursionDepth To 1 Step -1
parentArray(populationRow, columnPopulationIndex) = inputColumns(columnPopulationIndex).Values(recursionInputColumnPopulationIndex(columnPopulationIndex) + 1)
Next
recursionInputColumnPopulationIndex(recursionDepth) = recursionInputColumnPopulationIndex(recursionDepth) + 1
populationRow = populationRow + 1
End If
Next
recursionInputColumnPopulationIndex(recursionDepth) = 0
End Sub
Private Function GetRowCount(ByRef inputColumns() As InputColumn) As Long
GetRowCount = 1
Dim depthCounter As Long
For depthCounter = LBound(inputColumns) To UBound(inputColumns)
GetRowCount = GetRowCount * inputColumns(depthCounter).CountOfValues
Next
End Function
Private Sub PopulateInputColumns(ByVal inputSourceArea As Range)
Dim populateInputColumnsCounter As Long
For populateInputColumnsCounter = LBound(inputColumns) To UBound(inputColumns)
Set inputColumns(populateInputColumnsCounter) = InputColumn.Create(populateInputColumnsCounter, inputSourceArea.Columns(populateInputColumnsCounter))
Next
End Sub
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This looks like a decent recursive implementation. So, this is mainly about style and readability.</p>\n\n<p>First, I would like to talk about two things which are really hard and could use some improvement here, naming and consistency of semantic levels. Then I have some more miscellaneous comments.</p>\n\n<h2>Naming</h2>\n\n<p>Generally, the naming is not too bad, but some of the names are a bit misleading, e.g. the function name <code>GetRowCount</code> suggests that it returns the number of rows of whatever I give it. However, what it returns is the number of rows of the later output. So, one could simply call it <code>OutputRowCount</code>, which also follows the general guideline to use nouns that describe the return value for functions.</p>\n\n<p>Another things with the naming is that it sticks a bit much to the role of things in the implementation and not to what they are. Naming things after what they are can make understanding the code much faster. E.g. using <code>inputColumnIndex</code> instead of <code>recursionDepth</code> would immediately tell the reader that you are dealing with this specific input column right now. Then the technical <code>maxRecursionDepth</code> could also be <code>lastColumnIndex</code> or <code>countOfColumns</code>. Similarly, the rather ominous <code>recursionInputColumnPopulationIndex(recursionDepth)</code> could be <code>currentInputIndex(inputColumnIndex)</code>. So generally, my advice would be to name things after what they are and not their implementation purpose.</p>\n\n<h2>Consistency of Semantic Levels</h2>\n\n<p>Programmers, me included, are notoriously bad a keeping semantic levels consistent in procedures. To explain what I mean take a look at <code>RecursiveParametricSweep</code>. It does some high level orchestration like calling the procedure to populate the input columns, calling a function to get the number of output rows, calling the procedure to populate the output array and assigning the return value. However, in between it goes into the detail of how to handle headers. This is a break in semantic level of the procedure that throws one off a bit when first reading the procdure. This could be avoided by extracting either an <code>InitializeOutputArray</code> or a <code>WriteHeaders</code> procedure.</p>\n\n<h2>Miscellaneous</h2>\n\n<ul>\n<li>The global variable <code>maxRecursionDepth</code> is a bit superfluous since it is just <code>UBound(inputColumns)</code>, which is a bit clearer semantically, I think.</li>\n<li>Instead of incrementing <code>recursionInputColumnPopulationIndex(recursionDepth)</code>, you could just always set it to <code>populateElementCount</code> at the start of the loop, which might be called <code>currentInputIndex</code> instead.</li>\n<li>Istead of keeping track of the indeces for the columns in an array, you might just as well keep track of the values in an array instead. That would put the choice of value closer to the action for the specific column.</li>\n<li>It looks a bit strange to have the <code>populationRow</code> counter as a module level variable. You could avoid this by passing it <code>ByRef</code> into the recursive procedure.</li>\n<li>It might make sense to extract a <code>PopulateRow</code> procedure to keep semantic levels consitsent.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T08:55:44.757",
"Id": "229788",
"ParentId": "229781",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T05:48:53.083",
"Id": "229781",
"Score": "11",
"Tags": [
"vba",
"excel",
"recursion",
"combinatorics"
],
"Title": "Recursive code to generate a parametric sweep of input values"
}
|
229781
|
<p>This problem is from <a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-s095-programming-for-the-puzzled-january-iap-2018/puzzle-1-you-will-all-conform/" rel="nofollow noreferrer">MIT Course</a> and I have implemented it in C++. Review this code and how can I improve it complexity-wise and with better features available in C++.</p>
<blockquote>
<p>Let’s say we have a whole bunch of people in line waiting to see a
baseball game. They are all hometown fans and each person has a team
cap and is wearing it. However, not all of them are wearing the caps
in the same way – some are wearing their caps in the normal way, and
some are wearing them backwards.</p>
<p>People have different definitions of normal and backwards but you, the
gatekeeper thinks that the cap on the left below is being normally
worn and the one on the right is being worn backwards.</p>
<p>You are the gatekeeper and can only let them in to the stadium if the
entire group has their caps on in the same way – either all forwards
or all backwards. Because everyone has different definitions of
forward and backward, you can’t tell them to wear their cap forwards
or backwards. You can only tell them to flip their caps. The good news
is that each person knows what position they are in the line, starting
with the first person having position 0 and the last one position n –
1. </p>
<p>You can say things like:</p>
<pre class="lang-none prettyprint-override"><code>Person in position i please flip your cap.
People in positions i through j (inclusive) please flip your caps.
</code></pre>
<p>What you would like to do is to minimize the number of requests you
have to shout out to save your voice.</p>
</blockquote>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <vector>
#include <tuple>
std::vector< std::tuple<std::size_t, std::size_t, char> > please_conform(std::vector<char>& caps,
int forward_count, int backward_count)
{
std::vector< std::tuple<std::size_t, std::size_t, char> > positions;
std::size_t start = 0, end;
for (std::size_t i = 0; i < caps.size()-1; ++i)
{
if (i+1 == caps.size()-1)
{
if (caps[i] != caps[i+1])
{
end = i;
positions.push_back(std::make_tuple(start, end, caps[end]));
if (caps[end] == 'F')
{
forward_count++;
}
else
{
backward_count++;
}
start = i+1;
end = i+1;
positions.push_back(std::make_tuple(start, end, caps[end]));
if (caps[end] == 'F')
{
forward_count++;
}
else
{
backward_count++;
}
}
else
{
end = i+1;
positions.push_back(std::make_tuple(start, end, caps[end]));
if (caps[end] == 'F')
{
forward_count++;
}
else
{
backward_count++;
}
}
}
else
{
if (caps[i] != caps[i+1])
{
end = i;
positions.push_back(std::make_tuple(start, end, caps[end]));
if (caps[end] == 'F')
{
forward_count++;
}
else
{
backward_count++;
}
start = i+1;
}
}
}
return positions;
}
void speak_commands(std::vector< std::tuple<std::size_t, std::size_t, char> >& positions,
int forward_count, int backward_count)
{
char cap_to_flip;
if (forward_count < backward_count)
{
cap_to_flip = 'F';
}
else
{
cap_to_flip = 'B';
}
for (std::size_t i = 0; i < positions.size(); ++i)
{
if (std::get<2>(positions[i]) == cap_to_flip &&
std::get<0>(positions[i]) == std::get<1>(positions[i]))
{
std::cout << "People in position " << std::get<0>(positions[i]) << " flip your cap!\n";
}
else if (std::get<2>(positions[i]) == cap_to_flip &&
std::get<0>(positions[i]) != std::get<1>(positions[i]))
{
std::cout << "People in positions " << std::get<0>(positions[i]) << " through " << std::get<1>(positions[i]) << " flip your caps!\n";
}
}
}
int main()
{
std::vector<char> caps = {'F', 'F', 'B', 'B', 'B', 'F', 'B', 'B',
'B', 'F', 'F', 'B', 'F'};
if (caps.empty())
{
std::cout << "Empty list!!!\n";
}
int forward_count = 0, backward_count = 0;
std::vector< std::tuple<std::size_t, std::size_t, char> > res =
please_conform(caps, forward_count, backward_count);
speak_commands(res, forward_count, backward_count);
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Parameter Passage to Functions</strong><br>\nThe code isn't exactly working as expected, the variables <code>forward_count</code> and <code>backward_count</code> that are passed from <code>main()</code> into <code>please_conform()</code> are being passed by <code>value</code> rather than by <code>reference</code> so they are still zero when the function <code>please_conform()</code> returns. The vector <code>caps</code> is being passed by <code>reference</code> when it should be passed by <code>value</code> because the vector is not being changed in <code>please_conform()</code>. It might be better if the variables <code>forward_count</code> and <code>backward_count</code> were local to <code>please_conform</code> and a single variable possible of type char was returned that indicated the direction.</p>\n\n<p><strong>Duplication of Code</strong><br>\nThis code repeats several times in the function <code>please_conform()</code>:</p>\n\n<pre><code> positions.push_back(std::make_tuple(start, end, caps[end]));\n if (caps[end] == 'F')\n {\n forward_count++;\n }\n else\n {\n backward_count++;\n }\n</code></pre>\n\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n\n<p><strong>Complexity</strong><br>\nThe functions <code>please_conform()</code> and <code>speak_commands()</code> are both too complex and should be broken into smaller functions. Both functions violate the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that states</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>One of the functions that should be added for <code>please_conform()</code> is described in <em>Duplication if Code</em> above. It is important to note that if the tuple contained one more field which was the character indicating the director there would be less duplication of code and the variables <code>forward_count</code> and <code>backward_count</code> would not be need in <code>please_conform()</code>.</p>\n\n<p>The comparison of <code>forward_count</code> and <code>backward_count</code> in the begining of the function <code>speak_commands()</code> would probably be better as it's own function. This function could iterate through the tuples incrementing <code>forward_count</code> and <code>backward_count</code> and then return the direction that wins the comparison. This function could be called either by <code>main()</code> or by <code>speak_commands()</code></p>\n\n<p>The idea behind this is to keep breaking actions up into smaller and smaller functions until each function does only one thing.</p>\n\n<p>Here is one possible re-write of the <code>speak_command()</code> function.</p>\n\n<pre><code>char which_cap_to_flip(std::vector< std::tuple<std::size_t, std::size_t, char> >& positions)\n{\n unsigned forward_count = 0;\n unsigned backward_count = 0;\n\n for (auto cap: positions)\n {\n if (std::get<2>(cap) == 'F')\n {\n forward_count++;\n }\n else\n {\n backward_count++;\n }\n }\n\n return (forward_count < backward_count) ? 'F' : 'B';\n}\n\nvoid speak_commands(std::vector< std::tuple<std::size_t, std::size_t, char> >& positions)\n{\n char cap_to_flip = which_cap_to_flip(positions);\n\n for (std::size_t i = 0; i < positions.size(); ++i)\n {\n if (std::get<2>(positions[i]) == cap_to_flip &&\n std::get<0>(positions[i]) == std::get<1>(positions[i]))\n {\n std::cout << \"People in position \" << std::get<0>(positions[i]) << \" flip your cap!\\n\";\n }\n else if (std::get<2>(positions[i]) == cap_to_flip &&\n std::get<0>(positions[i]) != std::get<1>(positions[i]))\n {\n std::cout << \"People in positions \" << std::get<0>(positions[i]) << \" through \" << std::get<1>(positions[i]) << \" flip your caps!\\n\";\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T15:16:02.743",
"Id": "229800",
"ParentId": "229792",
"Score": "2"
}
},
{
"body": "<p>The good:</p>\n\n<ul>\n<li>Using <code>std::size_t</code> for indexing a std::vector.</li>\n<li>Properly using <code>std::</code> where necessary.</li>\n</ul>\n\n<p>:)</p>\n\n<hr>\n\n<p>The bad:</p>\n\n<ul>\n<li><p><strong>bug</strong>: <code>forward_count</code> and <code>backward_count</code> are passed by value into <code>please_conform</code>. They appear to be output parameters, so they must be passed by reference.</p></li>\n<li><p><strong>bug</strong>: Although we warn the user when encountering an empty list, we carry on running the program, which will cause serious problems in <code>please_conform</code> with the end condition of <code>i < caps.size() - 1</code>. We need to <code>return</code> from <code>main</code>, or move the empty check to the start of <code>please_conform</code>.</p></li>\n<li><p>We should pass the <code>caps</code> vector into <code>please_conform</code> by <code>const&</code>, not <code>&</code>, since we don't intend to change it. Similarly the <code>positions</code> argument to <code>speak_commands</code> should be a <code>const&</code>.</p></li>\n<li><p>A <code>bool</code> would be better than a <code>char</code> to represent cap direction, since it only has two possible values and is easy to flip. An even better choice would be an <code>enum class</code>, since that would also add type-safety (and we easily could supply a \"flip\" function).</p></li>\n<li><p><code>int</code> may not cover the appropriate range for the forward and backward counts. I'd suggest using <code>std::size_t</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>The ugly:</p>\n\n<ul>\n<li><p>Use a <code>struct</code> instead of a tuple. This saves typing, and lets us give meaningful names to the member variables, instead of trying to remember what e.g. <code>std::get<1>()</code> is referring to.</p></li>\n<li><p><code>please_conform</code> is not an informative name. Perhaps something like <code>find_adjacent_ranges</code> or <code>find_runs</code> would be better.</p></li>\n<li><p><code>please_conform()</code> has a lot of repetition. Since we increment <code>forward_count</code> or <code>backward_count</code> in every branch, it might be best to do this at the start of each loop iteration (and count the last item outside of the loop).</p></li>\n<li><p><code>please_conform()</code> finds \"runs\" of the same cap direction. We can do this more easily with two for loops: an outer loop to increment the \"start\" index of each run, and an inner loop to find the \"end\" index (which will be the \"start\" index of the next run). We can use <code>std::find</code> for the inner loop.</p></li>\n<li><p>If we store the \"forward\" and \"backward\" ranges in two separate vectors, we can simplify the \"speak_commands\" function considerably, since we don't have to check each range to see if the direction matches the one we want to flip.</p></li>\n</ul>\n\n<hr>\n\n<p>Applying some of the suggestions above:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n\nstruct range\n{\n std::size_t start = 0;\n std::size_t size = 0;\n};\n\nstruct ranges\n{\n std::vector<range> ranges;\n std::size_t total = 0;\n};\n\nvoid find_ranges(std::vector<bool> const& caps, ranges& forward, ranges& backward)\n{\n forward = ranges();\n backward = ranges();\n\n if (caps.empty())\n return;\n\n for (std::size_t i = 0; i != caps.size(); )\n {\n bool style = caps[i];\n std::size_t start = i;\n std::size_t end = (std::find(caps.begin() + i + 1, caps.end(), !style) - caps.begin());\n std::size_t size = (end - i);\n\n ranges& rs = (style ? forward : backward);\n rs.ranges.push_back({start, size});\n rs.total += size;\n\n i += size;\n }\n}\n\nvoid speak_commands(std::vector<range> const& ranges)\n{\n for (auto const& r : ranges)\n {\n if (r.size == 1)\n std::cout << \"Person in position \" << r.start << \" please flip your cap.\\n\";\n else\n std::cout << \"People in positions \" << r.start << \" through \" << (r.start + r.size - 1) << \" (inclusive) please flip your caps.\\n\";\n }\n}\n\nint main()\n{\n std::vector<bool> caps = { true, true, false, false, false, true, false, false, false, true, true, false, true };\n\n ranges forward, backward;\n find_ranges(caps, forward, backward);\n\n ranges const& to_flip = (backward.total <= forward.total ? backward : forward);\n speak_commands(to_flip.ranges);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T15:48:04.410",
"Id": "229802",
"ParentId": "229792",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T10:44:30.110",
"Id": "229792",
"Score": "3",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "MIT Puzzle: You Will All Conform"
}
|
229792
|
<p>I've implemented my first data encryption / decryption methods on Node.js.
Although it might look similar to hundreds of sample implementations available online, I'm curious to get a feedback.</p>
<p>I'm particularly interested in:</p>
<ul>
<li>some flaw points, potential security, and performance issues</li>
<li>In <code>encrypt()</code> I return an <code>ENCRYPTED</code> object with encrypted data after being freezed by <code>Object.freeze()</code>, are there any drawbacks/pitfalls of returning a freezed object besides the read-only status of the object?</li>
</ul>
<pre class="lang-js prettyprint-override"><code>const CRYPTO = require("crypto");
const ALG_CIPHER = "aes-256-gcm";
const ENC_IN = "utf8";
const ENC_OUT = "base64";
const BUFFER_SIZE = 16;
const KEY = Buffer.from("…", ENC_IN);
/**
* Encrypt data using an initialisation vector
*
* @param {string} data - data to be encrypted
* @returns {Promise<{authTag: Buffer, data: string, iv: Buffer}>} encrypted - encrypted data with decryption parameters
*/
const encrypt = async function encrypt(data) {
const IV = Buffer.from(CRYPTO.randomBytes(BUFFER_SIZE));
const CIPHER = CRYPTO.createCipheriv(ALG_CIPHER, KEY, IV);
let enc = CIPHER.update(data, ENC_IN, ENC_OUT);
enc += CIPHER.final(ENC_OUT);
const ENCRYPTED = Object.freeze({
data: enc,
iv: IV,
authTag: CIPHER.getAuthTag()
});
return ENCRYPTED;
};
/**
* Decrypt data using an initialisation vector
*
* @param {string} data - data to be decrypted
* @param {string} iv - initialisation vector
* @param {Buffer} authTag - authentication tag
* @returns {Promise<string>} decrypted - decrypted data
*/
const decrypt = async function decrypt(data, iv, authTag) {
const DECIPHER = CRYPTO.createDecipheriv(ALG_CIPHER, KEY, iv);
DECIPHER.setAuthTag(authTag);
let decrypted = DECIPHER.update(data, ENC_OUT, ENC_IN);
decrypted += DECIPHER.final(ENC_IN);
return decrypted;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T11:24:43.500",
"Id": "467141",
"Score": "3",
"body": "Please don't change the code after receiving answers, doing so would invalidate them or otherwise create a mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:04:55.857",
"Id": "467178",
"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 you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Please consider posting a new question instead, linking back to the old question. Question threads get terribly messy if we allow updates like this, I'm sorry."
}
] |
[
{
"body": "<p>Comments are below the code fragments.</p>\n\n<pre><code>const ENC_IN = \"utf8\";\nconst ENC_OUT = \"base64\";\n</code></pre>\n\n<p>With the choice of encryption and encoding, I'd include the \"encoding\" part fully (e.g. <code>ENCODING_IN</code> and <code>ENCODING_OUT</code>).</p>\n\n<pre><code>const KEY = Buffer.from(\"…\", ENC_IN);\n</code></pre>\n\n<p>No, a key should not be a constant, and a key should certainly not be a string, even if it has a specific encoding. A key should be 16, 24 or 32 fully unpredictable bytes (for 128, 192 or 256 bit keys respectively). With UTF-8 you only have some 108 possible printable characters for each byte. Besides that, many libraries will not handle partial or overly long keys well.</p>\n\n<p>If you want to use a password, then use a password based key derivation function (PBKDF) and then <code>createCipheriv</code> / <code>createDecipheriv</code>. Support for that is build in (note that <code>createCipher</code> / <code>createDecipher</code> is deprecated).</p>\n\n<h2>Encryption</h2>\n\n<pre><code>const encrypt = async function encrypt(data) {\n</code></pre>\n\n<p>At this point you may want to document the character encoding and the base 64 encoding that is being applied, the mode of operation and that an IV and authentication tag is added. Document or point to the protocol in other words.</p>\n\n<pre><code>const IV = Buffer.from(CRYPTO.randomBytes(BUFFER_SIZE));\n</code></pre>\n\n<p>Good, random IV. For GCM though I'd use 12 bytes or the mode has to perform additional operations for no security benefit.</p>\n\n<pre><code>const ENCRYPTED = Object.freeze({\n</code></pre>\n\n<p>Even though you froze the variable, it's still a local variable and therefore you should not be using all uppercase.</p>\n\n<pre><code>data: enc,\niv: IV,\nauthTag: CIPHER.getAuthTag()\n</code></pre>\n\n<p>Now this is a bit weird. Unless I'm mistaken <code>enc</code> is now base 64 encoded, but <code>iv</code> and <code>authTag</code> are just plain buffers of binary data.</p>\n\n<h2>Decryption</h2>\n\n<pre><code> * @param {string} iv - initialisation vector\n</code></pre>\n\n<p>Strange, your <code>iv</code> of type <code>Buffer</code> seems to have magically become a string...</p>\n\n<p>Otherwise the <code>decrypt</code> function is nicely symmetrical to the <code>encrypt</code> function, which is good.</p>\n\n<hr>\n\n<p>Beware of overly stringifying your code. Beware of wrapper classes; don't start using above class for all your code: use <strong>user specific</strong> encryption routines insetead, and clearly specify your protocol.</p>\n\n<p>When using GCM, you may want to allow additional authenticated data (AAD) to be included in the calculation of the tag.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T10:06:23.550",
"Id": "467136",
"Score": "0",
"body": "Thanks for the detailed review. Regarding _a key should not be a constant_, do I understand it correctly, I need to randomly generate a key every time I want to encrypt the data? If I store the keys in the DB, next to the encrypted data, then if the DB is compromised, the security of the encrypted data is also affected. Therefore, where it's better to store these random keys? Regarding `const ENCRYPTED`, it's a capital since it's a _constant_ and not because it is global/local variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T10:19:20.723",
"Id": "467137",
"Score": "0",
"body": "Regarding `@param {string} iv - initialisation vector`, nice catch! I just forgot to update a JSDoc annotations, now it's fixed, the code snippet is updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T10:28:12.587",
"Id": "467139",
"Score": "0",
"body": "_I'd write out encoding_, [according to the Node.js documentation](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding), encoding is an optional parameter and if not specified, the `utf8` is applied by default. So, why it is better to eliminate encoding in `Buffer.from()`, or is it just a matter of a taste?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T12:06:45.897",
"Id": "467143",
"Score": "1",
"body": "Comment #1. No, you don't need to generate a new key each time, you can for instance keep it in a key store. However, if you keep it in a constant it will also get in your code repo, and it will not allow you to have test keys etc. Key management is a tricky subject, but just using constant keys is not the answer. ENCRYPTED is not constant at all, it changes with the input data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T12:10:45.930",
"Id": "467144",
"Score": "1",
"body": "About the sentence about using ENC for encoding, that was a Dutch-ism :) Sorry for the confusion (uitschrijven != write out)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T12:38:50.757",
"Id": "467147",
"Score": "0",
"body": "Regarding _ENCRYPTED is not constant at all_, as far as I understand the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), being defined as `const` and assigning `Object.freeze(…)` makes the variable constant in its scope: _«A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed»_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T12:43:41.933",
"Id": "467148",
"Score": "1",
"body": "The problem that I have with it is that ENCRYPTED will still be different for each message that you encrypt. If developers see an all caps constant, they expect it to be constant *throughout the application*. Being constant, in other words, is different from being **a** constant. In Java we have *immutable* types, which I use a lot. Instances are as \"constant\" as the JS description of `const`, but they are still not written using all upper caps (unless, of course, they are *also* `static final` class fields)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T12:47:24.953",
"Id": "467149",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/105044/discussion-between-maarten-bodewes-and-mike-b)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T00:49:09.900",
"Id": "238176",
"ParentId": "229793",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238176",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T11:40:40.350",
"Id": "229793",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"cryptography",
"async-await"
],
"Title": "Data encryption / decryption on Node.js"
}
|
229793
|
<p>I have three lists of nodes.</p>
<ul>
<li>sources</li>
<li>sinks</li>
<li>pipes</li>
</ul>
<p>There is a directed weighted graph from sources to pipes to sinks.
Sources are only connected to pipes and pipes only to sinks. But sources are not directly connected to sinks. Pipes are zero-sum, meaning that the sum of the weights that come to each pipe from sources is equal to the sum of the edges that go from that pipe to sinks.</p>
<p>I would like to add a number of edges from sinks back to sources so that sinks and sources also become zero-sum. While minimizing the maximum degree of the graph. I've written a sub-optimal solution that I'm posting here for review.</p>
<p><strong>In simpler words:</strong>
I have a list of sinks and sources. Each sink has a negative number and each source has a positive number so that the sum of all the numbers in the nodes of the graph are zero(no edges so far). I would like to add a number of edges to this graph so that the sum of the weights of the edges going out/in to each node becomes equal to the number on that node.</p>
<p><strong>Here is a sample Code for testing if a graph summarizes another graph</strong>:</p>
<pre><code>from functools import reduce
from collections import Counter
source_edges = {
"a0": {"p0": 1, "p2": 5},
"a1": {"p0": 2},
"a2": {"p1": 3}
}
sink_edges = {
"b0": {"p0": 1},
"b1": {"p0": 1, "p1": 1},
"b2": {"p0": 1, "p1": 2, "p2": 5},
}
res = {
"a0": {"b0": 1, "b2": 5},
"a1": {"b1": 2},
"a2": {"b2": 3}
}
sink_degs1 = {k: sum(v.values()) for k, v in sink_edges.items()}
sink_degs2 = dict(reduce(lambda x, y: x + y, (Counter(v) for v in res.values())))
source_degs1 ={k: sum(v.values()) for k, v in res.items()}
source_degs2 ={k: sum(v.values()) for k, v in source_edges.items()}
if sink_degs1 == sink_degs2 and source_degs1 == source_degs2:
print('res summerizes the graph')
else:
print('res does not summerize this graph')
</code></pre>
<p>And a visualization of this graph:</p>
<p><a href="https://i.stack.imgur.com/SOl4T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SOl4T.png" alt="graph image" /></a></p>
<p>What follows is a sub-optimum solution with less than n-1 edges.</p>
<pre><code>from numpy.random import randint
from collections import defaultdict
import copy
def create_sample(source_count=5000, sink_count=200):
diff = -1
while diff < 0:
sinks = [["b" + str(i), randint(source_count)] for i in range(sink_count)]
sources = [["a" + str(i), randint(sink_count)] for i in range(source_count)]
sink_sum = sum([x[1] for x in sinks])
source_sum = sum([x[1] for x in sources])
diff = sink_sum - source_sum
avg_refill = diff // source_count + 1
weights_match = False
while not weights_match:
for i in range(source_count):
if not diff:
break
rnd = randint(avg_refill * 2.5) if diff > 10 * (avg_refill) else diff
diff -= rnd
sources[i][1] += rnd
weights_match = sum([x[1] for x in sources]) == sum([x[1] for x in sinks])
return sources, sinks
def solve(sources, sinks):
src = sorted(copy.deepcopy(sources), key=lambda x: x[1])
snk = sorted(copy.deepcopy(sinks), key=lambda x: x[1])
res = []
while snk:
if src[0][1] > snk[0][1]:
edge = (src[0][0], *snk[0])
src[0][1] -= snk[0][1]
del snk[0]
elif src[0][1] < snk[0][1]:
edge = (src[0][0], snk[0][0], src[0][1])
snk[0][1] -= src[0][1]
del src[0]
else:
edge = (src[0][0], *snk[0])
del src[0], snk[0]
res += [edge]
return res
def test(sources, sinks):
res = solve(sources, sinks)
d_sources = defaultdict(int)
d_sinks = defaultdict(int)
w_sources = defaultdict(int)
w_sinks = defaultdict(int)
for a, b, c in res:
d_sources[a] += 1
d_sinks[b] += 1
w_sources[a] += c
w_sinks[b] += c
print("source " + ("is" if dict(sources) == w_sources else "isn't") + " source")
print("sink " + ("is" if dict(sinks) == w_sinks else "isn't") + " sink")
print(
f"source:\n \tdeg_sum = {sum(d_sources.values())}\n\tmax_deg = {max(d_sources.values())}"
)
print(
f"sink:\n \tdeg_sum = {sum(d_sinks.values())}\n\tmax_deg = {max(d_sinks.values())}"
)
</code></pre>
<p>Here is a sample run:</p>
<pre><code>In [1]: %run solver.py
In [2]: test(*create_sample())
source is source
sink is sink
source:
deg_sum = 5196
max_deg = 3
sink:
deg_sum = 5196
max_deg = 56
</code></pre>
<p>Here is an illustration of how it works:</p>
<pre><code>sources: 4,5,3,2
sinks: 2,7,2,2,1
sorted:
55555|44|44|33|32|2
77777|77|22|22|22|1
So we have 6 edges.
</code></pre>
<p>Here is a comparison between sorted and unsorted solution with this algorithm:</p>
<pre><code>---------------------------------------------
| (1000,1000) |
---------------------------------------------
| criteria | sorted | random order |
| source degree sum | 1991 | 1999 |
| source max degree | 3 | 7 |
| sink degreee sum | 1991 | 1999 |
| sink max degree | 3 | 8 |
---------------------------------------------
---------------------------------------------
| (200,5000) |
---------------------------------------------
| criteria | sorted | random order |
| source degree sum | 5198 | 5198 |
| source max degree | 2 | 3 |
| sink degreee sum | 5198 | 5198 |
| sink max degree | 43 | 54 |
---------------------------------------------
</code></pre>
<p>I'm looking for improvements to the algorithm or implementation to better the performance of this solution. It can be assumed that the edges come from normal distribution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:36:42.853",
"Id": "447230",
"Score": "0",
"body": "@dfhwze But I already have written a working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:43:07.167",
"Id": "447232",
"Score": "0",
"body": "@dfhwze I've seen an *improvements* section in many of the code reviews here, and I considered better performance as a possible improvement. Seems like It was a misunderstanding, I will edit my question nwo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:49:34.927",
"Id": "447233",
"Score": "1",
"body": "@dfhwze is this better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:51:54.460",
"Id": "447234",
"Score": "2",
"body": "seems to be on-topic now, good edit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:54:54.833",
"Id": "447235",
"Score": "1",
"body": "@dfhwze thank you for your guidance."
}
] |
[
{
"body": "<h2>Use f-strings</h2>\n\n<pre><code>\"b\" + str(i)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'b{i}'\n</code></pre>\n\n<h2>Don't make inner lists</h2>\n\n<pre><code>sum([x[1] for x in sinks])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>sum(x[1] for x in sinks)\n</code></pre>\n\n<h2>Avoid loop flags</h2>\n\n<pre><code>weights_match = False\nwhile not weights_match:\n # ...\n weights_match = sum([x[1] for x in sources]) == sum([x[1] for x in sinks])\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>while True:\n # ...\n if sum(x[1] for x in sources) == sum(x[1] for x in sinks):\n break\n</code></pre>\n\n<p>(C has a do-while, but Python doesn't.)</p>\n\n<h2>Replace your lambda</h2>\n\n<p>Don't repeat this lambda:</p>\n\n<pre><code>lambda x: x[1]\n</code></pre>\n\n<p>Create it once as:</p>\n\n<pre><code>from operator import itemgetter\nsecond = itemgetter(1)\n</code></pre>\n\n<h2>Add type hints</h2>\n\n<pre><code>def create_sample(source_count=5000, sink_count=200):\n</code></pre>\n\n<p>becomes, at a guess,</p>\n\n<pre><code>def create_sample(source_count: int = 5000, sink_count: int = 200) ->\n (list, list):\n</code></pre>\n\n<p>You can get fancier with typed lists, but this is the bare minimum.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:46:24.917",
"Id": "447268",
"Score": "2",
"body": "Thank you so much for your great review, I upvoted your answer for now, but I'm hoping to get a more functional and performance-wise review to have as the accepted answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:10:40.670",
"Id": "229811",
"ParentId": "229796",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229811",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:23:22.557",
"Id": "229796",
"Score": "2",
"Tags": [
"python",
"performance",
"graph",
"complexity",
"community-challenge"
],
"Title": "Finding minimum weighted matching in sink source graph"
}
|
229796
|
<p>I'm trying to optimize my solution to this <a href="https://leetcode.com/problems/super-ugly-number/" rel="nofollow noreferrer">LeetCode problem</a>:</p>
<blockquote>
<p>Write a program to find the n<sup>th</sup> super ugly number.</p>
<p>Super ugly numbers are positive numbers whose all prime factors are in
the given prime list primes of size k.</p>
</blockquote>
<p>My working, accepted solution:</p>
<pre><code>import heapq
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
heap = [1]
seen = set()
while n>=0:
num = heapq.heappop(heap)
n -=1
if n == 0:
return num
for p in primes:
if num * p not in seen:
seen.add(num*p)
heapq.heappush(heap, num*p)
return heapq.heappop(heap)
</code></pre>
<p>What are some ways to optimize it in terms of time and space complexity?</p>
|
[] |
[
{
"body": "<h2>Loop like a native</h2>\n\n<pre><code> while n>=0:\n n -=1\n</code></pre>\n\n<p>You don't actually use <code>n</code>, nor should you be manually decrementing it, so this can become</p>\n\n<pre><code>for _ in range(n+1):\n</code></pre>\n\n<h2>Returns</h2>\n\n<p>I'm not clear on why you have two <code>return</code>s. <code>return num</code> will take effect on the last iteration of the loop, so how would the other return happen at all? Probably you should remove the <code>if n == 0</code> condition and rework the place where <code>heappop</code> is called so that the <code>for _ in range</code> can completely control the loop.</p>\n\n<h2>Set operations</h2>\n\n<p>Try this out to see what performance impact it has:</p>\n\n<p>Rather than </p>\n\n<pre><code> for p in primes:\n if num * p not in seen:\n seen.add(num*p)\n heapq.heappush(heap, num*p)\n</code></pre>\n\n<p>try</p>\n\n<pre><code>to_add = {num*p for p in primes} - seen\nseen |= to_add\nfor a in to_add:\n heapq.heappush(heap, a)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:51:31.367",
"Id": "229809",
"ParentId": "229798",
"Score": "1"
}
},
{
"body": "<p>As already explained <a href=\"https://codereview.stackexchange.com/a/229807/35991\">in this answer</a>, there is no need to use a class with an instance method here. In addition, the convention for function names in Python is to use <code>snake_case</code>, not <code>camelCase</code>. </p>\n\n<p>On the other hand, this template is given on the <a href=\"https://leetcode.com/problems/super-ugly-number/\" rel=\"nofollow noreferrer\">LeetCode submission template</a>, so you are not free to change it. </p>\n\n<p>What you can do is to make the required solution method a wrapper for a free function (which then is universally usable):</p>\n\n<pre><code>def nth_super_ugly_number(n: int, primes: List[int]) -> int:\n # ...\n\n\nclass Solution:\n def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n return nth_super_ugly_number(n, primes)\n</code></pre>\n\n<p><em>Generating</em> the ugly numbers can be separated from <em>counting</em> them (until the nth ugly number is reached) if the former is done with a <em>generator.</em> The generator is now a reusable function as well, and you might want to add a docstring comment:</p>\n\n<pre><code>def super_ugly_numbers(primes: List[int]) -> int:\n \"\"\"Generate super ugly numbers.\n\n Super ugly numbers are positive integers whose all prime factors are in\n the given prime list.\n \"\"\"\n\n heap = [1]\n seen = set()\n while True:\n num = heapq.heappop(heap)\n yield num\n for p in primes:\n if num * p not in seen:\n seen.add(num * p)\n heapq.heappush(heap, num * p)\n\n\ndef nth_super_ugly_number(n: int, primes: List[int]) -> int:\n ugly_numbers = super_ugly_numbers(primes)\n for _ in range(n - 1):\n next(ugly_numbers)\n return next(ugly_numbers)\n</code></pre>\n\n<p>The last function can be simplified using <code>itertools.islice</code>:</p>\n\n<pre><code>import itertools\n\ndef nth_super_ugly_number(n: int, primes: List[int]) -> int:\n ugly_numbers = super_ugly_numbers(primes)\n return next(itertools.islice(ugly_numbers, n - 1, n))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T06:32:38.807",
"Id": "229835",
"ParentId": "229798",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T13:45:53.160",
"Id": "229798",
"Score": "2",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"primes"
],
"Title": "Finding the nth ugly number"
}
|
229798
|
<p>What's the best way to check if a String ends with any of multiple suffixes in Rust?</p>
<p>I have a working, naive solution:</p>
<pre class="lang-rust prettyprint-override"><code>fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool {
for suffix in &suffixes {
if s.ends_with(suffix) {
return true;
}
}
false
}
</code></pre>
<p><em>Note: suffixes could have varying lengths</em></p>
<p>As I am quite new to Rust, I would very much appreciate any/all suggestions about how my code can better leverage Rust idioms.</p>
<p>Here are some test cases I need to function pass</p>
<pre><code>#[test]
fn empty_suffixes() {
let s = String::from("5m");
let suffixes = vec![];
assert!(!string_ends_with_any(s, suffixes))
}
#[test]
fn empty_string_has_no_suffix() {
let s = String::from("");
let suffixes = vec!["txt"];
assert!(!string_ends_with_any(s, suffixes))
}
#[test]
fn string_ends_with_first_suffix() {
let s = String::from("foo.txt");
let suffixes = vec!["txt", "csv"];
assert!(string_ends_with_any(s, suffixes))
}
#[test]
fn string_ends_with_last_suffix() {
let s = String::from("foo.csv");
let suffixes = vec!["txt", "csv"];
assert!(string_ends_with_any(s, suffixes))
}
#[test]
fn string_doesnt_end_with_any_suffix() {
let s = String::from("foo.csv");
let suffixes = vec!["txt", "tsv"];
assert!(!string_ends_with_any(s, suffixes))
}
#[test]
fn string_ends_in_suffix_but_case_is_wrong() {
let s = String::from("foo.csv");
let suffixes = vec!["txt", "Csv"];
assert!(!string_ends_with_any(s, suffixes))
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T16:14:53.000",
"Id": "447253",
"Score": "0",
"body": "https://doc.rust-lang.org/std/string/struct.String.html#method.ends_with"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T16:43:42.110",
"Id": "447257",
"Score": "2",
"body": "@πάνταῥεῖ that's not particularly helpful. I know that `String::ends_with` exists (I use it in my implementation). The question I quite clearly asked was whether there is a way to test whether a String ends in any number of given strings more effectively than I am."
}
] |
[
{
"body": "<p>You could use <a href=\"https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_any.html\" rel=\"nofollow noreferrer\">Iterator:any</a> to write this in a succinct way:</p>\n\n<pre><code>fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool {\n return suffixes.iter().any(|&suffix| s.ends_with(suffix));\n}\n</code></pre>\n\n<p>Because this pattern returns true on first match of the predicate:</p>\n\n<blockquote>\n<pre><code>for suffix in &suffixes {\n if s.ends_with(suffix) {\n return true;\n }\n}\nfalse\n</code></pre>\n</blockquote>\n\n<p>Whether this is <em>rustacious</em> remains to be seen. I'm by no means an expert in Rust.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:50:00.833",
"Id": "229808",
"ParentId": "229799",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229808",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T15:13:20.763",
"Id": "229799",
"Score": "2",
"Tags": [
"beginner",
"strings",
"unit-testing",
"rust"
],
"Title": "Rustacious way of checking if string ends with any suffix from a selection"
}
|
229799
|
<p>I'm trying to solve this problem</p>
<blockquote>
<p>Given a positive integer n, find the least number of perfect square
numbers (for example, 1, 4, 9, 16, ...) which sum to n.</p>
</blockquote>
<p>I've come up with a solution that works correctly but times out on large inputs:</p>
<pre><code>from collections import defaultdict
class Solution:
def numSquares(self, n: int) -> int:
coins = []
for i in range(1, n+1):
if i**2>n:
break
coins.append(i**2)
min_coins_to_make = defaultdict(lambda :float("inf"))
min_coins_to_make[0] = 0
for coin in coins:
if coin > n:
break
for target in range(coin, n+1):
min_coins_to_make[target] = min(min_coins_to_make[target], 1+min_coins_to_make[target-coin])
if min_coins_to_make[target] == float("inf"):
return 0
return min_coins_to_make[target]
</code></pre>
<p>How do I optimize it in terms of time and space complexity?</p>
<p><a href="https://leetcode.com/problems/perfect-squares/" rel="noreferrer">https://leetcode.com/problems/perfect-squares/</a></p>
|
[] |
[
{
"body": "<p>I won't specifically address the execution time concerns to begin with; there are other issues:</p>\n\n<h2>Don't use a class</h2>\n\n<p>There's no reason for this to be a class. You have one method and you don't even reference <code>self</code>. In theory you could remove <code>self</code> and mark it a <code>@staticmethod</code>, but really it should just be a function without a class.</p>\n\n<h2>Reuse variables</h2>\n\n<p>Make this variable -</p>\n\n<pre><code>i2 = i**2\n</code></pre>\n\n<p>since it's used twice. The same goes for <code>min_coins_to_make[target]</code>.</p>\n\n<h2>Loop limit</h2>\n\n<pre><code> for coin in coins:\n if coin > n:\n break \n</code></pre>\n\n<p>That termination condition will be true if <code>coin > n</code>, but <code>coin == i**2</code>. <code>i**2 > n</code> will never be true, because in the previous loop,</p>\n\n<pre><code> if i**2>n:\n break \n</code></pre>\n\n<p>So can't you just write <code>for coin in coins</code> without an interior termination condition?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:54:40.127",
"Id": "447260",
"Score": "3",
"body": "You are of course right about the class and instance method. Just note that this is *given* in the problem submission template on https://leetcode.com/problems/perfect-squares/."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:56:04.787",
"Id": "447261",
"Score": "2",
"body": "Ah true - that's a silly template."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:56:17.707",
"Id": "447262",
"Score": "1",
"body": "I agree with Reinderien: https://codereview.meta.stackexchange.com/questions/9345/reviewing-programming-challenge-requirements-and-givens"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T17:33:34.407",
"Id": "229807",
"ParentId": "229803",
"Score": "7"
}
},
{
"body": "<p>Here</p>\n\n<pre><code>if min_coins_to_make[target] == float(\"inf\"):\n return 0 \nreturn min_coins_to_make[target]\n</code></pre>\n\n<p>you use the fact that <code>target</code> has the last value from a preceding (nested) loop, and that happens to be <code>n</code>. It would be more clear to use <code>n</code> directly instead:</p>\n\n<pre><code>if min_coins_to_make[n] == float(\"inf\"):\n return 0 \nreturn min_coins_to_make[n]\n</code></pre>\n\n<p>Then note that the if-condition can never be true, so that you can remove that test: Every positive integer <span class=\"math-container\">\\$ n \\$</span> can be written as\n<span class=\"math-container\">$$\nn = \\underbrace{1 + 1 + \\ldots + 1}_{n \\text{ terms}}\n$$</span>\nwhich makes it a sum of <span class=\"math-container\">\\$ n \\$</span> perfect squares. (Actually every positive integer can be written as the sum of at most <em>four squares</em> according to <a href=\"https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem\" rel=\"nofollow noreferrer\">Lagrange's four-square theorem</a>.)</p>\n\n<p>This</p>\n\n<pre><code>coins = []\nfor i in range(1, n+1):\n if i**2>n:\n break \n coins.append(i**2)\n</code></pre>\n\n<p>can be written as a list comprehension:</p>\n\n<pre><code>coins = [i * i for i in range(1, int(math.sqrt(n)) + 1)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:54:17.187",
"Id": "447357",
"Score": "0",
"body": "what are the gains in time/space complexity with these suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T15:58:18.893",
"Id": "447360",
"Score": "0",
"body": "I made suggestions to remove unneeded code, to make it better understandable, and to use idiomatic Python. – The policy on this site is that an answer can review *any* aspect of the posted code, not only the topics the OP is concerned about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T18:58:09.740",
"Id": "447382",
"Score": "1",
"body": "Nice mentioning the theorem. It's a good option to speed things up."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:45:03.503",
"Id": "229819",
"ParentId": "229803",
"Score": "6"
}
},
{
"body": "<p>You can remove the <code>coins</code> variable altogether and replace it with a generator of squares:</p>\n\n<pre><code>for coin in (x**2 for x in itertools.count(1)):\n ...\n</code></pre>\n\n<p>You don't necessarily need a <code>defaultdict</code> with a lambda, since you are going to create the all the values in the dict anyway (<code>defaultdict</code> is more appropriate if you don't know in advance what keys you'll need):</p>\n\n<pre><code>min_coins_to_make = {i: i for i in range(n)}\n</code></pre>\n\n<p>(which takes care of the square of 1, too, so you can start your count at 2, realistically)</p>\n\n<p>In terms of space and complexity, space is <code>O(N)</code>, complexity is <code>O(N*Log(N))</code> (it's actually a Harmonic number (<code>sum(1/i for i < n)</code>), but it converges to <code>ln(N)</code>). I don't see a better option right now.</p>\n\n<p>One other way to look at the problem could be to go backward from large squares, that way you can stop when the square you're looking at is smaller that N/current best (as you'd <em>have</em> to replace a bigger element, hence increasing\nthe total count.) or when you somehow know that the current solution is optimal. I don't know exactly how you'd go about this approach, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T06:49:43.870",
"Id": "447323",
"Score": "1",
"body": "`for coin in (x**2 for x in itertools.count(1)): ...` looks rather weird. `for x in itertools.count(1): coin = x ** 2` is much better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T04:06:47.583",
"Id": "229833",
"ParentId": "229803",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem\" rel=\"nofollow noreferrer\">Lagrange's_four-square_theorem</a> says:</p>\n\n<blockquote>\n <p>every natural number can be represented as the sum of four integer squares.</p>\n</blockquote>\n\n<p>The theorem allows the squares to be zero, so in context of our problem we will say that every natural number can be represented as the sum of four or less integer squares. It means that when we want to determine which square is the largest in the \"shortest\" sum, it must be greater than n // 4. It is the most significant optimization of the code below, it is implemented in the line <code>elif square > n_4:</code>. The code runs in 1136 ms and 30.7 MB on leetcode. I believe it can be better improved and explained but the theorem is the main idea.</p>\n\n<pre><code>import collections\n\n\nParameters = collections.namedtuple('Parameters', ['n', 'last_index', 'num_squares'])\n\n\nclass Solution:\n def numSquares(self, n):\n squares = [i ** 2 for i in range(1, int(n ** 0.5) + 1)]\n min_num = n\n lst = [Parameters(n, len(squares) - 1, 0)]\n while lst:\n new_lst = []\n for parameters in lst:\n if parameters.num_squares < min_num:\n n_4 = parameters.n // 4\n for index in range(parameters.last_index + 1):\n square = squares[index]\n if square == parameters.n:\n min_num = min(min_num, parameters.num_squares + 1)\n elif square > parameters.n:\n break\n elif square > n_4:\n new_lst.append(\n Parameters(\n parameters.n - square,\n index,\n parameters.num_squares + 1\n )\n )\n lst = new_lst\n return min_num\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:39:51.653",
"Id": "229869",
"ParentId": "229803",
"Score": "1"
}
},
{
"body": "<p>If you want to optimize your code, optimize the algorithm first.</p>\n\n<p>Thanks to <a href=\"https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem\" rel=\"nofollow noreferrer\">Lagrange's four-square theorem</a>, you know you will need at most four squares of positive integers.</p>\n\n<ul>\n<li>You can pretend that the last number chosen will succeed.</li>\n<li>You can impose that the next number chosen is not greater.</li>\n<li>You can pretend that the next try will be no worse than the best to date.</li>\n<li>If you get a solution fast, you can cull the search-space, so start at the big end.</li>\n</ul>\n\n<p>Every selection will be similar, though under potentially more severe constraints, so use recursion:</p>\n\n<pre><code>def numSquaresImpl(n: int, upper: int, num: int) -> int:\n upper = min(int(sqrt(n)) + 1, upper)\n while upper ** 2 > n:\n upper = upper - 1\n if upper ** 2 == n:\n return 1\n if num <= 2:\n return 2\n lower = max(0, int(sqrt(n // num)) - 1)\n while upper >= lower:\n r = numSquaresImpl(n - upper ** 2, upper, num - 1) + 1\n upper = upper - 1\n if r < num:\n if r == 2:\n return 2\n num = r\n lower = max(0, int(sqrt(n // num)) - 1)\n return num\ndef numSquares(n: int) -> int:\n return numSquaresImpl(n, n, 4) if n > 0 else 0\n</code></pre>\n\n<p><sub>Warning: I only proved this correct, I didn't run it. Also, I rarely do Python.</sub></p>\n\n<p>As others already said, wrapping a pure function in a class without any good reason makes no sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:30:18.167",
"Id": "229880",
"ParentId": "229803",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T16:01:04.973",
"Id": "229803",
"Score": "10",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Minimum perfect squares needed to sum up to a target"
}
|
229803
|
<p>I want to learn about Design Patterns and be able to apply them in Excel VBA. So to learn about patterns I bought a book that seems promising: <em>Head First Design Patterns</em>; it presents the material clearly. However, the code exercises/examples are in Java 8. VBA does not have direct counterparts for some things (e.g. <code>Extends</code>) so I need to work out how to accomplish the same/similar in VBA.</p>
<p>I am following along with the exercises and doing what I think parallels the Java in VBA. What I am asking here is "am I on the right track?"</p>
<p>More detail: the specific aspect (I think) is the Extends use in Java (MallardDuck Extends Duck); VBA has no Extends, so the specific question would be does the technique I used of passing the Duck to my VBA MallardDuck in the Create method and setting the fly and quack behaviors accomplish the Extends use in Java?</p>
<p>Here’s the Java for a part of on exercise:</p>
<blockquote>
<pre><code>public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() {
}
public void setFlyBehavior(FlyBehavior fb) {
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
quackBehavior = qb;
}
abstract void display();
public void performFly() {
flyBehavior.fly();
}
public void performQuack() {
quackBehavior.quack();
}
public void swim() {
System.out.println("All ducks float, even decoys!");
}
}
public class MallardDuck extends Duck {
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public void display() {
System.out.println("I'm a real Mallard duck");
}
}
public class MiniDuckSimulator {
public static void main(String[] args) {
MallardDuck mallard = new MallardDuck();
FlyBehavior cantFly = () -> System.out.println("I can't fly");
QuackBehavior squeak = () -> System.out.println("Squeak");
RubberDuck rubberDuckie = new RubberDuck(cantFly, squeak);
DecoyDuck decoy = new DecoyDuck();
Duck model = new ModelDuck();
mallard.performQuack();
rubberDuckie.performQuack();
decoy.performQuack();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}
</code></pre>
</blockquote>
<p>Here's what I’ve done in VBA - There are some differences in the <code>Main</code> procedures because I haven't completely mimicked the Java in VBA. I am more interested in the <code>Duck</code> and <code>Mallard</code> implementations.</p>
<p>Any suggestions are greatly appreciated.</p>
<p><strong>Duck</strong> class module:</p>
<pre class="lang-vb prettyprint-override"><code>'@Folder("SimUDuck.Objects.HeadFirst")
Option Explicit
Private Type TObject
FlyBehavior As IFlyBehavior
QuackBehavior As IQuackBehavior
DuckModel As IDuckModel
End Type
Private this As TObject
Private Sub Class_Terminate()
With this
Set .FlyBehavior = Nothing
Set .QuackBehavior = Nothing
End With
End Sub
Public Property Get DuckModel() As IDuckModel
Set DuckModel = this.DuckModel
End Property
Public Property Set DuckModel(ByVal model As IDuckModel)
With this
Set .DuckModel = model
End With
End Property
Public Property Get FlyBehavior() As IFlyBehavior
Set FlyBehavior = this.FlyBehavior
End Property
Public Property Set FlyBehavior(ByVal behavior As IFlyBehavior)
Set this.FlyBehavior = behavior
End Property
Public Property Get QuackBehavior() As IQuackBehavior
Set QuackBehavior = this.QuackBehavior
End Property
Public Property Set QuackBehavior(ByVal behavior As IQuackBehavior)
Set this.QuackBehavior = behavior
End Property
Public Sub performFly()
this.FlyBehavior.Fly
End Sub
Public Sub performQuack()
this.QuackBehavior.Quack
End Sub
Public Sub Swim()
'todo
End Sub
Public Sub Display()
this.DuckModel.Display
End Sub
</code></pre>
<p><strong>MallardDuck</strong> class module:</p>
<pre class="lang-vb prettyprint-override"><code>'@PredeclaredId
'@Folder("SimUDuck.Models.HeadFirst")
Option Explicit
Private Type TModel
Display As String
End Type
Private this As TModel
Implements IDuckModel
Private Sub IDuckModel_Display()
Debug.Print this.Display '"I'm A Mallard Duck"
End Sub
Public Function CreateDuck(ByVal duck As DuckObject) As IDuckModel
With duck
Set .FlyBehavior = New FlyWithWingsBehavior
Set .QuackBehavior = New QuackBehavior
End With
With New MallardDuckModel
.Display = "I'm A Mallard Duck"
Set CreateDuck = .Self
End With
End Function
Public Property Get Self() As IDuckModel
Set Self = Me
End Property
Public Property Get Display() As String
Display = this.Display
End Property
Public Property Let Display(ByVal value As String)
this.Display = value
End Property
</code></pre>
<pre><code>Public Sub MainDuck()
Dim duck As DuckObject
Set duck = New DuckObject
With New MallardDuckModel
Dim model As IDuckModel
Set model = .CreateDuck(duck)
End With
With duck
Set .DuckModel = model
.performFly
.performQuack
.Display
Dim FlyBehavior As IFlyBehavior
Set FlyBehavior = New FlyRocketPoweredBehavior
Set .FlyBehavior = FlyBehavior
Dim QuackBehavior As IQuackBehavior
Set QuackBehavior = New SqueakBehavior
Set .QuackBehavior = QuackBehavior
.performFly
.performQuack
.Display
End With
Set duck = New DuckObject
With New ModelDuckModel
Set model = .CreateDuck(duck)
End With
With duck
Set .DuckModel = model
.performFly
.performQuack
.Display
End With
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:33:59.033",
"Id": "447267",
"Score": "0",
"body": "Welcome to Code Review. As you stated yourself, it is a bit broad, but also unclear what exactly it is you are asking. Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:24:47.907",
"Id": "447273",
"Score": "2",
"body": "@dfhwze I'm confused. This isn't the first [tag:design-patterns] question on this site, and it isn't going to be the last. OP is presenting a pattern they read about in Java, and implemented it in VBA, and now they're asking for feedback on any/all aspects of the code. Did CR's scope suddenly become about \"specific problems\" overnight or I missed a memo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:35:17.963",
"Id": "447274",
"Score": "1",
"body": "@SmileyFtW to be fair it's indeed a bit hard to work out the pieces, since many of them are left out. I would recommend to [edit] your post to clearly identify the VBA classes (not sure I got the names right), and consider including more of the code - don't worry about making a long post, and note that TAB characters should be replaced by 4 spaces (I fixed that in your original post)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:48:28.950",
"Id": "447275",
"Score": "1",
"body": "@MathieuGuindon Taking out the Java tag and formatting Java code the way you did is already a major improvement. It felt like a cross-language review request before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:47:07.170",
"Id": "447281",
"Score": "0",
"body": "@MathieuGuindon - I apologize for the confusion in the pieces. The edits you did look great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:47:15.093",
"Id": "447282",
"Score": "1",
"body": "@dfhwze - the specific aspect (I think) is the Extends use in Java (MallardDuck Extends Duck); VBA has no Extends, so the specific question would be does the technique I used of passing the Duck to my VBA MallardDuck in the Create method and setting the fly and quack behaviors accomplish the Extends use in Java? I will bone up on formatting questions to avoid messes like my first post was,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:49:19.993",
"Id": "447283",
"Score": "2",
"body": "You should include your last comment in the question, since noone will read through these comments :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T20:58:54.363",
"Id": "447285",
"Score": "1",
"body": "I wouldn't try to use VBA to follow the patterns in that book unless VBA is the only programming language you know. As you already observed above you can't do some of the things you need to for that book. FYI some patterns are language specific. Head First Design Patterns does not discuss all design patterns but it can get you started."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T21:16:52.327",
"Id": "447291",
"Score": "1",
"body": "@pacmaninbw - VBA is all I know and plan to know; HFDP seemed like a place to get started. I recognize that there may be things that may not be possible at all in VBA, but I am sure there is much in the book that can be. As I have seen from Mathieu, VBA can do quite a bit more than most folks think. My sense is that using a pattern in VBA just takes some juggling to get it to be properly implemented. Thank you for your input."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:29:42.697",
"Id": "229812",
"Score": "5",
"Tags": [
"object-oriented",
"design-patterns",
"vba"
],
"Title": "Extending VBA classes with Behavioral Patterns"
}
|
229812
|
<p>I recently discovered that it is much faster to generate primes using a Sieve of Eratosthenes (SoE) with a boolean array data structure than with a heap. Since then I have been looking for fast and scalable implementations. The fastest Python version I found is <a href="https://programmingpraxis.com/2012/01/06/pritchards-wheel-sieve/" rel="nofollow noreferrer">here</a> in a comment by Willy Good.</p>
<p>But Willy's code is just to demonstrate how wheel factorization works, I believe. It uses O(n) memory. When I run it for n > 2.5e9 or so, my laptop with 8G of RAM starts to thrash (excessive paging). </p>
<p>I realize that using a segmented SoE makes it scalable, so I experimented with simple segmented sieves. That eliminated the thrashing for big N but was considerably slower than using mod 30 wheel factorization. </p>
<p>My next goal was to find a combination of wheel factorization and segmentation. Kim Walisch's <a href="https://github.com/kimwalisch/primesieve" rel="nofollow noreferrer">primesieve</a> is a great example in C++ with very helpful doc, and Gordon B Good has a fast <a href="https://stackoverflow.com/a/57108107/11943198">javascript version</a>, but I couldn't find anything for Python. Here is my version (sorry for the length):</p>
<pre><code>#!/usr/bin/python3 -Wall
# program to find all primes up to and including n, using a segmented wheel sieve
from sys import argv, stdout
from bitarray import bitarray
# Counts and optionally prints all prime numbers no larger than 'n'
#CUTOFF = 10 # for debugging only
#SIEVE_SIZE = 2 # for debugging only
CUTOFF = 1e4
SIEVE_SIZE = 2**20
GHz = 1.6 # on my i5-6285U laptop
# mod 30 wheel constant arrays
modPrms = [7,11,13,17,19,23,29,31]
modPrmsM30 = [7,11,13,17,19,23,29,1]
gaps = [4,2,4,2,4,6,2,6,4,2,4,2,4,6,2,6] # 2 loops for overflow
ndxs = [0,0,0,0,1,1,2,2,2,2,3,3,4,4,4,4,5,5,5,5,5,5,6,6,7,7,7,7,7,7]
rnd2wh = [7,7,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,3,4,4,5,5,5,5,6,6,6,6,6,6]
def num2ix(n):
"""Return the wheel index for n."""
n = n - 7 # adjust for wheel starting at 1st prime past 2,3,5 vs. 0
return (n//30 << 3) + ndxs[n % 30]
def ix2num(i):
"""Return a number matching i (a wheel index)."""
return 30 * (i >> 3) + modPrms[i & 7]
def progress(j, num_loops, enabled):
"""Display a progress bar on the terminal."""
if enabled:
size = 60
x = size*j//num_loops
print("%s[%s%s] %i/%i\r" % ("Sieving: ", "#"*x, "."*(size-x), j, num_loops), end=' ')
stdout.flush()
def prime_gen_wrapper(n):
"""Decide whether to use the segmented sieve or a simpler version. Stops recursion."""
if n < CUTOFF:
return smallSieve(n+1) # rwh1 returns primes < N. We need sieving primes <= sqrt(limit)
else:
return segmentedSieve(n)
def smallSieve(n):
"""Returns a list of primes less than n."""
# a copy of Robert William Hanks' rwh1 used to get sieving primes for smaller ranges
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
sieve = [True] * (n//2)
for i in range(3,int(n**0.5)+1,2):
if sieve[i//2]:
sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]]
def segmentedSieve(limit, statsOnly = False):
"""
Sieves potential prime numbers up to and including limit.
statsOnly (default False) controls the return.
when False, returns a list of primes found.
when True, returns a count of the primes found.
"""
# segmentation originally based on Kim Walisch's simple C++ example of segmantation found here
# https://github.com/kimwalisch/primesieve/wiki/Segmented-sieve-of-Eratosthenes
# mod 30 wheel factorization based on a non-segmented version found here in a comment by Willy Good
# https://programmingpraxis.com/2012/01/06/pritchards-wheel-sieve/
sqrt = int(limit ** 0.5)
lmtbf = SIEVE_SIZE * 8
while (lmtbf >> 1) >= limit:
lmtbf >>= 1 # adjust the sieve size downward for small N
multiples = []; wx = []
outPrimes = [2,3,5] # the wheel skips multiples of these, but they may be needed as output
count = len(outPrimes)
lim_ix = num2ix(limit)
buf = bitarray(lmtbf)
show_progress = False
if statsOnly: # outer loop?
print("sieve size:", end=' ')
ss = len(memoryview(buf))
if ss > 1024:
print(ss//1024, "KB")
else:
print(ss, "bytes")
if limit > 1e8:
show_progress = True
num_loops = (lim_ix + lmtbf - 1)//(lmtbf) # round up
# get sieving primes recursively, skipping those eliminated by the wheel
svPrimes = prime_gen_wrapper(sqrt)[count:]
for lo_ix in range(0, lim_ix + 1, lmtbf): # loop over all the segments
low = ix2num(lo_ix)
high = ix2num(lo_ix + lmtbf) - 1
buf.setall(True)
progress(lo_ix//(lmtbf), num_loops, show_progress)
# generate new multiples of sieving primes and wheel indices needed in this segment
for p in svPrimes[len(multiples):]:
pSquared = p * p
if pSquared > high:
break
multiples.append(pSquared)
wx.append(num2ix(p) & 7)
# sieve the current segment
for x in range(len(multiples)):
s = multiples[x]
if s <= high:
p = svPrimes[x]
ci = wx[x]
s -= 7
p8 = p << 3
for j in range(8):
c = (s//30 << 3) + ndxs[s % 30] - lo_ix
# buf[c::p8] = False * ((lmtbf - c) // p8 + 1)
buf[c::p8] = False # much simpler with bitarray vs. pure python
s += p * gaps[ci]; ci += 1
# calculate the next multiple of p to sieve in an upcoming segment and its wheel index
f = (high + p - 1)//p # next factor of a multiple of p past this segment
f_mod = f % 30
i = rnd2wh[f_mod] # round up to next wheel index to eliminate multiples of 2,3,5
nxt = p * (f - f_mod + modPrmsM30[i]) # back to a normal multiple of p past this segment
wx[x] = i # save wheel index
multiples[x] = nxt # ... and next multiple of p
# handle any extras in the last segment
if high > limit:
top = lim_ix - lo_ix
else:
top = lmtbf -1
# collect results from this segment
if statsOnly:
count += buf[:top+1].count()
else:
for i in range(top + 1):
if buf[i]:
x = i + lo_ix
p = 30 * (x >> 3) + modPrms[x & 7] # ix2num(x) inlined, performance is sensitive here
outPrimes.append(p)
if show_progress:
progress(num_loops, num_loops, True)
print()
if statsOnly:
return count
else:
return outPrimes
# Driver Code
if len(argv) < 2:
a = '1e8'
else:
a = argv[1]
n = int(float(a))
from math import log
from time import time
#from datetime import timedelta
start = time()
count = segmentedSieve(n, statsOnly = True)
elapsed = time() - start
BigOculls = n * log(log(n,2),2)
cycles = GHz * 1e9 * elapsed
cyclesPerCull = cycles/BigOculls
print(count, "primes found <=", a)
print("%.3f seconds, %.2f cycles per Big-O cull" %(elapsed, cyclesPerCull))
if count < 500:
print(segmentedSieve(n))
</code></pre>
<p>Is anyone aware of another Python prime generator that is segmented and faster for large sizes? Any ideas to speed this one up, or make the code more compact or more clear? I had been using Willy Good's mod 30 unsegmented wheel sieve for smallSieve() here because it is faster, but Robert William Hank's primes_rwh1 is more compact and nearly as good for big N. I am not necessarily tied to using a mod 30 wheel; if someone is aware of a faster implementation and can demonstrate that it beats Willy's code with a benchmark, I am all ears. </p>
<p>If I didn't care somewhat about code size, I would implement some features found in Kim Walisch's primesieve, such as:</p>
<ul>
<li>pre_sieving for primes up to 19, then copying the result into each segment</li>
<li>dividing up the sieving primes into small, medium, and large sizes, and processing each group differently</li>
</ul>
<p>...but this is probably too long already.</p>
<p>Originally I wanted this to be pure Python but I realized that the bitarray package fit my needs well. </p>
<p><strong>EDIT</strong></p>
<p>Some benchmarks against Willy Good's unsegmented mod 30 wheel sieve, the fastest Python implementation I'm currently aware of for smaller sizes. Willy's is prime_wheel.py, the segmented wheel sieve is prime_ba.py (ba == bitarry, the last significant change). First at 1 million:</p>
<pre><code>$ time ./prime_ba.py 1e6
sieve size: 1024 KB
78498 primes found <= 1e6
0.032 seconds, 11.68 cycles per Big-O cull
real 0m0.064s
user 0m0.031s
sys 0m0.000s
$ time ./prime_wheel.py 1e6
78498 primes found <= 1e6
real 0m0.053s
user 0m0.016s
sys 0m0.031s
</code></pre>
<p>The unsegmented wheel sieve is a little faster than my segmented version. But both run in under .1 sec so I'm not too worried. Next at 100 million:</p>
<pre><code>$ time ./prime_ba.py 1e8
sieve size: 1024 KB
5761455 primes found <= 1e8
0.290 seconds, 0.98 cycles per Big-O cull
real 0m0.322s
user 0m0.297s
sys 0m0.016s
$ time ./prime_wheel.py 1e8
5761455 primes found <= 1e8
real 0m2.789s
user 0m2.500s
sys 0m0.281s
</code></pre>
<p>This is starting to show the effects of the different memory footprints. The segmented version is only using 1M of RAM for sieving, the unsegmented version uses O(n) memory. That is my incentive for creating this version. At 10 billion:</p>
<pre><code>$ time ./prime_ba.py 1e10
sieve size: 1024 KB
Sieving: [############################################################] 318/318
455052511 primes found <= 1e10
33.420 seconds, 1.06 cycles per Big-O cull
real 0m33.451s
user 0m33.297s
sys 0m0.016s
$ time ./prime_wheel.py 1e10
^C^CTraceback (most recent call last):
File "./prime_wheel.py", line 36, in <module>
for x in primes235(n):
File "./prime_wheel.py", line 22, in primes235
buf[c::p8] = [False] * ((lmtbf - c) // p8 + 1)
KeyboardInterrupt
^C
real 3m16.165s
user 0m32.734s
sys 2m15.953s
</code></pre>
<p>The segmented version chugs along, still using a 1MB sieve. The unsegmented version uses all of my 8G of RAM, the system starts to page excessively, the fan shifts into high gear. I hit ctrl-C several times to get out of it after 3 minutes. The "sys" time is now dominant due to the paging.</p>
<p><strong>EDIT 2</strong></p>
<p>Replaced the code with a new version to:</p>
<ul>
<li>fix an off-by-one error calling smallSieve() a.k.a. rwh1_primes, which generates primes less than N. When it is used to generate sieving primes, we need to get all of the primes up to and including N, the integer square root of the input limit. External symptom: some composite numbers are reported as primes.</li>
<li>shrink the bitarray when it is much larger than needed for the input limit. This results in a dramatic speedup for smaller sizes since the entire bitarray is always sieved to simplify the segmentation loop.</li>
<li>report the sieve size in bytes when appropriate due to the previous change</li>
<li>a few minor cleanups</li>
</ul>
<p>If anyone is interested in seeing a diff of the changes, please let me know in the comments.</p>
<p><strong>EDIT 3</strong></p>
<ul>
<li>Replaced the code with a Python 3 version. "2to3-2.7" made the conversion much easier than I feared. Once 2to3 was done, about all I had to do was change "/" to "//" in bunches of places to get integer/floor division and test it. Thanks again @GZ0 for pointing out how soon Python 2.7 support is going away.</li>
<li>Moved the code to calculate the total number of segments for the progress bar from the segmentation loop itself and into the the initialization (blush).</li>
<li>Add some rudimentary docstrings. </li>
</ul>
<p><strong>EDIT 4</strong></p>
<p>A new OO version incorporating changes suggested by @QuantumChris is available <a href="https://codereview.stackexchange.com/q/230220/210384">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:02:10.737",
"Id": "447271",
"Score": "2",
"body": "downvote with no comment? Could there be trolls with bots lurking here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T00:08:27.303",
"Id": "447314",
"Score": "1",
"body": "[This post](https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/2073279#2073279) may be helpful for you. BTW, Python 2 [will not be maintained past 2020](https://www.python.org/dev/peps/pep-0373/). If you are not going to work with legacy Python code I do not see any good reason not to use Python 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T00:41:07.440",
"Id": "447316",
"Score": "1",
"body": "@GZ0, thanks for looking. I did spend a lot of time looking at the entire post you referenced. That's where I found Robert WIlliam Hank's rwh1_primes that I'm using in smallSieve. The highest ranked answer to that post contains a benchmark showing that rwh1_primes beats sunaraman3 by about 4x. \n\nregarding Python 3: dang! Support is a compelling feature. I better start learning it, even though I don't feel I know Python 2.7 well enough yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T08:20:56.637",
"Id": "447910",
"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 you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Code edits after answers have been posted are not acceptable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:52:16.927",
"Id": "447967",
"Score": "0",
"body": "@Mast OK, will do, sorry. I'm a newbie here. I actually posted new code again before noticing your comment. I will ask new questions going forward"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:58:43.027",
"Id": "447968",
"Score": "0",
"body": "@Mast code rolled back, per the guidelines"
}
] |
[
{
"body": "<p>Hi welcome to code review! Interesting topic, I remember writing some different prime sieves for project Euler problems.</p>\n\n<p>Stylistically, it would really help to use <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It's python's standard style-guide which helps readability for yourself and others. Things like imports at the top, consistent naming, etc.</p>\n\n<p>There are a few places where I think ternary operators would really clean up the code: e.g.</p>\n\n<pre><code>if statsOnly:\n return count\nelse:\n return outPrimes\n</code></pre>\n\n<p>would be replaced with</p>\n\n<pre><code>return count if statsOnly else outPrimes\n</code></pre>\n\n<p>You have a lot of variables and code floating around outside of functions. I think a class would serve well to fix this. You could have your <code>modPrms</code>, <code>modPrmsM30</code> etc as class or instance variables and the functions like <code>num2ix()</code> as methods of the class. A rough outline of the class might be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class PrimeSieve:\n\n def __init__(self):\n self.cutoff = 1e4\n self.sieve_size = 2 ** 20\n self.clock_speed = 1.6 # In GHz\n\n # mod 30 wheel constant arrays\n self.mod_primes = [7, 11, 13, 17, 19, 23, 29, 31]\n self.mod_primes_m30 = [7, 11, 13, 17, 19, 23, 29, 1]\n self.gaps = [4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 4, 6, 2, 6] # 2 loops for overflow\n self.ndxs = [0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7]\n self.rnd2wh = [7, 7, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6]\n\n def num2ix(self, n):\n \"\"\"Return the wheel index for n.\"\"\"\n # Adjust for wheel starting at 1st prime past 2,3,5 vs. 0\n n -= 7\n return (n // 30 << 3) + self.ndxs[n % 30]\n\n ...\n\n</code></pre>\n\n<p>You could also provide things like clock_speed as arguments which might be preferred (just put these into the init arguments):</p>\n\n<pre><code>def __init__(self, cutoff, sieve_size, clock_speed):\n ...\n</code></pre>\n\n<p>It seems weird to me to have <code>progress()</code> contain an <code>enabled</code> argument which basically decides whether anything is done at all. I would remove this argument, and simply wrap the function call with an <code>if</code>. For displaying progress I'd also highly recommend using <a href=\"https://pypi.org/project/tqdm/\" rel=\"nofollow noreferrer\">tqdm</a> which is made for exactly this kind of thing. <code>print()</code> also has a <code>flush</code> argument which will flush output. If you don't want to use tqdm, switch to using f-strings or <code>.format()</code> which are much more readable than the old <code>%</code> style you're using.</p>\n\n<p>You can add file <code>\"\"\"docstrings\"\"\"</code> just as you have function docstrings. These sit at the top of the file and are preferred over introductory comments.</p>\n\n<p>Timing functions and methods is often done well using decorators. These wrap methods allowing you to execute code before and after their execution which is helpful for timing, logging and all sorts of other things. The following is a simple example I use a lot. It can be applied to functions and methods:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import wraps\n\n\ndef timer_func(orig_func):\n \"\"\"\n Prints the runtime of a function when applied as a decorator (@timer_func).\n \"\"\"\n\n @wraps(orig_func)\n def wrapper(*args, **kwargs):\n\n t1 = time()\n result = orig_func(*args, **kwargs)\n t2 = time() - t1\n\n print(f'{orig_func.__qualname__} ran in: {t2} seconds.')\n\n return result\n return wrapper\n</code></pre>\n\n<p>You could write another decorator which counts the number of calls of a function, <a href=\"https://stackoverflow.com/questions/9158294/good-uses-for-mutable-function-argument-default-values\">see here</a>.</p>\n\n<p>Your variable naming could be much improved. It should be obvious what everything is. <code>GHz</code> -> <code>clock_speed</code>; <code>modPrms</code> -> <code>mod_primes</code> <code>rnd2wh</code> -> literally anything else. Using <code>i</code>, <code>j</code> or <code>x</code> is fine for small one-off index names or iterables but not for such huge sections of code.</p>\n\n<p>The variable <code>low</code> is declared but not used. This may be a bug.</p>\n\n<p>If you want to iterate over an object and get its indices, use <code>enumerate()</code>:</p>\n\n<pre><code>for i, multiple in enumerate(multiples):\n ...\n</code></pre>\n\n<p><code>segmented_sieve()</code> should really be broken up. You have a lot of code here for processing, printing, formatting ... Try to have your functions perform single, short tasks. This also makes it much easier to convert functions to generators as you don't need to jump in and out, you can often just swap a <code>return</code> for a <code>yield</code> and call it as an iterable. Modularity also helps with readability, debugging, testing and extending. </p>\n\n<p>It's recommended to wrap code you call in <code>if __name__ == '__main__':</code> See <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">this</a> excellent answer for why.</p>\n\n<p>There's more to be said but I have to go for now; I may add more comments later. Feel free to post another question with the above changes where you may get more specific feedback on optimisations and such.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T17:18:14.780",
"Id": "447510",
"Score": "1",
"body": "thanks much for the review. I'm on it! I did try PEP8 already, hence all the spaces in the constant arrays but then it complained about line length. As you can probably tell I'm still fairly new to Python. I will be benchmarking regularly as I go. I tried using named tuples as a substitute for C structs to group sieving primes, wheel indices, and prime multiples, but then the performance tanked due to all the new() operations; back to three separate lists :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T17:30:08.367",
"Id": "447513",
"Score": "0",
"body": "@GregAmes If you want to make C-style structs, `__slots__` might help. It fixes what the class will contain so there's less overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T17:34:46.467",
"Id": "447514",
"Score": "1",
"body": "I'll check out ```__slots__ ```. Thanks for the tip."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:32:08.803",
"Id": "447529",
"Score": "0",
"body": "I'll be away/offline until tomorrow. My boat needs some patches and it's a 2.5hr drive to the coast. I should be back at this tomorrow p.m."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:56:31.493",
"Id": "447738",
"Score": "0",
"body": "re: low. a leftover that used to control the segmentation loop. I'm really surprised the -Wall option on the shebang line didn't give me a warning about that. In fact, I don't recall -Wall giving me any warnings (!?!?!) How did you identify that low is unused?\n\nmodularity/small chunks: yep I agree, no philosophical problem there. It's just a matter of how to accomplish it with no/negligible performance impact,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T02:32:40.197",
"Id": "447894",
"Score": "0",
"body": "*You could have your modPrms, modPrmsM30 etc as class variables* The provided code does not agree with this design. It uses the variables as instance variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:24:06.247",
"Id": "447920",
"Score": "0",
"body": "@GZ0 Thanks, corrected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:26:56.147",
"Id": "447921",
"Score": "0",
"body": "@QuantumChris Actually I think class variables are more appropriate in this case. Instance variables like that are normally initialized using init arguments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T10:27:00.933",
"Id": "447923",
"Score": "0",
"body": "@GregAmes I use an IDE, Pycharm which identifies errors and warnings such as unused variables. IDEs in general are extremely helpful for coding; Pycharm's a common choice for Python and has a free community edition."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:42:56.477",
"Id": "229915",
"ParentId": "229813",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229915",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:59:04.770",
"Id": "229813",
"Score": "8",
"Tags": [
"python",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Segmented and wheel factorized prime generator in Python"
}
|
229813
|
<p>I'm a beginner programmer that's really motivated at the moment. I made this in two days and I'm really proud of it because I never used any tutorials or any online help. Just good ol' grey matter and for real I think I did a much better job than my last game thanks to you guys! I really appreciate the feedback on my last code, it really helped me.</p>
<blockquote>
<p>The game consists of having the largest card. So for example, if I
have A and you have, say 9, you lose because A is "bigger" than 9 and
so on. For physical game play you take one card at a time from a deck
and the biggest card wins.</p>
</blockquote>
<p>This is my code and it's working correctly.</p>
<pre><code>import string
import random
# Main game Loop
def game():
#Make the Cards
def make_cards():
cards = []
suits = ["◆", "♥", "♠", "♣"]
for suit in suits:
for i in range(2, 11):
card_id = str(i) + suit
if i == 10:
cards.append(card_id + " " + card_id + "\n\n" " tony " "\n\n" + card_id + " " + card_id + "\n" )
else:
cards.append( card_id + " " + card_id + "\n\n" " tony " "\n\n" + card_id + " " + card_id + "\n" )
for suit in suits:
for i in ["J","Q","K","A"]:
card_id = i + suit
cards.append( card_id + " " + card_id + "\n\n" + " tony " "\n\n" + card_id + " " + card_id + "\n" )
return cards
cards = make_cards()
# Distribute the cards
def play_cards(cards):
card_shuffle = [random.choice(cards) for i in cards]
play_cards.p1 = card_shuffle[0:26]
play_cards.p2 = card_shuffle[26:52]
return play_cards.p1, play_cards.p2
play_cards(cards)
# Show cards in game
def card_dump(input, p1, p2):
if input == "":
win_add()
return (
print(game_logic()),
print("\n"),
print(" __________________________________"),
print("| WIN COUNTER DELUXE |"),
print("".join(win_add.p1)),
print("|__________________________________|"),
print("\n"),
print(" Player One Card\n"),
print(p1[0]),
print("\n"),
print(" __________________________________"),
print("| WIN COUNTER DELUXE |"),
print("".join(win_add.p2)),
print("|__________________________________|"),
print("\n"),
print(" Player Two Card\n"),
print(p2[0]),
play_cards.p1.pop(0),
play_cards.p2.pop(0)
)
who_won = []
# Game logic
def game_logic():
p1 = play_cards.p1[0][:1]
p2 = play_cards.p2[0][:1]
letter_value = {"A": 13, "K":12, "Q":11, "J":10}
if p1 == "1":
p1 = "10"
if p2 == "1":
p2 = "10"
if p1 == p2:
who_won.append(0)
elif p1.isdigit() == True and p2.isdigit() == True:
if int(p1) > int(p2):
who_won.append(1)
else:
who_won.append(2)
elif p1.isdigit() == False and p2.isdigit() == False:
if letter_value[p1] > letter_value[p2]:
who_won.append(1)
else:
who_won.append(2)
elif p1.isdigit() == True and p2.isdigit() == False:
if int(p1) > int(letter_value[p2]):
who_won.append(1)
else:
who_won.append(2)
elif p1.isdigit() == False and p2.isdigit() == True:
if int(p2) > int(letter_value[p1]):
who_won.append(2)
else:
who_won.append(1)
return ""
game_logic()
# Return the list of how many times each player won
def end_game():
return who_won
# Game score board "Win Counter Deluxe"
def win_add():
win_add.p1 = []
win_add.p2 = []
for i in who_won:
if 1 == i:
win_add.p1.append( " |")
elif 2 == i:
win_add.p2.append(" |")
return win_add.p1, win_add.p2
# Outcome Loop
p1 = play_cards.p1
p2 = play_cards.p2
x = end_game()
count = 0
while True:
if count == 26:
p1_won = x.count(1)
p2_won = x.count(2)
draws = x.count(0)
if p1_won == p2_won:
print(f"The game finished in a DRAW. {p1_won} VS {p2_won}")
break
elif p1_won > p2_won:
print(f"Player // ONE // won the game with {p1_won} wins VS {p2_won} for player // TWO //. There were {draws} draws.")
break
else:
print(f"Player // TWO // won the game with {p2_won} wins VS {p1_won} wins for player // ONE //. There were {draws} draws.")
break
card_dump(input("Please hit enter"),p1, p2)
count += 1
def main():
game()
while "y" in input("Play again? [Y/n]").lower():
game()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>You have a lot of places where you do something like</p>\n\n<pre><code>if int(p1) > int(p2):\n who_won.append(1)\nelse:\n who_won.append(2)\n</code></pre>\n\n<p>There's more duplication than necessary here. At the very least, you should move the call to <code>append</code> out so it's only called once. If you every change how <code>who_won</code> works, you don't want to have to change a ton of things all over. The less places you use it the easier it will be to refactor later. You can use a conditional expression here:</p>\n\n<pre><code>who_won.append(1 if int(p1) > int(p2) else 2)\n</code></pre>\n\n<hr>\n\n<p>You're comparing against <code>True</code> in a few places:</p>\n\n<pre><code>elif p1.isdigit() == True and p2.isdigit() == True:\n</code></pre>\n\n<p>This is unnecessary. <code>if</code> already interprets what you give it as either \"truthy\" or \"falsey\". <code>== True</code> is redundant. Just reduce it to:</p>\n\n<pre><code>elif p1.isdigit() and p2.isdigit():\n</code></pre>\n\n<p>That reads much more fluently anyways.</p>\n\n<hr>\n\n<p>At the top, you have a giant chunk consisting of calls to <code>print</code>:</p>\n\n<pre><code>print(game_logic()),\nprint(\"\\n\"),\nprint(\" __________________________________\"),\nprint(\"| WIN COUNTER DELUXE |\"),\n. . .\n</code></pre>\n\n<p>Calling <code>print</code> excessively isn't a good idea, even though it won't really matter here. I would expect it to be more performant (and more readable) to use a single <code>print</code> with a <code>sep=\"\\n\"</code> argument passed:</p>\n\n<pre><code>print(game_logic(),\n \"\\n\",\n \" __________________________________\",\n \"| WIN COUNTER DELUXE |\",\n . . .\n sep=\"\\n\") # sep=\"\\n\" tells it to insert a newline between arguments\n</code></pre>\n\n<hr>\n\n<pre><code>card_shuffle = [random.choice(cards) for i in cards]\n</code></pre>\n\n<p>This doesn't seem like a \"shuffle\". This will, unless I'm overlooking something, not return a list with the original proportion of cards. It will randomly have more of different cards than others. Just use <a href=\"https://docs.python.org/3.7/library/random.html#random.shuffle\" rel=\"nofollow noreferrer\"><code>random.shuffle</code></a>:</p>\n\n<pre><code>random.shuffle(cards) # Shuffles inplace instead of returning a new list.\n</code></pre>\n\n<p>If you wanted to avoid mutating the original, just <a href=\"https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list\">make a copy first</a>:</p>\n\n<pre><code>random.shuffle(cards[:])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T00:59:39.673",
"Id": "229829",
"ParentId": "229822",
"Score": "4"
}
},
{
"body": "<h1>Style</h1>\n\n<p>I suggest you check <strong>PEP0008</strong> <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide which will be very useful when it comes to writing a more Pythonic code.</p>\n\n<ul>\n<li><p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. I see you wrote many comments above each of your functions and I suggest to include docstrings instead for these functions indicating what they do and what they return and type hints(if necessary when functions have many parameters).</p>\n\n<p><strong>example:</strong></p>\n\n<pre><code>def make_cards():\n \"\"\"Return deck of cards\"\"\"\n # do things\n</code></pre></li>\n<li><p><strong>Too many blank lines:</strong> according to PEP0008: Surround top-level function and class definitions with two blank lines.Method definitions inside a class are surrounded by a single blank line.Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).</p></li>\n<li><p><strong>Nested functions:</strong> since most of your functions do not have any parameters, there is no need for nested functions that complicate the code, unless your program has many aspects and needs many functions then you might consider using a class(which is not needed in your case). Nested functions are usually short and very specific in what they do (Usually they use the parameters of the enclosing function and do a specific task which is not the case here).</p></li>\n<li><p><strong>Long lines: (lines 174, 178)</strong></p>\n\n<pre><code>print(f\"Player // ONE // won the game with {p1_won} wins VS {p2_won} for player // TWO //. There were {draws} draws.\") \n</code></pre>\n\n<p>According to PEP0008 a line should contain 79 characters max.</p></li>\n<li><p><strong>Space around operators:</strong> <code>card_dump(input(\"Please hit enter\"),p1, p2)</code>\na space should be left on both sides of a binary operator(+-*/,=><|^&!=) for readability.</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<p>From my understanding the game is all about a 2-player card virtual game that keeps displaying cards and calculates a score at the end. I think this code can be shortened, let's dissect your program parts:</p>\n\n<pre><code>def make_cards():\n # do stuff\n</code></pre>\n\n<p>Since no docstrings are included, I'm going to imply what they might be intended to do: this function creates 52 cards and returns a list with a very non-readable content.</p>\n\n<p>a sample of what is returned : </p>\n\n<p>['2◆ 2◆\\n\\n tony \\n\\n2◆ 2◆\\n', '3◆ 3◆\\n\\n tony \\n\\n3◆ 3◆\\n', '4◆ 4◆\\n\\n tony \\n\\n4◆ 4◆\\n', '5◆ 5◆\\n\\n tony \\n\\n5◆ 5◆\\n', '6◆ 6◆\\n\\n tony \\n\\n6◆] </p>\n\n<p>This is a very hurting my eyes to read and this might be very annoying to debug (if not impossible), I suggest you create the deck in the following way:</p>\n\n<pre><code>def deck():\n \"\"\"Return a list of 52-cards deck.\"\"\"\n suits = '◆♥♠♣'\n digits = [str(number) for number in range(2, 11)]\n specials = 'AKQJ'\n special_cards = [special + suit for special in specials for suit in suits]\n numbered_cards = [number + suit for number in digits for suit in suits]\n return special_cards + numbered_cards \n</code></pre>\n\n<p><strong>returns:</strong> <code>['A◆', 'A♥', 'A♠', 'A♣', 'K◆', ...]</code> which is much more readable and has the same use.</p>\n\n<p>The <code>play_cards()</code> function:\nDoes not return the full deck and if you want to check yourself, try running the following line:</p>\n\n<pre><code>print(len(set(play_cards(cards)[0])), len(set(play_cards(cards)[1])))\n</code></pre>\n\n<p><strong>output:</strong> 21 22 (43 cards instead of 52) and it will return different results of course each time you try running it, so it does not even return the full shuffled deck.</p>\n\n<p>To fix the problem I suggest you use <code>random.shuffle()</code></p>\n\n<pre><code>random.shuffle(cards)\n</code></pre>\n\n<p>then the <code>play_cards()</code> function is unecessary and you can shuffle the cards before returning them in the <code>make_cards()</code> function (the one I called <code>deck()</code>)</p>\n\n<p><strong>in the <code>game_logic()</code> function:</strong></p>\n\n<pre><code>elif p1.isdigit() == False and p2.isdigit() == False:\n</code></pre>\n\n<p>this line repeated several times in different forms, here's the correct way of writing it:</p>\n\n<pre><code>if not p1.isdigit() and not p2.isdigit():\n</code></pre>\n\n<p><strong>Here's an improved version of the code:</strong></p>\n\n<pre><code>import random\n\n\ndef deck():\n \"\"\"Return a list of 52-card deck.\"\"\"\n suits = '◆♥♠♣'\n digits = [str(number) for number in range(2, 11)]\n specials = 'AKQJ'\n special_cards = [special + suit for special in specials for suit in suits]\n numbered_cards = [number + suit for number in digits for suit in suits]\n cards = special_cards + numbered_cards\n return cards\n\n\ndef get_winner(card1, card2):\n \"\"\"Determine winner and return 1 or 2 or 0 for a tie.\"\"\"\n suit_ranks = {'♣': 1, '◆': 2, '♥': 3, '♠': 4}\n special_ranks = {'J': 1, 'Q': 2, 'K': 3, 'A': 4}\n if card1 == card2:\n return 0\n if card1[0].isdecimal() and card2[0].isalpha():\n return 2\n if card1[0].isalpha() and card2[0].isdecimal():\n return 1\n if card1[0].isdecimal() and card2[0].isdecimal():\n if int(card1[0]) > int(card2[0]):\n return 1\n if int(card1[0]) < int(card2[0]):\n return 2\n if card1[0].isalpha() and card2[0].isalpha():\n if special_ranks[card1[0]] > special_ranks[card2[0]]:\n return 1\n if special_ranks[card1[0]] < special_ranks[card2[0]]:\n return 2\n if card1[-1] != card2[-1] and card1[:-1] == card2[:-1]:\n if suit_ranks[card1[-1]] > suit_ranks[card2[-1]]:\n return 1\n if suit_ranks[card1[-1]] < suit_ranks[card2[-1]]:\n return 2\n\n\ndef play_game():\n \"\"\"Display rounds interactively and results at the end.\"\"\"\n cards = deck()\n rounds = input('Enter the number of rounds to play: ')\n while not rounds.isdecimal():\n print('Invalid rounds number')\n rounds = input('Enter the number of rounds to play: ')\n games_played = 0\n player1_score, player2_score = 0, 0\n while games_played < int(rounds):\n confirm_round = input(f'Press enter to display round {games_played} or q to exit: ')\n while confirm_round and confirm_round != 'q':\n confirm_round = input(f'Press enter to display round {games_played} or q to exit: ')\n if confirm_round == 'q':\n print('Thank you for playing cards.')\n print(30 * '=')\n exit(0)\n player1_card = random.choice(cards)\n player2_card = random.choice(cards)\n print(f'player 1 card: {player1_card}')\n print(f'player 2 card: {player2_card}')\n winner = get_winner(player1_card, player2_card)\n if winner == 0:\n print('Tie!')\n if winner == 1:\n print('Player 1 wins.')\n player1_score += 1\n if winner == 2:\n print('Player 2 wins.')\n player2_score += 1\n games_played += 1\n print(30 * '=', '\\n')\n print(30 * '=')\n print(f'Total rounds played: {games_played}')\n print(f'Player 1 {player1_score}-{player2_score} player 2')\n if player1_score > player2_score:\n print(f'Winner is Player 1 ({player1_score} out of {games_played} games played)')\n if player2_score > player1_score:\n print(f'Winner is Player 2 ({player2_score} out of {games_played} games played)')\n if player1_score == player2_score:\n print('Neither wins, TIE!')\n\n\nif __name__ == '__main__':\n play_game()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T03:54:56.063",
"Id": "229832",
"ParentId": "229822",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229832",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T21:16:17.947",
"Id": "229822",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"playing-cards"
],
"Title": "My second game: War Card game V.1"
}
|
229822
|
<p>I normally use MySQLi and this is my first time trying out PDO. I am doing this because this is my first web application that is going to be used by the public, hence I want it to be secure. The code I wrote, following a W3 tutorial is working flawlessly, however due to a few other posts on Stack Overflow I have read, I am worried it might not be as secure as I would like.</p>
<pre><code> <?php
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
include 'dbconfig.php';
$pickuploc = ($_POST['pickuploc']);
$droploc = ($_POST['droploc']);
$pickupdate = ($_POST['pickupdate']);
$pickuptime = ($_POST['pickuptime']);
$dropdate = ($_POST['dropdate']);
$droptime = ($_POST['droptime']);
$class = ($_POST['cclass']);
$numofdrivers = ($_POST['numdrivers']);
$coverage = ($_POST['coverage']);
$driversage = ($_POST['agedrivers']);
$roadsideass = ($_POST['roadsideass']);
$afterhoursdrop = ($_POST['afterhoursdrop']);
$promo = ($_POST['promo']);
$fname = ($_POST['fname']);
$lname = ($_POST['lname']);
$address = ($_POST['address']);
$city = ($_POST['city']);
$state = ($_POST['state']);
$country = ($_POST['country']);
$post = ($_POST['post']);
$dlnum = ($_POST['dlnum']);
$dlexpm = ($_POST['dlexpm']);
$dlexpy = ($_POST['dlexpy']);
$dlcountry = ($_POST['dlcountry']);
$phone = ($_POST['phone']);
$email = ($_POST['email']);
$addcomments = ($_POST['addcomments']);
$predropdatetime = $dropdate . " " . $droptime;
$date = new DateTime($predropdatetime);
$dropdatetime = $date->format('Y-m-d H:i:s');
$prepickupdatetime = $pickupdate . " " . $pickuptime;
$date = new DateTime($prepickupdatetime);
$pickupdatetime = $date->format('Y-m-d H:i:s');
$date = new DateTime('now');
$bookingdatetime = $date->format('Y-m-d H:i:s');
$dlexp = "20" . $dlexpy . "-" . $dlexpm . "-01";
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$remoteip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$remoteip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$remoteip = $_SERVER['REMOTE_ADDR'];
}
$date = new DateTime($pickupdate);
$sqlpickupdate = $date->format('Y-m-d');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "SELECT COUNT(*) AS num FROM blackout WHERE :pickupdate BETWEEN start_date AND end_date AND city=:pickuploc AND class=:class";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':class', $class);
$stmt->bindValue(':pickupdate', $sqlpickupdate);
$stmt->bindValue(':pickuploc', $pickuploc);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
$blackout = true;
} else{
$blackout = false;
}
$conn = null;
if ((($dlcountry == "US" || $dlcountry == "JP") && ($driversage == "19" || $driversage == "20") && $coverage == "inclusive") || ($class == "suv" || $class == "minivan" || $class == "convert") && ($driversage == "19" || $driversage == "20") || ($pickuploc == "oc") || ($blackout == true)) {
echo "RESERVATION NOT BOOKED YOU NEED TO TAKE ACTION!!<br><br><br>";
$status = "Unconfirmed";
}else{
$status = "Confirmed";
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO reservations (bookingdatetime, firstname, lastname, address, city, state, country, post, dlnum, dlexp, dlcountry, phone, email, addcomments, pickuploc, droploc, pickupdatetime, dropdatetime, class, numofdrivers, coverage, driversage, roadsideass, afterhoursdrop, promo, status, remoteip)
VALUES (:bookingdatetime, :firstname, :lastname, :address, :city, :state, :country, :post, :dlnum, :dlexp, :dlcountry, :phone, :email, :addcomments, :pickuploc, :droploc, :pickupdatetime, :dropdatetime, :class, :numofdrivers, :coverage, :driversage, :roadsideass, :afterhoursdrop, :promo, :status, :remoteip)");
$stmt->bindParam(':bookingdatetime', $bookingdatetime);
$stmt->bindParam(':firstname', $fname);
$stmt->bindParam(':lastname', $lname);
$stmt->bindParam(':address', $address);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':state', $state);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':post', $post);
$stmt->bindParam(':dlnum', $dlnum);
$stmt->bindParam(':dlexp', $dlexp);
$stmt->bindParam(':dlcountry', $dlcountry);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':addcomments', $addcomments);
$stmt->bindParam(':pickuploc', $pickuploc);
$stmt->bindParam(':droploc', $droploc);
$stmt->bindParam(':pickupdatetime', $pickupdatetime);
$stmt->bindParam(':dropdatetime', $dropdatetime);
$stmt->bindParam(':class', $class);
$stmt->bindParam(':numofdrivers', $numofdrivers);
$stmt->bindParam(':coverage', $coverage);
$stmt->bindParam(':driversage', $driversage);
$stmt->bindParam(':roadsideass', $roadsideass);
$stmt->bindParam(':afterhoursdrop', $afterhoursdrop);
$stmt->bindParam(':promo', $promo);
$stmt->bindParam(':status', $status);
$stmt->bindParam(':remoteip', $remoteip);
// insert a row
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Database Error: " . $e->getMessage();
}
$conn = null;
echo "pick up location: " . $pickuploc . "<br> drop off locaiton: " . $droploc . "<br>pick up date: " . $pickupdate . "<br>pick up time: " . $pickuptime . "<br>drop date: " . $dropdate . "<br>drop time: " . $droptime . "<br>class: " . $class . "<br> number of drivers: " . $numofdrivers . "<br> coverage: " . $coverage . "<br>drivers age: " . $driversage . "<br>roadside assitance: " . $roadsideass . "<br>after hours drop:" . $afterhoursdrop . "<br>promo: " . $promo ."<br><br>first name: " . $fname . "<br>last name: " . $lname . "<br>address: " . $address . "<br>city: " . $city . "<br>state: " . $state . "<br>country: " . $country . "<br>post code: " . $post . "<br>dl number: " . $dlnum . "<br>dl exp month: " . $dlexpm . "<br>dl exp yesr: " . $dlexpy . "<br>dl country: " . $dlcountry . "<br>phone: " . $phone . "<br>email: " . $email . "<br>add comments: " . $addcomments;
</code></pre>
|
[] |
[
{
"body": "<p>You are missing charset in your DSN and you have emulated prepared statements still on. This could potentially leave your vulnerable to SQL injection. See <a href=\"https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection\">Are PDO prepared statements sufficient to prevent SQL injection?</a><br>\nAs I have pointed out to you in an <a href=\"https://stackoverflow.com/a/58142127/1839439\">answer on Stack Overflow</a> you should set the proper charset and disable emulated prepared statements. </p>\n\n<pre><code>$options = [\n \\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_DEFAULT_FETCH_MODE => \\PDO::FETCH_ASSOC,\n \\PDO::ATTR_EMULATE_PREPARES => false,\n];\n$conn = new \\PDO(\"mysql:host=$servername;dbname=$dbname;charset=utf8mb4\", $username, $password, $options);\n</code></pre>\n\n<p>I do not know why you have 2 PDO connections opened, you need only one. </p>\n\n<p>Also, you should enable error reporting for PDO and avoid using try-catch in your code, if all you do is display the error message on the screen.</p>\n\n<p>Using <code>bindParam</code> seems completely unnecessary. It would be much more readable to pass the values in <code>execute()</code></p>\n\n<p>Brackets around variables are just noise and serve no purpose. e.g. <code>($_POST['addcomments'])</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:50:55.290",
"Id": "447402",
"Score": "0",
"body": "(not a copy, takes me longer when answering from my phone on the train)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:58:32.293",
"Id": "447403",
"Score": "0",
"body": "@mickmackusa There are similarities, but far from a copy. I only added an answer, copying my comments, because nobody else seemed to do so, and I have no time for full Code Review. Safe journey!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T23:03:27.600",
"Id": "447404",
"Score": "0",
"body": "...ha, typically I don't either... got stuck on the train this morning due to electrical fault -- Stack Exchange wins!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:12:17.177",
"Id": "448238",
"Score": "1",
"body": "*\"Using bindParam seems completely unnecessary. It would be much more readable to pass the values in execute()\"* That only works correctly when or atleast adviced only when string based types are involved as you don't have to dependent on MySQL auto casting then.. Notice what the [manual](https://www.php.net/manual/en/pdostatement.execute.php) says *\"An array of values with as many elements as there are bound parameters in the SQL statement being executed. **All values are treated as PDO::PARAM_STR.**\"*"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:33:29.840",
"Id": "229881",
"ParentId": "229826",
"Score": "5"
}
},
{
"body": "<ol>\n<li>w3schools gets its placement from shelling out big bucks for high ranking in search engine results (as I've read), not for being the best resource for web development advice. When in doubt, read Stack Exchanges sites. SE sites enjoy the benefit of constant peer review. If something is not quite right, eventually a whistleblower is going to find it and call it out.</li>\n<li>There is no benefit to the parenthetical wrapping of the POST values -- this can be safely omitted. When declaring variables, use camelCase or snake_case for improved readability -- if done consistently through a project, you'll thank yourself later.</li>\n<li><p>Your <code>COUNT()</code> query is looking for a <code>true</code>|<code>false</code> determination; this can be simplified using this technique: <a href=\"https://stackoverflow.com/a/37958929/2943403\">https://stackoverflow.com/a/37958929/2943403</a> As a personal preference, passing an array to <code>execute()</code> is a superior syntax because it is less verbose.</p>\n\n<pre><code>$stmt = $conn->prepare(\n \"SELECT 1\n FROM blackout\n WHERE :pickupdate BETWEEN start_date AND end_date\n AND city = :pickuploc\n AND class = :class\"\n);\n$stmt->execute([\n 'class' => $class,\n 'pickupdate' => $sqlPickUpDate,\n 'pickuploc'=> $pickUpLoc,\n]);\n$blackout = (bool)$stmt->fetchColumn();\n</code></pre></li>\n<li>Definitely re-use the same connection variable, there is no benefit in grabbing another.</li>\n<li><p>Write your simplest / less-intensive conditions first and progress to expressions that involve function calls or relatively heavier processing. Using <code>in_array()</code> will spare your conditional expressions from being overloaded with lots of <code>&&</code>s and <code>||</code>s. Don't let your line width stretch on for too long, try to avoid doing a lot of horizontal scrolling when writing/reading your scripts. For my liking, your \"second half\" of conditions when determining if booking action is required, needs an additional set of parentheses to make the logic absolutely clear to humans. I'm actually not going to touch that ordering of the conditions because I don't want to accidentally break the logic, but if this was my script, I would go further to clear up what is happening.</p>\n\n<pre><code>if (\n ($coverage == 'inclusive' &&\n in_array($dlCountry, ['US', 'JP']) &&\n in_array($driversAge, [19, 20])\n ) ||\n in_array($class, ['suv', 'minivan', 'convert']) &&\n in_array($driversAge, [19, 20]) ||\n $pickuploc == 'oc' ||\n $blackout\n) {\n</code></pre></li>\n<li>Again with the INSERT query, I recommend declaring an associative array instead of all of those <code>bindParam()</code> calls.</li>\n<li>You must never, ever display db error messages to the end user in production. When you are developing, it may be okay, but if you provide those precise details to someone with malicious intentions, things can go very badly for you and your project.</li>\n<li>If you are going to just <code><br></code> delimit your data and print to screen, it will make things a bit simpler and more scalable to set up an array and implode the values with <code><br></code> as glue. Again, try not to write excessively wide code.</li>\n</ol>\n\n<p>Overall, I'd say you are doing quite well -- I've seen far worse attempts. You are using prepared statements and datetime objects, so you are on the right path.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:50:11.147",
"Id": "229883",
"ParentId": "229826",
"Score": "3"
}
},
{
"body": "<p>You got the SQL part quite well. If you only had been as careful when generating the HTML.</p>\n\n<p>At the very least, you should wrap every bit of output through <code>htmlspecialchars</code>. I'm sure there are better ways, but that's the basic building block, and you should learn it.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function html_println($label, $value) {\n echo htmlspecialchars($label) . \": \" . htmlspecialchars($value) . \"<br>\\n\";\n}\n\nhtml_println(\"name\", $name);\nhtml_println(\"class\", $class);\n// and so on\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T23:34:18.640",
"Id": "229885",
"ParentId": "229826",
"Score": "2"
}
},
{
"body": "<h3>w3fools</h3>\n<blockquote>\n<p>following a W3 tutorial</p>\n</blockquote>\n<p>I would say the most important suggestion you can get is never ever use any tutorial from w3shcools. They are dubbed as "w3fools" for a reason. Their tutorials are outdated, buggy and - as you can already see from other answers - far from being optimal making you a monkey writing a lot of useless code that repeats again and again.</p>\n<h3>IP address detection jiggery-pokery</h3>\n<p>Any <code>$_SERVER</code> array element that begins from <code>HTTP_</code> is filled directly form the HTTP header. It means that <em>to spoof it is a no-brainier</em> at all.</p>\n<p>You have two code blocks that effectively fill the IP address from the user input, instead of taking it from the hardware protocol. You have to <strong>get rid of the second code block completely</strong>, and make <strong>the first one unconditional</strong>. Just make your mind whether your code is behind Cloudfare or not, and either add <code>HTTP_CF_CONNECTING_IP</code> processing or leave <code>REMOTE_ADDR</code> alone accordingly.</p>\n<p>Just learn from this educational story, <a href=\"https://blog.ircmaxell.com/2012/11/anatomy-of-attack-how-i-hacked.html\" rel=\"nofollow noreferrer\">How I hacked Stack Overflow</a> and never step on this rake again.</p>\n<p>Other issues such as wrong error reporting, double connection and overall inefficiency are already reviewed in other excellent answers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:29:43.253",
"Id": "447480",
"Score": "0",
"body": "I was starting to worry that you weren't going to chime in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:43:28.270",
"Id": "447485",
"Score": "0",
"body": "I intentionally wanted to step aside to let others to have a voice, and then to pick up the rest"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T08:17:03.390",
"Id": "229897",
"ParentId": "229826",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T22:31:37.773",
"Id": "229826",
"Score": "5",
"Tags": [
"php",
"mysql",
"security",
"pdo"
],
"Title": "PDO MySQL queries for web application to reserve a vehicle"
}
|
229826
|
<h2>What is it?</h2>
<p>React native <s>Accordion</s> Collapsible Panel.</p>
<p>You pass the <em>summary</em> (always shown bit) and the <em>detail</em> (sometimes hidden bit).</p>
<p>If the detail is passed as a function or promise (ie async function), it will be lazily called as it's expanded.</p>
<h2>(Questionable??) Design choices:</h2>
<p>I allow all three types of <em>detail</em> into the same variable in the constructor, and there are two places I indulge in method existence checking to figure out what exactly I'm actually working with.</p>
<p>Is this a decent way to present this real-object vs lazy-init dynamic to coder using this component?</p>
<p>Am I type checking in a decent way?</p>
<p>Is there anything else?</p>
<h2>What it looks like:</h2>
<p>Here are two collapsing panels rendered in a list:</p>
<p><a href="https://i.stack.imgur.com/MhVn0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MhVn0.png" alt="enter image description here"></a></p>
<h2>Code:</h2>
<p>Usage: </p>
<pre><code>// In some rendering function:
const mySummary: React.ReactElement = this.renderMySummary(obj);
const myDetail: () => Promise<React.ReactElement> = async () => this.renderMyDetailAsync(obj);
// ... or
// const myDetail: () => React.ReactElement = () => this.renderMyDetail(obj);
// const myDetail: React.ReactElement = this.renderMyDetail(obj);
return <CollapsingPanel summary={mySummary} detail={myDetail} />;
</code></pre>
<p>Class:</p>
<pre><code>import React, { Component, ReactElement, ReactNode } from 'react';
import { View, TouchableOpacity, ViewStyle, TextStyle } from "react-native";
import { Icon } from 'react-native-elements';
const styles: {
summaryRow: ViewStyle,
summary: ViewStyle,
icon: TextStyle,
parentHr: ViewStyle,
child: ViewStyle,
} = {
summaryRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
summary: {
flex: 1
},
icon: {
fontSize: 30
},
parentHr: {
height: 1,
width: '100%'
},
child: {
padding: 16,
},
};
type Props = {
/** The part of this Component which is always shown */
summary: ReactElement;
/** The initially hidden part of this Component. Can be passed as a value, as a function or as asynchronous function.
* The latter two will be evaluated only as the component is expanded
*/
detail: (ReactElement) | (() => ReactElement) | (() => Promise<ReactElement>);
/**
* A marker property for triggering a re-render. Not neccesary when detail is changed.
* But when using a invokable (lazy) detail, you may want this component to call the same function again because you expect different
* results.
*/
rerenderOnData?: {};
};
type State = {
resolvedDetail: ReactElement;
detailEvaluated: boolean;
expanded: boolean;
};
export class CollapsingPanel extends Component<Props, State> {
public state: State = {
resolvedDetail: undefined,
detailEvaluated: false,
expanded: false
};
constructor(props:
{
summary: ReactElement,
detail: (ReactElement) | (() => ReactElement) | (() => Promise<ReactElement>),
rerenderOnData?: {}
}
) {
super(props);
if (props.detail["call"] == null) {
this.state.detailEvaluated = true;
this.state.resolvedDetail = this.props.detail as ReactElement;
}
}
public render(): ReactNode {
const { summary } = this.props;
const { resolvedDetail } = this.state;
return <View>
<TouchableOpacity style={styles.summaryRow} onPress={this.toggleExpand}>
<View style={styles.summary}>{summary}</View>
<Icon name={this.state.expanded ? 'keyboard-arrow-up' : 'keyboard-arrow-down'} style={styles.icon} />
</TouchableOpacity>
<View style={styles.parentHr} />
{
this.state.expanded &&
<View style={styles.child}>
{resolvedDetail}
</View>
}
</View>;
}
public componentDidUpdate(prevProps: Props): void {
if (!this.state.detailEvaluated) {
return;
}
if (prevProps.detail !== this.props.detail ||
prevProps.rerenderOnData !== this.props.rerenderOnData) {
if (this.state.expanded) {
this.ensureResolved(true);
} else {
this.state.detailEvaluated = false;
this.state.resolvedDetail = undefined;
}
}
}
private toggleExpand = () => {
const expanding: boolean = !this.state.expanded;
this.setState({ expanded: expanding });
if (expanding) {
this.ensureResolved();
}
}
private ensureResolved(force: boolean = false): void {
if (!force && this.state.detailEvaluated) {
return;
}
if (this.props.detail["call"] == null) {
this.setState({ detailEvaluated: true, resolvedDetail: this.props.detail as ReactElement });
} else {
const invoked: ReactElement | Promise<ReactElement> =
(this.props.detail as (() => ReactElement | Promise<ReactElement>))();
Promise.resolve(invoked).then(element => {
this.setState({
detailEvaluated: true, resolvedDetail: element
});
});
}
}
}
const invoked: ReactElement | Promise<ReactElement> =
(this.props.detail as (() => ReactElement | Promise<ReactElement>))();
Promise.resolve(invoked).then(element => {
this.setState({
detailEvaluated: true, resolvedDetail: element
});
});
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T22:51:55.460",
"Id": "229827",
"Score": "1",
"Tags": [
"typescript",
"react-native"
],
"Title": "React Native Lazy Collapsible Panel"
}
|
229827
|
<p>An office has a bathroom that can be used by both men and women, but not both at the same time. If a man is in the bathroom, other men may enter, but any women wishing to use the bathroom should wait for it to be empty. If a woman is in the bathroom, other women may enter, but any men wishing to use the bathroom should wait it to be empty. Each person (man or woman) will spend some time using the bathroom.</p>
<hr>
<pre><code>package basics.problems;
//BATHROOM_SIZE - 5
//2 types of threads - MEN and WOMEN
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class UniSexBathroom {
AtomicInteger currentSize;
int capacity;
Semaphore noOfEntriesSemaphore;
Semaphore currentGenderSemaphore = new Semaphore(1);
volatile Person currentGender;
public UniSexBathroom(int capacity) {
this.capacity = capacity;
this.noOfEntriesSemaphore = new Semaphore(capacity);
this.currentSize = new AtomicInteger(0);
}
public void occupy(Person personSex) throws InterruptedException {
acquireGenderSemaphore(personSex);
useBathroomAndExit(personSex);
releaseGenderSemaphore(personSex);
}
private void releaseGenderSemaphore(Person personSex) {
if(currentSize.get()==0){
currentGenderSemaphore.release();
currentGender = null;
System.out.println(personSex.type+ Thread.currentThread().getName()+" releasing gender semaphore");
}
}
private void useBathroomAndExit(Person personSex) throws InterruptedException {
noOfEntriesSemaphore.acquire();
currentSize.incrementAndGet();
System.out.println(personSex.type + Thread.currentThread().getName()+" is stepping in, current capacity is : "+currentSize.get());
Thread.sleep(100);
noOfEntriesSemaphore.release();
currentSize.decrementAndGet();
System.out.println(personSex.type + Thread.currentThread().getName()+" is stepping out, current capacity is : "+ currentSize.get() +"-----------------");
}
private void acquireGenderSemaphore(Person personSex) throws InterruptedException {
if(currentSize.get() == 0){
currentGenderSemaphore.acquire();
currentGender = personSex;
}
if(!personSex.type.equals(currentGender.type)){
currentGenderSemaphore.acquire();
currentGender = personSex;
}
}
public static void main(String[] args){
UniSexBathroom uniSexBathroom = new UniSexBathroom(2);
new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
new Thread(new PersonThread(uniSexBathroom, Person.FEMALE)).start();
new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
new Thread(new PersonThread(uniSexBathroom, Person.FEMALE)).start();
}
}
enum Person {
MALE("Male"), FEMALE("Female");
String type;
Person(String type) {
this.type = type;
}
}
class PersonThread implements Runnable {
public UniSexBathroom uniSexBathroom;
public Person person;
public PersonThread(UniSexBathroom uniSexBathroom, Person person){
this.uniSexBathroom = uniSexBathroom;
this.person = person;
}
@Override
public void run() {
try {
uniSexBathroom.occupy(person);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T05:52:33.317",
"Id": "447321",
"Score": "3",
"body": "Welcome to CR! Can you explain what the unisex bathroom problem is and provide some context as to how your code works to solve it? This feels like a code dump as it stands. See [ask]. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:31:05.097",
"Id": "447461",
"Score": "0",
"body": "Problem Statement : An office has a bathroom that can be used by both men and women, but not both at the same time. If a man is in the bathroom, other men may enter, but any women wishing to use the bathroom should wait for it to be empty. If a woman is in the bathroom, other women may enter, but any men wishing to use the bathroom should wait it to be empty. Each person (man or woman) will spend some time using the bathroom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:42:24.273",
"Id": "447463",
"Score": "2",
"body": "@NareshDoniparti any information pertinent to the question should be included in the question body, because not everyone reads the comments, and and comments have a habit of disappearing without a trace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T03:35:46.527",
"Id": "462288",
"Score": "0",
"body": "Is the bathroom \"fair\"? If there are two men in the bathroom and a woman is waiting, does a man queue up behind the woman, or does the man get to cut ahead and enter the bathroom immediately?"
}
] |
[
{
"body": "<p>Your code has a bug. I can reproduce it fairly consistently by changing your run method to:</p>\n\n<pre><code>@Override\npublic void run() {\n try {\n for(int i=0;i<100;i++) {\n uniSexBathroom.occupy(person);\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n\n<p>Notice, that I've increased the number of times that each thread tries to occupy the bathroom. Starting/Stopping threads is a fairly slow process so in order to encourage more contention I used a loop so more time is spent trying to get into the bathroom. It results in a null pointer in the <code>acquireGenderSemaphore</code> method on this line:</p>\n\n<pre><code>if (!personSex.type.equals(currentGender.type)) {\n</code></pre>\n\n<p>It's happening because <code>currentGender</code> is null. We can be confident about this, because personSex is the same for every call for a given thread. How is it null? Well, because this isn't safe:</p>\n\n<pre><code>if (currentSize.get() == 0) {\n currentGenderSemaphore.acquire();\n currentGender = personSex;\n}\n</code></pre>\n\n<p>The problem is that context switches can happen at any time, so just because currentSize wasn't 0 for the if evaluation, it doesn't mean that it's still zero during the execution of the if block.</p>\n\n<p>So:</p>\n\n<p>Thread2 is currently in the bathroom (Size 1)</p>\n\n<p>Thread1 comes in to acquire the lock, checks the value of current size and finds it's 1, skip the if block</p>\n\n<pre><code>if (currentSize.get() == 0) { // Size still 1\n</code></pre>\n\n<p>Thread2, which is currently using the bathroom leaves:</p>\n\n<pre><code>noOfEntriesSemaphore.release();\ncurrentSize.decrementAndGet(); // Size becomes 0\n</code></pre>\n\n<p>Thread2, then checks if they were the last one out, which they were:</p>\n\n<pre><code>if (currentSize.get() == 0) {\n currentGenderSemaphore.release();\n currentGender = null; // Gender becomes null\n}\n</code></pre>\n\n<p>Thread1 then proceeds, assuming there is still somebody in the bathroom:</p>\n\n<pre><code>if (!personSex.type.equals(currentGender.type)) {\n</code></pre>\n\n<p>But since <code>currentGender</code> has been set to null by Thread 2 when it left.... Bang.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:41:51.743",
"Id": "236027",
"ParentId": "229831",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T03:08:05.583",
"Id": "229831",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Unisex Bathroom problem with semaphore"
}
|
229831
|
<p>This problem is from <a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-s095-programming-for-the-puzzled-january-iap-2018/puzzle-2-the-best-time-to-party/" rel="nofollow noreferrer">MIT Course</a> and I have implemented it in C++. Please review and suggest improvements.</p>
<blockquote>
<p>There is a party to celebrate celebrities that you get to attend
because you won a ticket at your office lottery. Because of the high
demand for tickets you only get to stay for one hour but you get to
pick which one since you received a special ticket. You have access to
a schedule that lists when exactly each celebrity is going to attend
the party. You want to get as many pictures with celebrities as
possible to improve your social standing. This means you wish to go
for the hour when you get to hob-nob with the maximum number of
celebrities and get selfies with each of them.</p>
<p>We are given a list of intervals that correspond to when each celebrity
comes and goes. Assume that these intervals are [i, j), where i and j
correspond to hours. That is, the interval is closed on the left hand
side and open on the right hand side. This just means that the
celebrity will be partying on and through the ith hour, but will have
left when the jth hour begins. So even if you arrive on dot on the th
hour, you will miss this particular celebrity. </p>
<p>Here’s an example: </p>
<p><a href="https://i.stack.imgur.com/HuDqg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HuDqg.png" alt="example"></a></p>
<p>When is the best time to attend the party? That is, which hour should
you go to?</p>
</blockquote>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
struct range
{
int start = 0;
int end = 0;
range() = default;
range(int start_time, int end_time):
start(std::move(start_time)),
end(std::move(end_time))
{}
};
int celeb_density(std::vector<range>& schedule)
{
//sort according to start_time
auto by_start_time = [](const range &a, const range &b)
{
return a.start < b.start;
};
std::sort(schedule.begin(), schedule.end(), by_start_time);
int party_start = schedule[0].start; //Party start time
int party_end = schedule[schedule.size()-1].end; //Party end time
int max_count = 0, curr_max = 0, best_time, curr_best_time;
int i = party_start;
while (i < party_end)
{
for (int j = 0; j < schedule.size(); ++j)
{
if (i == schedule[j].start)
{
curr_max++;
curr_best_time = i;
}
else if (i < schedule[j].start)
{
break;
}
if (i == schedule[j].end)
{
curr_max--;
}
}
if (curr_max > max_count)
{
max_count = curr_max;
best_time = curr_best_time;
}
i++;
}
return best_time;
}
int main()
{
std::vector<range> schedule;
int number_of_celebs;
std::cout << "Enter number of celebrities attending party: ";
std::cin >> number_of_celebs;
std::cout << "Enter entry time and exit time for a celebrity\n";
for (int i = 0; i < number_of_celebs; ++i)
{
int s, e;
std::cin >> s >> e;
schedule.push_back(range(s, e));
}
int best_time = celeb_density(schedule);
std::cout << "Best time to attend party is from " << best_time << " to " << best_time + 1 << "\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T13:37:06.000",
"Id": "447339",
"Score": "0",
"body": "You're not getting what std::move is all about ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T16:18:28.540",
"Id": "447361",
"Score": "0",
"body": "@CarloWood do write an answer if you think you can provide a useful review; it doesn't need to be long, it just needs to make a valuable and unique contribution, and since I barely know C++, if you can make a comment as someone who does, that would be great."
}
] |
[
{
"body": "<h2>General Stuff</h2>\n\n<p>I would use a for-loop for <code>i</code>: with the while loop you've just ended up moving the <code>i++</code> far from the condition logic, which makes it that little bit harder to understand quickly. I'd also rename it to <code>time</code> or <code>t</code>: <code>i</code> is typical for indexing, which might give the wrong impression.</p>\n\n<p>I don't really know C++, so I might be falling into a trap, but I would consider removing <code>range</code>'s parameterless constructor so that it's harder to misuse.</p>\n\n<p>Your <code>celeb_density</code> method will crash violently if the <code>schedule</code> is empty. You should probably detect this case and fail in a helpful manner. <code>celeb_density</code> is not great name: it tells me nothing about what it does or what it returns.</p>\n\n<p>Your <code>main</code> method (though I don't suppose you are too worried about this) doesn't perform any validation, so I can, for example, request a negative number of entries, and it will happily ask me to enter a start and end time before it crashes in <code>celeb_density</code>. It only prompts for a range once (which is confusing), and it doesn't complain if I enter a range where <code>start > end</code>. <code>Range</code> could also throw if <code>start > end</code>, which would ensure that the code producing the invalid input throws rather than algorithms producing meaningless results.</p>\n\n<p>Your vector has a size type of <code>size_t</code>, so you should ideally make <code>j</code> that same type.</p>\n\n<h2>Performance and Scalability</h2>\n\n<p>Using a sort to find the start is excessive, because you algorithm doesn't care about the order in the <code>schedule</code>: you can find these with a linear scan. It also means you have modified the input, which the caller might not appreciate.</p>\n\n<p>Your method (ignoring the sort) has a worst case time complexity of <code>O(n*m)</code> where <code>n</code> is the size of the schedule, and <code>m</code> is the time-space between the start and end of the schedule. In terms of scalability, this isn't ideal, but its a stupid little example without a specification for performance, so this might not matter.</p>\n\n<p>However, we can achieve a <code>O(n log(n))</code> worst case time complexity (which would already have because of the sort, but that is trivially removed). A sort will be in order, but first break the events into two entries: an incrementing entry and a decrementing entry. You can then sort these and just loop over them incrementing and decrementing as you go, keeping track of the 'best time' as you already are. The only detail is that you need to sort the decrementing events before the incrementing events or otherwise deal with the situation where there are arrivals and departures on the same hour.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T09:36:43.717",
"Id": "229840",
"ParentId": "229836",
"Score": "3"
}
},
{
"body": "<p>Good to see you're not doing a <code>using namespace std</code> ;).\nOf course it doesn't <em>really</em> hurt in a source file (.cpp) (it does in a header file!),\nbut even then that is still considered bad practice. My personal reason to just always type the namespace is because it makes code easier to read (you know what is part of a namespace and which and don't have to guess that) and it is easier to search with regular expressions and the like.</p>\n\n<p>While the standard does not use class names that begin with an upper case letter, many good coders do. It allows you - in fact - to have your own classes to stand out better, and using both upper case and lower case adds more state to your namespace (aka, less collisions). For example, you can call your class <code>Range</code> and a Range variable <code>range</code>.</p>\n\n<p>Also for both, readability and regular expression searches, I strongly recommend <em>only</em> to use complete English words for any class, variable or function name and never resort to abbreviations. The only exceptions to this rule are local variables that are so local (used in a scope of only a few lines) that you can easily see their declaration and use on one screen and where their meaning is mostly irrelevant(!). For example a counter of a <code>for</code> loop can be called <code>i</code> if you must.</p>\n\n<p>Also for ease of regular expression search and understandability (maintenance) of code it is a good idea to use the same name for variables that contain the same object (you copied a value from one to the other). Ok, that is normally not possible unless you pass them as function argument (you can't write <code>range = range</code>) but you'll surprised how often it is; for example use <code>range_end</code> for every variable that means \"the end of a range\". Why am I mentioning this? Well, this is the reason that class member variables often have a prefix (either <code>M_</code> or <code>m_</code> or something. I use <code>m_</code>. That way you avoid collisions with local variables with the same name, and member functions with the same name.</p>\n\n<p>C++ provides classes with a reason: to write Object Oriented code. Encapsulation is part of that. In almost all cases your class member variables should be private!</p>\n\n<p>For (ostream based) debugging output, it is a good idea to make <em>every</em> class\nwritable to an ostream.</p>\n\n<p><code>std::move</code> is just a cast, from an lvalue reference to an rvalue reference, and only useful when you pass the result to a function that takes an rvalue reference (aka, you pick the right overloaded function with it). Where you used <code>std::move</code> the argument isn't an lvalue reference, nor do you pass the result of the <code>std::move</code> to a function that accepts an rvalue reference, so using <code>std::move</code> there is nonsense. PS By convention a moved object (whose rvalue reference was passed to a function) should only be destructed afterwards (in all but exceptional cases). So if you cast an lvalue reference to an rvalue reference then that variable had better be passed in as an rvalue reference in the first place. The typical use case therefore looks as follows:</p>\n\n<pre><code>void bar(Bar&& bar);\n\nvoid foo(Bar&& bar)\n{\n // Here bar is an lvalue reference!\n bar(std::move(bar));\n // Now 'bar' may no longer used, only destructed (by convention:\n // it is like that because one would expect that bar() makes it so.\n}\n</code></pre>\n\n<p>This would work fine when <code>foo()</code> took an lvalue reference (<code>foo(Bar& bar)</code>) but \nthen the caller of <code>foo</code> wouldn't be aware of the fact that <code>bar</code> was moved and could \"accidently\" use bar still after returning from <code>foo(bar)</code>.</p>\n\n<p>Combining what we learned so far, I arrive at the follow code for <code>Range</code>:</p>\n\n<pre><code>class Range\n{\n private:\n int m_start_time = 0;\n int m_end_time = 0;\n\n public:\n Range() = default;\n Range(int start_time, int end_time) :\n m_start_time(start_time),\n m_end_time(end_time)\n { }\n\n int start_time() const { return m_start_time; }\n int end_time() const { return m_end_time; }\n\n friend std::ostream& operator<<(std::ostream& os, Range const& range);\n};\n</code></pre>\n\n<p>Well, that's enough for today.\nI'll finish with my own stab at celeb_density:</p>\n\n<pre><code>int celeb_density(std::vector<Range> const& schedule)\n{\n // Do not pass an empty schedule.\n assert(!schedule.empty()); // #include <cassert>\n\n std::array<unsigned int, 24> hours; // #include <array>\n hours.fill(0);\n\n int best_time = schedule[0].start_time();\n int max_celebs = 1;\n for (auto range : schedule)\n for (int hour = range.start_time(); hour < range.end_time(); ++hour)\n if (++hours[hour] > max_celebs)\n {\n ++max_celebs;\n best_time = hour;\n }\n\n return best_time;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T17:43:20.153",
"Id": "229861",
"ParentId": "229836",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229861",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T06:51:31.310",
"Id": "229836",
"Score": "1",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "MIT Puzzle: The Best Time to Party"
}
|
229836
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.