body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've written a solution to a Codewars challenge:</p>
<blockquote>
<p>You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:</p>
<p>12 ==> 21; 513 ==> 531; 2017 ==> 2071 </p>
</blockquote>
<p>I am getting the following error on Codewars: "Execution Timed Out (12000 ms)". I am a rookie, and would appreciate if anyone could give me some suggestions on optimizing my code, as this is something I know very little about.</p>
<p>I've made some minor tweaks but nothing that really reconstructs the solution from the ground up.</p>
<pre><code>//takes a num and finds the next biggest num composed of the same digits.
function nextBigger(num) {
let newNum = 0;
let otherNum = 0;
let indicator = 0;
while (num > newNum) {
if (indicator === 0) {
otherNum = num;
indicator++;
continue;
}
if (
String(num)
.split("")
.sort()
.join("") ===
String(otherNum)
.split("")
.sort()
.join("")
) {
if (otherNum > num) {
newNum = otherNum;
}
}
otherNum++;
}
return newNum;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T22:32:11.243",
"Id": "450518",
"Score": "2",
"body": "Think about which digits need to be rearranged to make the smallest possible difference. Looking at the relationships between the numbers in the examples given in the challenge should help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T10:43:16.953",
"Id": "450564",
"Score": "1",
"body": "To close voters, `time-limit-exceeded` is a valid CodeReview tag, this question should not be closed."
}
] |
[
{
"body": "<p>I know whatever program codewars uses does not care about readability (most computer programs don't), but in the real world readability is important.</p>\n\n<p>The first step to refactoring should be creating tests. This way you can easily figure out if you've broken something:</p>\n\n<pre><code>let test1 = getNextNumberOfGreaterSize(12);\nlet test2 = getNextNumberOfGreaterSize(513);\nlet test3 = getNextNumberOfGreaterSize(2017);\n\nassertEquals(21, test1);\nassertEquals(531, test2);\nassertEquals(2071, test3);\n\nfunction assertEquals(expected, actual) {\n if (expected !== actual) {\n throw new Error(\"expected: \" + expected + \" but was: \" + actual);\n }\n}\n</code></pre>\n\n<p>While designing tests, you may discover other edge cases such as:</p>\n\n<ul>\n<li>What if the number given is already the highest?</li>\n<li>What if the number doesn't have any other combinations (such as 11)?</li>\n<li>What if a single digit number is given (1)?</li>\n</ul>\n\n<p>You didn't provide a function name but assuming it wasn't descriptive I suggest you change it. It's tricky coming up with a name for such a function (Functions like these probably wouldn't exist in the 'real world'), but something like <code>getNextNumberOfGreaterSize(originalNumber)</code> with a comment describing what it does.</p>\n\n<p>Set <code>otherNumber</code> (Note I changed the name to be more readable. Cutting off 3 letters isn't saving you, or the interpreter any time) outside of the while loop and get rid of your if statement:</p>\n\n<pre><code>let otherNum = originalNumber;\nwhile (originalNumber > newNum) {\nif (....\n</code></pre>\n\n<p>Whatever you are doing inside the if statement deserves a comment. Better yet, you should also put it inside a function (especially when you know you'll refactor it later!):</p>\n\n<pre><code>function numbersContainSameDigits(number1, number2) {\n return String(number1)\n .split(\"\")\n .sort()\n .join(\"\") ===\n String(number2)\n .split(\"\")\n .sort()\n .join(\"\");\n}\n</code></pre>\n\n<p>Now that we got the important stuff out of the way, let's move onto what you're actually asking for. How can we shave a few milliseconds off each run / Why is coderank telling us the methods too slow?</p>\n\n<p>Computers suck at computing Strings. However they rock at computing numbers. Let's see if we can cut down on the amount of String computing.</p>\n\n<p>The way we check if the two numbers contain the same letters can be changed. First we get an array containing the characters, then compare the two arrays after sorting:</p>\n\n<pre><code>function numbersContainSameDigits(number1, number2) {\n return checkIfTwoArraysAreEqual(getArrayContainingDigits(number1), getArrayContainingDigits(number2));\n}\n\nfunction checkIfTwoArraysAreEqual(array1, array2) {\n return JSON.stringify(array1.sort()) === JSON.stringify(array2.sort());\n}\n\nfunction getArrayContainingDigits(number) {\n let arrayOfDigits = [];\n while (number >= 1) {\n arrayOfDigits.push(Math.floor(number % 10));\n number /= 10;\n }\n\n return arrayOfDigits;\n}\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>You are going through a much wider range of numbers than needed. You could instead get all available combinations of a number, and select the permutation 1 index greater than the input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T14:45:04.943",
"Id": "452005",
"Score": "0",
"body": "I believe the generally-accepted name for this function is \"next_permutation\" (or some variant with different case style)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T22:48:01.667",
"Id": "231122",
"ParentId": "231120",
"Score": "2"
}
},
{
"body": "<p>Stimulating question;</p>\n\n<p>Both the edit of @dustytrash and the comment of @Ry are giving a great hint.</p>\n\n<p>But before we go there, let's look at this part:</p>\n\n<pre><code> let newNum = 0;\n let otherNum = 0;\n let indicator = 0;\n while (num > newNum) {\n if (indicator === 0) {\n otherNum = num;\n indicator++;\n continue;\n }\n</code></pre>\n\n<p>You are setting up <code>otherNum</code> up within the loop, you only do it once with <code>indicator</code> but you are still performing an <code>if</code> statement every cycle. You can just drop <code>indicator</code> completely and start with the smallest possible value of <code>otherNum</code>:</p>\n\n<pre><code> let otherNum = num + 1;\n while (num > newNum) {\n</code></pre>\n\n<p>Then you can replace this part:</p>\n\n<pre><code> if (otherNum > num) {\n newNum = otherNum;\n }\n</code></pre>\n\n<p>with simply a return statement there:</p>\n\n<pre><code>if (String(num).split(\"\").sort().join(\"\") === String(otherNum).split(\"\").sort().join(\"\"){\n return otherNum;\n}\n</code></pre>\n\n<p>You would not need <code>newNum</code> at all any more.\nStill, to your point in the question, we are looking for more than minor tweaks.</p>\n\n<p>This code basically tries out every integer between <code>num</code> and the solution, that is to say potentially a ton of numbers. For <code>2017</code> -> <code>2071</code> there are 54 tries, but there are only 24 possible combinations with 4 digits (4*3*2*1). From those 24 possible combinations we know that none of the combinations can start with either 0 or 1 because that would give a number smaller than 2017. Which leaves us with only 12 combinations to test.</p>\n\n<p>To go further, if we want to check the next big number of 2341, we know that the next biggest number starts with either 2 possibly, or 3. I could not be 1 since then the number is too small, it could not be 4 because any number starting with 4 is going to be both greater than any number starting with 3.</p>\n\n<p>Finally, we know that if the next biggest number started with '3', we should just apply the remaining digits from low to high (so 3124), there is no way to make a lower number than that.</p>\n\n<p>This is my rewrite, very commented since I am still wrapping my brains around it a bit, but it seems to work. I made one small change for my benefit, the code returns -1 if it cannot find a bigger number with the same digits. </p>\n\n<p>(Which is another issue with your code, it seems that running it for say 531, it will run forever).</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>//H4ck: We trust that n is part of the list\nfunction removeNumber(list, n){\n list.splice(list.indexOf(n), 1);\n return list;\n}\n\n//Takes a string that looks like a positive integer number \n//and returns the next bigger number formed by the same digits\n//Return the same number if we can not find a next bigger number\nfunction nextBiggerString(s){\n \n let digits = s.split('');\n let wip = [...digits]; //Work in progress\n \n //Special case we don't want to deal with, 2 digits\n //Very useful for a recursive approach\n if(digits.length == 2){\n //Don't reverse if we are already at max\n return Math.max(digits.reverse().join(\"\"), s);\n }\n \n //First digit has to be equal or next biggest after target digit to make sense\n const target = digits[0];\n //Only keep valid starting candidates \n wip = wip.sort().filter(i=>i>target);\n //Very often the solution is option 1, kicking the can down the road\n const option1 = target + nextBiggerString(s.slice(1));\n if(wip.length==0){\n //The first digit was the highest digit of them all, so we can only kick the can\n return option1;\n }else{\n if(option1 != s){\n //Only return option1 is it different from what we started with\n return option1\n } else{\n //Otherwise take the next digit, and sort the rest ascendingly\n return wip[0] + removeNumber(digits,wip[0]).sort().join(''); \n } \n }\n}\n\n//Takes a positive integer number and returns the next bigger number formed by the same digits\n//Return -1 if we cant find a next bigger number\n//this uses a stringbased biggerString because this uses an iterative solution\n//where for example 034 from 1034 becomes 34, which would return then 143\nfunction nextBigger(n){\n const maybe = nextBiggerString(String(n))*1;\n return maybe == n ? -1 : maybe;\n}\n\n\nconsole.log(nextBigger(12));\nconsole.log(nextBigger(513));\nconsole.log(nextBigger(531));\nconsole.log(nextBigger(2017));\nconsole.log(nextBigger(2721));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:21:08.843",
"Id": "231619",
"ParentId": "231120",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231122",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T21:43:32.500",
"Id": "231120",
"Score": "2",
"Tags": [
"javascript",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Function to take a positive integer and return the next bigger number formed by the same digits"
}
|
231120
|
<p>I am working with a system that needs to consume product images uploaded by employees and resize them / add white padding to the sides to create square images to be consumed by our e-commerce site. I'm attempting to keep things somewhat light on the memory usage because this will live in a windows service on an azure vm. I know there are better solutions, but that's what I'm given as a platform. I also don't want to use 3rd party libraries.</p>
<p>The following code is what I have so far. Please, pick it apart and let me know if i'm making any mistakes.</p>
<pre><code>public static Image ImageToFixedSize(Image originalImage, int width, int height)
{
Graphics graphicController = null;
try
{
if (originalImage != null)
{
int sourceWidth = originalImage.Width;
int sourceHeight = originalImage.Height;
int destX = 0;
int destY = 0;
float percent = 0;
float percentW = 0;
float percentH = 0;
percentW = width / (float)sourceWidth;
percentH = height / (float)sourceHeight;
if (percentH < percentW)
{
percent = percentH;
destX = Convert.ToInt16((width - (sourceWidth * percent)) / 2);
}
else
{
percent = percentW;
destY = Convert.ToInt16((height - (sourceHeight * percent)) / 2);
}
int destWidth = (int)(sourceWidth * percent);
int destHeight = (int)(sourceHeight * percent);
Bitmap tempPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
tempPhoto.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
graphicController = Graphics.FromImage(tempPhoto);
graphicController.FillRectangle(Brushes.White, 0, 0, width, height);
// The chances of hitting this ONE SPECIFIC COLOR are very slim
graphicController.SmoothingMode = SmoothingMode.HighQuality;
graphicController.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphicController.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicController.CompositingQuality = CompositingQuality.HighQuality;
graphicController.DrawImage(
originalImage,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(1, 1, sourceWidth - 1, sourceHeight - 1),
GraphicsUnit.Pixel);
return tempPhoto;
}
else
{
return null;
}
}
catch
{
throw;
}
finally
{
graphicController.Dispose();
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Reversing the condition of <code>if (originalImage != null)</code> and returning early will remove one level of indentation. The less indentation some code shows the easier to read it will become. </li>\n<li><code>catch</code> to just rethrow, althought you did it in the correct way, doesn't buy you anything. Just remove the <code>try..catch..finally</code> and enclose the usage of <code>graphics</code> with an <code>usage</code> block.</li>\n<li>Althought the code is mostly named well, one could stumble over <code>tempPhoto</code> and can't figure out at first glance wether this object is important or just temporary. </li>\n<li>You can cast e.g <code>((width - (sourceWidth * percent)) / 2)</code> directly to <code>int</code> you don't need a call to <code>Convert.ToInt16()</code> here. </li>\n<li><code>percentW</code> and <code>percentH</code> are first defined and on the next lines you assign a value to them. You should do it just at the declaration to save some (superflous) lines of code. </li>\n<li>Instead of <code>graphicController.FillRectangle(Brushes.White, 0, 0, width, height);</code> you should use <code>graphicController.Clear(Color.White);</code> which is easier to read. </li>\n<li>Comments, when used, should state, in a clear and understandable way, why the code is written as it is. I don't get the comment <code>// The chances of hitting this ONE SPECIFIC COLOR are very slim</code>. Where could be a problem with the code to make this comment justified? </li>\n<li>The code validates the <code>Image originalImage</code> method parameter, but allows \"illegal\" values for <code>int width</code> and <code>int height</code>. </li>\n</ul>\n\n<p>Implementing most of the mentioned points (validation is for you) will lead to </p>\n\n<pre><code>public static Image ImageToFixedSize(Image originalImage, int width, int height)\n{\n if (originalImage == null) { return null; }\n\n int sourceWidth = originalImage.Width;\n int sourceHeight = originalImage.Height;\n int destX = 0;\n int destY = 0;\n\n float percent = 0;\n float percentW = width / (float)sourceWidth;\n float percentH = height / (float)sourceHeight;\n\n if (percentH < percentW)\n {\n percent = percentH;\n destX = (int)((width - (sourceWidth * percent)) / 2);\n }\n else\n {\n percent = percentW;\n destY = (int)((height - (sourceHeight * percent)) / 2);\n }\n\n int destWidth = (int)(sourceWidth * percent);\n int destHeight = (int)(sourceHeight * percent);\n\n Bitmap fixedSizedImage = new Bitmap(width, height, PixelFormat.Format24bppRgb);\n fixedSizedImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);\n\n using (Graphics graphicController = Graphics.FromImage(fixedSizedImage))\n {\n graphicController.Clear(Color.White);\n\n // The chances of hitting this ONE SPECIFIC COLOR are very slim\n graphicController.SmoothingMode = SmoothingMode.HighQuality;\n graphicController.PixelOffsetMode = PixelOffsetMode.HighQuality;\n graphicController.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphicController.CompositingQuality = CompositingQuality.HighQuality;\n\n graphicController.DrawImage(\n originalImage,\n new Rectangle(destX, destY, destWidth, destHeight),\n new Rectangle(1, 1, sourceWidth - 1, sourceHeight - 1),\n GraphicsUnit.Pixel);\n }\n\n return fixedSizedImage;\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T12:32:19.627",
"Id": "450579",
"Score": "1",
"body": "I agree with almost everything you stated, thank you for your assistance. I want to ask, about the casting of sourceWidth / sourceHeight... My environment is warning me about a 'Possible loss of fraction'. Thoughts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T12:43:24.437",
"Id": "450580",
"Score": "1",
"body": "Well, my VS 2017 doesn't show a warning but you are right. One of the terms should be `float`. Will edit my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T19:33:51.747",
"Id": "450621",
"Score": "0",
"body": "Just a note on the `using`: With the current C# version, you can just write `using var graphicsController = Graphics.FromImage(...);` without having a block after. It will automatically be disposed once the enclosing scope is finished. See [here](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T05:12:23.810",
"Id": "231130",
"ParentId": "231125",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T00:10:14.150",
"Id": "231125",
"Score": "4",
"Tags": [
"c#",
"image",
"memory-optimization"
],
"Title": "C# handling of images - is this best for memory usage?"
}
|
231125
|
<p>This is a follow up to the code here: <a href="https://codereview.stackexchange.com/questions/230796/web-scraper-that-extracts-urls-from-amazon-and-ebay">Web scraper that extracts urls from Amazon and eBay</a>
A multi-threaded modification to the previous version that is Amazon focused and most of the necessary documentation is in the docstrings.</p>
<p>You'll find a copy of the source code as well as necessary files <a href="https://drive.google.com/open?id=1JwffnN3Ntn7KMsRjsHQslqdczUZAtPSJ" rel="nofollow noreferrer">here</a> including (<code>proxies.txt</code>, <code>amazon_log.txt</code>, <code>user_agents.txt</code>) to be enclosed within the same folder as the code's.</p>
<p><strong>Features:</strong></p>
<ul>
<li>Multi-threaded scraping of contents.</li>
<li>Save urls to .txt files</li>
<li>Scrape Amazon sections including: best sellers, new releases, most wished for ...</li>
<li>Save names to .txt files.</li>
<li>Map names to urls.</li>
<li>Caching of contents for further re-use.</li>
<li>Extraction of product features including(name, title, url, features, technical details ...</li>
</ul>
<p>I'll be implementing another class that manages this one with public methods organizing files into csv/json files and perform some data analysis as well as optimizations to this one. I'll be posting follow ups when I'm done.</p>
<p><strong>For reviewers:</strong> </p>
<ul>
<li><strong>Modifications:</strong> I made a lot of modifications in this version and it's completely different than the previous one. It's Amazon only focused and lots of unnecessary former method parameters <code>print_progress</code>, <code>cleanup_empty</code> are now class attributes. Sequential extraction is now optional as well as multi-threaded extraction which is 500 x faster. Docstrings are up to date and completely changed in terms of style and content. The code is much more organized in this version and much more readable.</li>
<li><strong>Shorter code suggestions:</strong> I want to shorten the code and eliminate repetition(if any), most of the code is repetition free, but tasks are repetitive in usually different forms.</li>
<li><strong>Proxies and user agents:</strong> Concerning the responses gathered using the <code>_get_response()</code> method, are <code>proxies</code> and and <code>headers</code> parameters doing the necessary job? are proxies working this way? are there any improvements that could be done?</li>
<li><strong>Random occasional failures</strong>: There are occasional and random occurrences of failures in feature extraction in sections that do not include best sellers or most wished for. Why these failures sometimes happen and sometimes they do not? and how to control this and get the least failure percentage possible?</li>
<li><strong>Private methods:</strong> Methods defined here are private <code>_private()</code> because this class will be used by another class that manages the extraction and will contain public methods mostly.</li>
<li><strong>Suggestions:</strong> General suggestions to improve the code are most welcome and feel free to ask questions if you need to clarify things.</li>
</ul>
<p><strong>Note: For people downvoting this, unless you work at Google or Nasa maybe or even Alan Turing at some other dimension at least give me the honor of letting me know why this might not have passed your super godly standards.</strong></p>
<p><strong>Code</strong></p>
<pre><code>#!/usr/bin/env python3
from requests.exceptions import HTTPError, ConnectionError, ConnectTimeout
from concurrent.futures import ThreadPoolExecutor, as_completed
from bs4 import BeautifulSoup
from time import perf_counter
from random import choice
import requests
import bs4
import os
class AmazonScraper:
"""
A tool to scrape Amazon different sections.
Sections:
Best Sellers - New Releases - Gift Ideas - Movers and Shakers - Most Wished For.
Features:
Category/Subcategory Urls and names.
Product Urls and details(title, features, technical details, price, review count)
"""
def __init__(
self, path=None, print_progress=False, cache_contents=True, cleanup_empty=True, threads=1, log=None):
"""
Args:
path: Folder path to save scraped and cached contents.
print_progress: If True then the progress will be displayed.
cache_contents: If True then the scraped contents will be cached for further re-use.
cleanup_empty: If True, empty .txt files that might result will be deleted.
threads: If number of threads(1 by default) is increased, multiple threads will be used.
log: If print_progress is True, content will be saved to the log (a file name + .txt).
"""
if not path:
self.path = '/Users/user_name/Desktop/Amazon Scraper/'
if path:
self.path = path
self.headers = [{'User-Agent': item.rstrip()} for item in open('user_agents.txt').readlines()]
self.print_progress = print_progress
self.cache_contents = cache_contents
self.cleanup_empty = cleanup_empty
self.session = requests.session()
self.threads = threads
if log:
if log in os.listdir(self.path):
os.remove(log)
self.log = open(log, 'w')
self.proxies = [{'https:': 'https://' + item.rstrip(), 'http':
'http://' + item.rstrip()} for item in open('proxies.txt').readlines()]
self.modes = {'bs': 'Best Sellers', 'nr': 'New Releases', 'gi': 'Gift Ideas',
'ms': 'Movers and Shakers', 'mw': 'Most Wished For'}
self.starting_target_urls = \
{'bs': ('https://www.amazon.com/gp/bestsellers/', 'https://www.amazon.com/Best-Sellers'),
'nr': ('https://www.amazon.com/gp/new-releases/', 'https://www.amazon.com/gp/new-releases/'),
'ms': ('https://www.amazon.com/gp/movers-and-shakers/', 'https://www.amazon.com/gp/movers-and-shakers/'),
'gi': ('https://www.amazon.com/gp/most-gifted/', 'https://www.amazon.com/gp/most-gifted'),
'mw': ('https://www.amazon.com/gp/most-wished-for/', 'https://www.amazon.com/gp/most-wished-for/')}
def _cache_main_category_urls(self, text_file_names: dict, section: str, category_class: str,
content_path: str, categories: list):
"""
Cache the main category/subcategory URLs to .txt files.
Args:
text_file_names: Section string indications mapped to their corresponding .txt filenames.
section: Keyword indication of target section.
'bs': Best Sellers
'nr': New Releases
'ms': Movers & Shakers
'gi': Gift Ideas
'mw': Most Wished For
category_class: Category level indication 'categories' or 'subcategories'.
content_path: Path to folder to save cached files.
categories: The list of category/subcategory urls to be saved.
Return:
None
"""
os.chdir(content_path + 'Amazon/')
with open(text_file_names[section][category_class], 'w') as cats:
for category in categories:
cats.write(category + '\n')
if self.print_progress:
if not open(text_file_names[section][category_class]).read().isspace():
print(f'Saving {category} ... done.')
if self.log:
print(f'Saving {category} ... done.', file=self.log, end='\n')
if open(text_file_names[section][category_class]).read().isspace():
print(f'Saving {category} ... failure.')
if self.log:
print(f'Saving {category} ... failure.', file=self.log, end='\n')
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
def _read_main_category_urls(self, text_file_names: dict, section: str, category_class: str, content_path: str):
"""
Read the main category/subcategory cached urls from their respective .txt files.
Args:
text_file_names: Section string indications mapped to their corresponding .txt filenames.
section: Keyword indication of target section.
'bs': Best Sellers
'nr': New Releases
'ms': Movers & Shakers
'gi': Gift Ideas
'mw': Most Wished For
category_class: Category level indication 'categories' or 'subcategories'.
content_path: Path to folder to save cached files.
Return:
A list of the main category/subcategory urls specified.
"""
os.chdir(content_path + 'Amazon')
if text_file_names[section][category_class] in os.listdir(content_path + 'Amazon/'):
with open(text_file_names[section][category_class]) as cats:
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
return [link.rstrip() for link in cats.readlines()]
def _get_response(self, url):
"""
Send a get request to target url.
Args:
url: Target Url.
Return:
Response object.
"""
return self.session.get(url, headers=choice(self.headers), proxies=choice(self.proxies))
def _scrape_main_category_urls(self, section: str, category_class: str, prev_categories=None):
"""
Scrape links of all main category/subcategory Urls of the specified section.
Args:
section: Keyword indication of target section.
'bs': Best Sellers
'nr': New Releases
'ms': Movers & Shakers
'gi': Gift Ideas
'mw': Most Wished For
category_class: Category level indication 'categories' or 'subcategories'.
prev_categories: A list containing parent category Urls.
Return:
A sorted list of scraped category/subcategory Urls.
"""
target_url = self.starting_target_urls[section][1]
if category_class == 'categories':
starting_url = self._get_response(self.starting_target_urls[section][0])
html_content = BeautifulSoup(starting_url.text, features='lxml')
target_url_part = self.starting_target_urls[section][1]
if not self.print_progress:
return sorted({str(link.get('href')) for link in html_content.findAll('a')
if target_url_part in str(link)})
if self.print_progress:
categories = set()
for link in html_content.findAll('a'):
if target_url_part in str(link):
link_to_add = str(link.get('href'))
categories.add(link_to_add)
print(f'Fetched {self.modes[section]}-{category_class[:-3]}y: {link_to_add}')
if self.log:
print(f'Fetched {self.modes[section]}-{category_class[:-3]}y: '
f'{link_to_add}', file=self.log, end='\n')
return categories
if category_class == 'subcategories':
if not self.print_progress:
if self.threads == 1:
responses = [self._get_response(category)
for category in prev_categories]
category_soups = [BeautifulSoup(response.text, features='lxml') for response in responses]
pre_sub_category_links = [str(link.get('href')) for category in category_soups
for link in category.findAll('a') if target_url in str(link)]
return sorted({link for link in pre_sub_category_links if link not in prev_categories})
if self.threads > 1:
with ThreadPoolExecutor(max_workers=self.threads) as executor:
future_html = {
executor.submit(self._get_response, category): category for category in prev_categories}
responses = [future.result() for future in as_completed(future_html)]
category_soups = [BeautifulSoup(response.text) for response in responses]
pre_sub_category_links = [str(link.get('href')) for category in category_soups
for link in category.findAll('a') if target_url in str(link)]
return sorted({link for link in pre_sub_category_links if link not in prev_categories})
if self.print_progress:
if self.threads == 1:
responses, pre, subcategories = [], [], set()
for category in prev_categories:
response = self._get_response(category)
responses.append(response)
print(f'Got response {response} for {self.modes[section]}-{category}')
if self.log:
print(f'Got response {response} for {self.modes[section]}-{category}',
file=self.log, end='\n')
category_soups = [BeautifulSoup(response.text, features='lxml') for response in responses]
for soup in category_soups:
for link in soup.findAll('a'):
if target_url in str(link):
fetched_link = str(link.get('href'))
pre.append(fetched_link)
print(f'Fetched {self.modes[section]}-{fetched_link}')
if self.log:
print(f'Fetched {self.modes[section]}-{fetched_link}', file=self.log,
end='\n')
return sorted({link for link in pre if link not in prev_categories})
if self.threads > 1:
with ThreadPoolExecutor(max_workers=self.threads) as executor:
category_soups = []
future_responses = {
executor.submit(self._get_response, category): category for category in prev_categories}
for future in as_completed(future_responses):
url = future_responses[future]
try:
response = future.result()
print(f'Got response {response} for {self.modes[section]}-{url}')
if self.log:
print(f'Got response {response} for {self.modes[section]}-{url}',
file=self.log, end='\n')
except(HTTPError, ConnectTimeout, ConnectionError):
print(f'Failed to get response from {url}')
if self.log:
print(f'Failed to get response from {url}', file=self.log, end='\n')
else:
category_soups.append(BeautifulSoup(response.text, features='lxml'))
pre_sub_category_links = [str(link.get('href')) for category in category_soups
for link in category.findAll('a') if target_url in str(link)]
return sorted({link for link in pre_sub_category_links if link not in prev_categories})
def _get_main_category_urls(self, section: str, subs=True):
"""
Manage the scrape/read from previous session cache operations and return section Urls.
If the program found previously cached files, will read and return existing data, else
new content will be scraped and returned.
Args:
section: Keyword indication of target section.
'bs': Best Sellers
'nr': New Releases
'ms': Movers & Shakers
'gi': Gift Ideas
'mw': Most Wished For
subs: If False, only categories will be returned.
Return:
2 sorted lists: categories and subcategories.
"""
text_file_names = \
{section_short: {'categories': self.modes[section_short] + ' Category Urls.txt',
'subcategories': self.modes[section_short] + ' Subcategory Urls.txt'}
for section_short in self.modes}
if 'Amazon' not in os.listdir(self.path):
os.mkdir('Amazon')
os.chdir(self.path + 'Amazon')
if 'Amazon' in os.listdir(self.path):
categories = self._read_main_category_urls(text_file_names, section, 'categories', self.path)
if not subs:
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
return sorted(categories)
subcategories = self._read_main_category_urls(text_file_names, section, 'subcategories', self.path)
try:
if categories and subcategories:
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
return sorted(categories), sorted(subcategories)
except UnboundLocalError:
pass
if not subs:
categories = self._scrape_main_category_urls(section, 'categories')
if self.cache_contents:
self._cache_main_category_urls(text_file_names, section, 'categories', self.path, categories)
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
return sorted(categories)
if subs:
categories = self._scrape_main_category_urls(section, 'categories')
if self.cache_contents:
self._cache_main_category_urls(text_file_names, section, 'categories', self.path, categories)
subcategories = self._scrape_main_category_urls(section, 'subcategories', categories)
if self.cache_contents:
self._cache_main_category_urls(text_file_names, section, 'subcategories', self.path, subcategories)
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
return sorted(categories), sorted(subcategories)
def _extract_page_product_urls(self, page_url: str):
"""
Extract product Urls from an Amazon page and the page title.
Args:
page_url: Target page.
Return:
The page category title(string) and a sorted list of product Urls.
"""
prefix = 'https://www.amazon.com'
response = self._get_response(page_url)
soup = BeautifulSoup(response.text, features='lxml')
try:
title = soup.h1.text.strip()
except AttributeError:
title = 'N/A'
product_links = {prefix + link.get('href') for link in soup.findAll('a') if 'psc=' in str(link)}
return title, sorted(product_links)
@staticmethod
def _cleanup_empty_files(dir_path: str):
"""
Cleanup a given folder from empty .txt files.
Args:
dir_path: Path to the target folder to be cleaned up.
Return:
None
"""
for file_name in [file for file in os.listdir(dir_path)]:
if not os.path.isdir(file_name):
try:
contents = open(file_name).read().strip()
if not contents:
os.remove(file_name)
except(UnicodeDecodeError, FileNotFoundError):
pass
def _category_page_title_to_url(self, section: str, category_class: str, delimiter='&&&'):
"""
Map category/subcategory names to their respective Urls.
Args:
section:
'bs': Best Sellers
'nr': New Releases
'ms': Movers & Shakers
'gi': Gift Ideas
'mw': Most Wished For
category_class: Category level indication 'categories' or 'subcategories'.
delimiter: Delimits category/subcategory names and their respective Urls in the .txt files.
Return:
A list of lists(pairs): [[category/subcategory name, Url], ...]
"""
file_names = {'categories': self.modes[section] + ' Category Names.txt',
'subcategories': self.modes[section] + ' Subcategory Names.txt'}
names_urls = []
os.chdir(self.path)
if 'Amazon' in os.listdir(self.path):
os.chdir('Amazon')
file_name = file_names[category_class]
if file_name in os.listdir(self.path + 'Amazon'):
with open(file_name) as names:
if self.cleanup_empty:
self._cleanup_empty_files(self.path)
return [line.rstrip().split(delimiter) for line in names.readlines()]
if 'Amazon' not in os.listdir(self.path):
os.mkdir('Amazon')
os.chdir('Amazon')
categories, subcategories = self._get_main_category_urls(section)
if not self.print_progress:
if self.threads == 1:
responses_urls = [(self._get_response(url), url)
for url in eval('eval(category_class)')]
soups_urls = [(BeautifulSoup(item[0].text, features='lxml'), item[1]) for item in responses_urls]
for soup, url in soups_urls:
try:
title = soup.h1.text.strip()
names_urls.append([title, url])
except AttributeError:
pass
if self.threads > 1:
with ThreadPoolExecutor(max_workers=self.threads) as executor:
future_responses = {
executor.submit(self._get_response, category): category
for category in eval('eval(category_class)')}
responses = [future.result() for future in as_completed(future_responses)]
responses_urls = [
(response, url) for response, url in zip(responses, eval('eval(category_class)'))]
soups_urls = [
(BeautifulSoup(item[0].text, features='lxml'), item[1]) for item in responses_urls]
for soup, url in soups_urls:
try:
title = soup.h1.text.strip()
names_urls.append([title, url])
except AttributeError:
pass
if self.print_progress:
if self.threads == 1:
for url in eval('eval(category_class)'):
response = self._get_response(url)
print(f'Got response {response} for {url}')
print(f'Fetching name of {url} ...')
if self.log:
print(f'Got response {response} for {url}', file=self.log, end='\n')
print(f'Fetching name of {url} ...', file=self.log, end='\n')
soup = BeautifulSoup(response.text, features='lxml')
try:
title = soup.h1.text.strip()
names_urls.append([title, url])
print(f'Fetching name {title} ... done')
if self.log:
print(f'Fetching name {title} ... done', file=self.log, end='\n')
except AttributeError:
print(f'Fetching name failure for {url}')
if self.log:
print(f'Fetching name failure for {url}', file=self.log, end='\n')
if self.threads > 1:
with ThreadPoolExecutor(max_workers=self.threads) as executor:
future_responses = {
executor.submit(self._get_response, category): category
for category in eval('eval(category_class)')}
for future_response in as_completed(future_responses):
response = future_response.result()
url = future_responses[future_response]
print(f'Got response {response} for {url}')
if self.log:
print(f'Got response {response} for {url}', file=self.log, end='\n')
soup = BeautifulSoup(response.text, features='lxml')
try:
title = soup.h1.text.strip()
names_urls.append([title, url])
print(f'Fetching name {title} ... done')
if self.log:
print(f'Fetching name {title} ... done', file=self.log, end='\n')
except AttributeError:
print(f'Fetching name failure for {url}')
if self.log:
print(f'Fetching name failure for {url}', file=self.log, end='\n')
if self.cache_contents:
with open(file_names[category_class], 'w') as names:
for name, url in names_urls:
names.write(name + delimiter + url + '\n')
if self.cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon')
return names_urls
def _extract_section_products(self, section: str, category_class: str):
"""
For every category/subcategory successfully scraped from the given section, product urls will be extracted.
Args:
section:
'bs': Best Sellers
'nr': New Releases
'ms': Movers & Shakers
'gi': Gift Ideas
'mw': Most Wished For
category_class: Category level indication 'categories' or 'subcategories'.
Return:
List of tuples(category name, product urls) containing product Urls for each scraped category/subcategory.
"""
products = []
names_urls = self._category_page_title_to_url(section, category_class)
urls = [item[1] for item in names_urls]
folder_name = ' '.join([self.modes[section], category_class[:-3].title() + 'y', 'Product Urls'])
if not self.print_progress:
if self.threads == 1:
products = [
(category_name, [product_url for product_url in self._extract_page_product_urls(category_url)[1]])
for category_name, category_url in names_urls]
products = [item for item in products if item[1]]
if self.threads > 1:
with ThreadPoolExecutor(max_workers=self.threads) as executor:
future_products = {executor.submit(self._extract_page_product_urls, category_url): category_url
for category_url in urls}
products = [future.result() for future in as_completed(future_products)]
products = [item for item in products if item[1]]
if self.print_progress:
products = []
if self.threads == 1:
for category_name, category_url in names_urls:
product_urls = self._extract_page_product_urls(category_url)
if product_urls[1]:
print(f'Extraction of {category_name} products ... done')
if self.log:
print(f'Extraction of {category_name} products ... done', file=self.log, end='\n')
products.append(product_urls)
else:
print(f'Extraction of {category_name} products ... failure')
if self.log:
print(f'Extraction of {category_name} products ... failure', file=self.log, end='\n')
if self.threads > 1:
with ThreadPoolExecutor(max_workers=self.threads) as executor:
future_products = {executor.submit(self._extract_page_product_urls, category_url): category_url
for category_url in urls}
for future in as_completed(future_products):
category_name, category_urls = future.result()
if category_urls:
print(f'Extraction of {category_name} products ... done')
if self.log:
print(f'Extraction of {category_name} products ... done', file=self.log, end='\n')
products.append((category_name, category_urls))
else:
print(f'Extraction of {category_name} products ... failure')
if self.log:
print(f'Extraction of {category_name} products ... failure', file=self.log, end='\n')
if self.cache_contents:
if folder_name not in os.listdir(self.path + 'Amazon'):
os.mkdir(folder_name)
os.chdir(folder_name)
for category_name, category_product_urls in products:
with open(category_name + '.txt', 'w') as links:
for url in category_product_urls:
links.write(url + '\n')
if self.cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/' + folder_name)
return products
def _get_amazon_product_details(self, product_url: str):
"""
Extract product details including:
[Price, Title, URL, Rating, Number of reviews, Sold by, Features, Technical table]
Args:
product_url: Target product.
Return:
A dictionary with the scraped details.
"""
product_html_details, text_details = {}, {}
response = self._get_response(product_url).text
html_content = BeautifulSoup(response, features='lxml')
product_html_details['Price'] = html_content.find('span', {'id': 'price_inside_buybox'})
product_html_details['Url'] = product_url
product_html_details['Title'] = html_content.title
product_html_details['Rating'] = html_content.find('span',
{'class': 'reviewCountTextLinkedHistogram noUnderline'})
product_html_details['Number of reviews'] = html_content.find('span', {'id': 'acrCustomerReviewText'})
product_html_details['Sold by'] = html_content.find('a', {'id': 'bylineInfo'})
product_html_details['Features'] = html_content.find('div', {'id': 'feature-bullets'})
if product_html_details['Features']:
product_html_details['Features'] = product_html_details['Features'].findAll('li')
technical_table = html_content.find('table', {'class': 'a-keyvalue prodDetTable'})
if technical_table:
product_html_details['Technical details'] = list(
zip([item.text.strip() for item in technical_table.findAll('th')],
[item.text.strip() for item in technical_table.findAll('td')]))
for item in product_html_details:
if isinstance(product_html_details[item], bs4.element.Tag):
text_details[item] = product_html_details[item].text.strip()
if isinstance(product_html_details[item], bs4.element.ResultSet):
text_details[item] = ' • '.join([tag.text.strip() for tag in product_html_details[item]])
if isinstance(product_html_details[item], str):
text_details[item] = product_html_details[item]
if item == 'Technical details':
text_details[item] = ' • '.join([' : '.join(pair) for pair in product_html_details[item]])
return text_details
if __name__ == '__main__':
start_time = perf_counter()
path = input('Enter path to save files: ')
session = AmazonScraper(print_progress=True, threads=20, log='amazon_log.txt', path=path)
print(session._extract_section_products('bs', 'categories'))
print(session._extract_section_products('bs', 'subcategories'))
end_time = perf_counter()
print(f'Time: {end_time - start_time} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T17:36:56.623",
"Id": "450604",
"Score": "0",
"body": "Dare I ask why you aren't using https://docs.aws.amazon.com/AWSECommerceService/latest/DG/Welcome.html ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T19:28:28.260",
"Id": "450620",
"Score": "0",
"body": "@Renderien yeah ask whatever you want. I'm not using AWS because I heard that product details are not available and that it might be limited in terms of access and so. I'm not sure if this is True, I read it somewhere and if i'm wrong, I would definitely use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T19:53:30.530",
"Id": "450625",
"Score": "0",
"body": "@Renderien may i ask for a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T20:10:03.403",
"Id": "450627",
"Score": "0",
"body": "Yep - after work ;-)"
}
] |
[
{
"body": "<h2>Default arguments</h2>\n\n<p>This default:</p>\n\n<pre><code>path=None\n</code></pre>\n\n<p>isn't effectively <code>None</code>, but instead <code>'/Users/user_name/Desktop/Amazon Scraper/'</code>. That's an immutable value, so it's safe to put into the default directly.</p>\n\n<p>An obvious issue with that path is that it's absolute and not per-user. Consider using <code>os.path.expanduser</code> with <code>~</code> instead.</p>\n\n<h2>Dict formatting</h2>\n\n<p>Writing this:</p>\n\n<pre><code>self.proxies = [{'https:': 'https://' + item.rstrip(), 'http':\n 'http://' + item.rstrip()} for item in open('proxies.txt').readlines()]\n</code></pre>\n\n<p>should have one dict item per line or it'll get confusing. In other words,</p>\n\n<pre><code>self.proxies = [{'https:': 'https://' + item.rstrip(),\n 'http': 'http://' + item.rstrip()}\n for item in open('proxies.txt').readlines()]\n</code></pre>\n\n<h2>Avoid backslash continuation</h2>\n\n<pre><code> self.starting_target_urls = \\\n {'bs': ('https://www.amazon.com/gp/bestsellers/', 'https://www.amazon.com/Best-Sellers'),\n 'nr': ('https://www.amazon.com/gp/new-releases/', 'https://www.amazon.com/gp/new-releases/'),\n 'ms': ('https://www.amazon.com/gp/movers-and-shakers/', 'https://www.amazon.com/gp/movers-and-shakers/'),\n 'gi': ('https://www.amazon.com/gp/most-gifted/', 'https://www.amazon.com/gp/most-gifted'),\n 'mw': ('https://www.amazon.com/gp/most-wished-for/', 'https://www.amazon.com/gp/most-wished-for/')}\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> self.starting_target_urls = {\n 'bs': ('https://www.amazon.com/gp/bestsellers/', 'https://www.amazon.com/Best-Sellers'),\n 'nr': ('https://www.amazon.com/gp/new-releases/', 'https://www.amazon.com/gp/new-releases/'),\n 'ms': ('https://www.amazon.com/gp/movers-and-shakers/', 'https://www.amazon.com/gp/movers-and-shakers/'),\n 'gi': ('https://www.amazon.com/gp/most-gifted/', 'https://www.amazon.com/gp/most-gifted'),\n 'mw': ('https://www.amazon.com/gp/most-wished-for/', 'https://www.amazon.com/gp/most-wished-for/')\n }\n</code></pre>\n\n<h2>Avoid manual path concatenation</h2>\n\n<p>This:</p>\n\n<pre><code> os.chdir(content_path + 'Amazon/')\n</code></pre>\n\n<p>should use <code>pathlib</code> and the <code>/</code> operator instead.</p>\n\n<h2>Use a log library</h2>\n\n<p>This:</p>\n\n<pre><code> if self.log:\n print(f'Saving {category} ... failure.', file=self.log, end='\\n')\n</code></pre>\n\n<p>shouldn't be writing to files directly. Instead, you should be setting up the stock Python logging with a file handler that goes to that file. It's more flexible and maintainable.</p>\n\n<h2>Implicit line iteration</h2>\n\n<p>For lines like this:</p>\n\n<pre><code> return [link.rstrip() for link in cats.readlines()]\n</code></pre>\n\n<p>You don't need to call <code>readlines</code>. Iterating over a file object iterates over its lines.</p>\n\n<h2>HTTP error checking</h2>\n\n<p><code>_get_response</code> should include a call to <code>raise_for_status</code>. It's a quick and easy way to get better validation on your HTTP calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:12:01.430",
"Id": "450645",
"Score": "0",
"body": "Thanks for this, I will be modifying all of the points you mentioned in my next follow up, do you have any idea about how to ensure proxies and user agents are working effectively? Because i'm getting some occasional robot checks, how to bypass the robot checks? I thought proxies and user agents should deal with such problems but it looks like not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:18:45.700",
"Id": "450646",
"Score": "0",
"body": "What exactly do you mean by robot check? Can you show an example of a failure produced by one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:40:16.953",
"Id": "450647",
"Score": "0",
"body": "okay, to see examples of when this happens, try running under `main` `session = AmazonScraper(print_progress=True, threads=10)` and choose your path then `for item in ['ms', 'nr', 'gi']: print(session._extract_section_products(item, 'subcategories'))` and change every line similar to `title = soup.h1.text` to `title = soup.title.text` and you'll encounter occasional pages named 'robot check' as title, then you can examine the html content if you want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:42:24.617",
"Id": "450648",
"Score": "0",
"body": "I think that question is better-suited to StackOverflow, but my guess is that the server is doing what it's supposed to - your client is literally a robot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:43:01.193",
"Id": "450649",
"Score": "0",
"body": "And this i think this shouldn't be happening with proxies and user agents if I understand how this works correctly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:44:59.583",
"Id": "450650",
"Score": "0",
"body": "Short of running a botnet with many source IPs, it's going to be fairly obvious to any non-trivially implemented server that you're a robot, regardless of what you do with your proxy and user agent string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T01:59:56.003",
"Id": "450651",
"Score": "0",
"body": "And what suggestions do you have for solving the problem? I won't be able to post it on SO because they disabled my account for no apparent reason and even if they didn't i think this might start a stupid competition for marking the question as duplicate as they always do without even reading what there is plus most of the SO answers for this problem are outdated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:01:58.360",
"Id": "450652",
"Score": "0",
"body": "Experiment with rate-limiting. Stop multithreading. You'll probably find a throughput threshold below which you can avoid triggering bot checks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:07:29.623",
"Id": "450655",
"Score": "0",
"body": "I tried before posting and still the same problem and since it's random, I cannot tell what rule there is with `threads = 1` I'm getting almost the same rate of failures on certain categories not including best sellers or most wished for which is strange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:08:09.697",
"Id": "450656",
"Score": "0",
"body": "`threads = 1` is not rate-limiting. You need to add sleeps between your requests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:11:28.380",
"Id": "450657",
"Score": "0",
"body": "Yeah, I might consider sleeping but that won't be as efficient for large input sizes, I'll be waiting forever. If you know some workarounds, this would be great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:12:13.570",
"Id": "450658",
"Score": "0",
"body": "Try an actual API instead of scraping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:17:12.630",
"Id": "450659",
"Score": "0",
"body": "It limits you in terms of contents and access rate but it is of course a thing to consider for light data such as title and main image and maybe price but i think the api will not give access to reviews and features because Amazon are very protective when it comes to their data. Unless i'm maybe paying for the data, I won't stand a chance with their api and maybe I'm misinformed I don't know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:17:43.800",
"Id": "450660",
"Score": "0",
"body": "I'll keep experimenting and will tell you as soon as I find solutions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:30:53.583",
"Id": "450800",
"Score": "0",
"body": "I solved the problem, by just adding an extra check in the response method."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T00:50:22.377",
"Id": "231165",
"ParentId": "231126",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231165",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T01:29:46.887",
"Id": "231126",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"multithreading",
"web-scraping",
"beautifulsoup"
],
"Title": "Ultra fast Amazon scraper multi-threaded"
}
|
231126
|
<p>I've written some C++ code, intended to run on an Arduino, the purpose of which is to talk to SparkFun's Simultaneous RFID Reader.</p>
<p><strong>The current situation:</strong></p>
<ul>
<li>The code runs fine, most of the time.</li>
<li>However, sometimes it throws up a "Module failed to respond..." error.</li>
<li>The above error tends to occur - perhaps <em>only</em> occurs - after I've made a minor change to the code, e.g. correcting spelling in a <code>Serial.println()</code> call, and then uploaded it to the Arduino.</li>
<li>This makes me think that the problem <em>may</em> be in the code. But it may not.</li>
</ul>
<p><strong>Extra detail:</strong></p>
<ul>
<li>The GitHub repository for SparkFun's Simultaneous RFID Tag Reader is <a href="https://github.com/sparkfun/SparkFun_Simultaneous_RFID_Tag_Reader_Library" rel="noreferrer">here</a>. It includes both source code and examples.</li>
<li>I was thinking that perhaps the problem is lurking in some sort of cache, which is not being cleared properly when new code is uploaded. (The "Module failed to respond..." issue is only really solved by completely powering the Arduino down, and then restarting.)</li>
<li>With that in mind, I tried putting in a couple of <code>Serial.flush()</code> statements, but this didn't seem to achieve anything useful.</li>
<li>I was thinking about perhaps re-initialising the <code>nano</code> object, but here my knowledge of C++ fails me.</li>
<li>Any other suggestions would be more than welcome.</li>
</ul>
<p><strong>The code:</strong></p>
<pre class="lang-cpp prettyprint-override"><code>// Libraries.
#include <SoftwareSerial.h>
#include "SparkFun_UHF_RFID_Reader.h"
// Constants.
#define MAX_LOOPS 10
// 100 units of power (below) = 1 dBm. Keep power < 27 dBm, i.e. 2700 units.
#define POWER 2000
#define DOT 250
#define DASH 1500
#define MIN_TWO_DIGITS_HEX 0x10
#define START_EPC 31
#define STOP_EPC '$'
#define USER_DATA_LENGTH 64
// Baud rates.
#define SOFTSERIAL_BAUD_INITIAL 115200
#define SOFTSERIAL_BAUD_NORMAL 9600
#define BAUD_A 115200
#define BAUD_B 57600
// Antennae: configure as desired.
#define ANTENNA_A true
// Status codes.
#define FAILED_TO_RESPOND 100
#define PRESS_TO_BEGIN 101
#define SCANNING 102
#define TAG_FOUND 103
#define BAD_CRC 104
#define UNKNOWN_ERROR 105
#define READING_CONTINUOUSLY 106
#define ERROR_DETAILS 107
#define SETTING_UP 108
#define SETUP_SUCCESS 109
#define TRYING_AGAIN 110
#define GIVE_UP 111
// Global variables.
SoftwareSerial softSerial(2, 3);
RFID nano;
void setup()
{
if(ANTENNA_A == false) Serial.begin(BAUD_B);
else Serial.begin(BAUD_A);
while(!Serial);
setupSoftSerial();
nano.setRegion(REGION_NORTHAMERICA);
nano.setReadPower(POWER);
// Comment out the line below, as desired.
// nano.enableDebugging();
Serial.print(PRESS_TO_BEGIN);
Serial.println(F("|Press a key to begin scanning for tags."));
while(!Serial.available());
Serial.read();
nano.startReading();
}
void loop()
{
byte responseType;
if(nano.check() == true)
{
responseType = nano.parseResponse();
if(responseType == RESPONSE_IS_KEEPALIVE)
{
Serial.print(SCANNING);
Serial.println(F("|Scanning..."));
}
else if(responseType == RESPONSE_IS_TAGFOUND)
{
printFoundTag(nano);
}
else if(responseType == ERROR_CORRUPT_RESPONSE)
{
Serial.print(BAD_CRC);
Serial.println("|Bad CRC.");
}
else
{
Serial.print(UNKNOWN_ERROR);
Serial.println("|Unknown error.");
}
}
}
// Ronseal.
void printFoundTag(RFID nano)
{
byte x;
byte tagEPCBytes = nano.getTagEPCBytes();
String epc = bytesToASCII(nano.msg, START_EPC, tagEPCBytes);
int rssi = nano.getTagRSSI();
long freq = nano.getTagFreq();
long timeStamp = nano.getTagTimestamp();
String result;
result = String(TAG_FOUND)+"|"+epc+":"+String(rssi);
Serial.println(result);
}
// Ronseal.
String bytesToASCII(byte *theBytes, int start, byte byteLength)
{
String result = "";
char letter;
char minASCII = ' ', maxASCII = '~';
byte theByte;
for(byte x = 0; x < byteLength; x++)
{
theByte = theBytes[start+x];
letter = char(theByte);
if((letter < minASCII) || (letter > maxASCII)) continue;
else if(letter == STOP_EPC) break;
else result = result+letter;
}
return result;
}
// Handles a reader that is already configured and reading.
boolean setupNano()
{
nano.begin(softSerial);
softSerial.begin(SOFTSERIAL_BAUD_NORMAL);
while(softSerial.isListening() == false);
while(softSerial.available()) softSerial.read();
nano.getVersion();
if (nano.msg[0] == ERROR_WRONG_OPCODE_RESPONSE)
{
nano.stopReading();
Serial.print(READING_CONTINUOUSLY);
Serial.println(F("|Module reading continuously. Asking it to stop..."));
delay(DASH);
}
else
{
softSerial.begin(SOFTSERIAL_BAUD_INITIAL);
nano.setBaud(SOFTSERIAL_BAUD_NORMAL);
softSerial.begin(SOFTSERIAL_BAUD_NORMAL);
delay(DOT);
}
nano.getVersion();
if(nano.msg[0] != ALL_GOOD)
{
handleError(nano.msg[0]);
return false;
}
nano.setTagProtocol();
nano.setAntennaPort();
return true;
}
// Prints a message for the error generated.
void handleError(int code)
{
Serial.print(ERROR_DETAILS);
Serial.print("|Error with code ");
Serial.print(code);
Serial.print(" = ");
if(code == ERROR_COMMAND_RESPONSE_TIMEOUT)
{
Serial.println("Timeout error.");
}
else if(code == ERROR_CORRUPT_RESPONSE)
{
Serial.println("Corrupt response.");
}
else if(code == ERROR_WRONG_OPCODE_RESPONSE)
{
Serial.println("Wrong opcode.");
}
else if(code == ERROR_WRONG_OPCODE_RESPONSE)
{
Serial.println("Wrong opcode.");
}
else if(code == ERROR_UNKNOWN_OPCODE)
{
Serial.println("Unknown opcode.");
}
else Serial.println("*Very* unknown error.");
}
// Sets up the SoftSerial, which in turns sets up the nano.
void setupSoftSerial()
{
int count = 0;
Serial.print(SETTING_UP);
Serial.println(F("|Setting up SoftSerial..."));
while(true)
{
if(setupNano())
{
Serial.print(SETUP_SUCCESS);
Serial.println(F("|Success!"));
break;
}
else
{
Serial.print(FAILED_TO_RESPOND);
Serial.println(F("|Module failed to respond."));
count++;
if(count < MAX_LOOPS)
{
Serial.print(TRYING_AGAIN);
Serial.println(F("|Trying again..."));
continue;
}
else
{
Serial.print(GIVE_UP);
Serial.println(F("|Give up."));
while(true);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:11:54.663",
"Id": "450540",
"Score": "3",
"body": "For those voting to close the question by suspicion that the code doesn't work as intended: as an electrical engineer I strongly suspect this has nothing to do with the code. Read errors after a code update are somewhat common, the usual approach is to discard the first so-many values by default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:13:28.627",
"Id": "450541",
"Score": "0",
"body": "Or force a reboot, or whatever fixes the problem. But that's an electrical limitation of firmware, not a code problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:23:13.150",
"Id": "450543",
"Score": "0",
"body": "To those thinking that this is a non-code issue: Do you know, then, how I would carry out the hardest possible reset **within the code**? Because pulling out both the power and data cables every time this error crops up isn't going to be practical in the long run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:28:29.223",
"Id": "450546",
"Score": "0",
"body": "Well, you could wire one of your pins to the RESET pin, should probably put a switch between it. Then all you have to do is put the correct signal on that pin (it's probably active low, so you'd need to pull it down). I'd do it with a switch and a resistor, I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:35:53.557",
"Id": "450548",
"Score": "0",
"body": "But, if you don't like additional hardware and prefer to live dangerous, it's explained [here](https://www.theengineeringprojects.com/2015/11/reset-arduino-programmatically.html) how to do it without."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:36:36.733",
"Id": "450549",
"Score": "0",
"body": "I doubt that the RESET pin is going to cut it. I've tried just pressing the reset button on the board. It works about 25% of the time, so usually you have to cycle it a few times. I can get the same rate of success just by re-calling the `setupNano()` function - and that doesn't involve dusting off the soldering iron."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:38:10.710",
"Id": "450550",
"Score": "0",
"body": "Your board only resets 25% of the time you press the reset button?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:41:11.757",
"Id": "450552",
"Score": "0",
"body": "No, it _resets_ every time you press the button. However, say that, before the reset, it threw up the \"Module failed to respond...\" error; the chances that it _won't_ throw up the same error _after_ each reset is about 25%."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:51:02.963",
"Id": "450553",
"Score": "0",
"body": "I recommend contacting the Arduino community about things like that. Are you still interested in a review about the rest of your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T08:59:18.053",
"Id": "450554",
"Score": "0",
"body": "Okay, no worries. Will do! A review of the code would be fantastic. My C++ definitely needs some work."
}
] |
[
{
"body": "<p>I see some things that may help you improve your program.</p>\n\n<h2>The Arduino language isn't C++</h2>\n\n<p>The language used for the Arduino isn't quite C and isn't quite C++, so if your goal is to learn or improve your C++, you might want to be careful about the differences. As <a href=\"https://www.arduino.cc/en/Main/FAQ#toc13\" rel=\"nofollow noreferrer\">they describe it</a> \"the Arduino language is merely a set of C/C++ functions that can be called from your code.\" So while the underlying compiler may actually be a C++ compiler, writing Arduino sketches is not the same as writing C++ programs. Specifically, the Arduino's use of <code>setup</code> and <code>loop</code> is unique to it. Also, all of the \"built-in\" things such as <code>digitalWrite</code> and <code>Serial</code> are non-standard. Unlike C++, there is no user-defined <code>main</code>. You can still learn useful things by learning to program the Arduino, but it's important to remain aware of the differences.</p>\n\n<h2>Add comments for non-obvious constructs</h2>\n\n<p>I happen to know that this line:</p>\n\n<pre><code>while(!Serial);\n</code></pre>\n\n<p>is intended to wait until the serial port is successfully open, but a comment to that effect would greatly aid people reading the code.</p>\n\n<h2>Use better naming</h2>\n\n<p>Looking at your <code>setupNano</code> code, I came across this line:</p>\n\n<pre><code>delay(DASH);\n</code></pre>\n\n<p>Then I had to look up <code>DASH</code> to find out it was a constant equal to 1500. Why make your readers work harder? While <code>DASH</code> and <code>DOT</code> are cute, <code>LONG_DELAY</code> and <code>SHORT_DELAY</code> would be more informative.</p>\n\n<h2>Understand pre- versus post-increment</h2>\n\n<p>If we write <code>count++</code> it has a different meaning than <code>++count</code>. The difference is that <code>count++</code> increments the value and returns the previous (unicremented) value, while <code>++count</code> returns the incremented value. It's a seemingly small difference, but on many processors, <code>++count</code> takes a wee bit less time and uses fewer machine instructions. Unless you need to actually keep the old value, I recommend always using the preincrement version <code>++count</code>. The compiler is probably smart enough to notice that you're not subsequently using the value and optimize that away anyway, but it's good to get into good habits.</p>\n\n<h2>Don't hide loop exit conditions</h2>\n\n<p>In <code>setupSoftSerial()</code> we have a rather convoluted loop construct:</p>\n\n<pre><code>while(true)\n{\n if(setupNano())\n {\n Serial.print(SETUP_SUCCESS);\n Serial.println(F(\"|Success!\"));\n break;\n }\n else\n {\n Serial.print(FAILED_TO_RESPOND);\n Serial.println(F(\"|Module failed to respond.\"));\n count++;\n\n if(count < MAX_LOOPS)\n {\n Serial.print(TRYING_AGAIN);\n Serial.println(F(\"|Trying again...\"));\n continue;\n }\n else\n {\n Serial.print(GIVE_UP);\n Serial.println(F(\"|Give up.\"));\n while(true);\n }\n }\n}\n</code></pre>\n\n<p>How, in human language, would you actually describe how this loop works? You might say \"repeat the loop until either the setup works or halt if it exhausts retries.\" That sounds more like a <code>for</code> loop to me:</p>\n\n<pre><code>for(retries = MAX_LOOPS; retries; --retries) \n{\n if(setupNano())\n {\n Serial.print(SETUP_SUCCESS);\n Serial.println(F(\"|Success!\"));\n break;\n }\n else\n {\n Serial.print(FAILED_TO_RESPOND);\n Serial.println(F(\"|Module failed to respond.\"));\n Serial.print(TRYING_AGAIN);\n Serial.println(F(\"|Trying again...\"));\n }\n}\n// if we're out of retries, give up\nif (retries == 0) {\n Serial.print(GIVE_UP);\n Serial.println(F(\"|Give up.\"));\n while(true);\n}\n</code></pre>\n\n<p>Note also that I have renamed the vaguely named <code>count</code> (count of <em>what</em>?) to the more descriptive <code>retries</code>.</p>\n\n<h2>Use a <code>switch</code> instead of a long <code>if..else</code></h2>\n\n<p>The Arduino language, like C and C++, implements a <a href=\"https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/\" rel=\"nofollow noreferrer\"><code>switch</code> control structure</a> which could replace a number of the long <code>if..else</code> chains in this code. It makes it more clear to the reader that it's one condition that's being checked for multiple values and also provides for a <code>default</code> case for the truly unexpected.</p>\n\n<h2>Control the external hardware</h2>\n\n<p>The RFID module you're using has a hardware <code>EN</code> line. If you connect that line to a GPIO pin on the Arduino, you can perform a hard reset of the module by bringing that line low and releasing it.</p>\n\n<h2>General embedded system troubleshooting</h2>\n\n<p>As every programmer knows, it's very common that things sometimes don't work. When code running on a PC doesn't work, we often have fancy tools to debug and troubleshoot, but if it's an embedded system (as with your Arduino), we don't have a screen or a lot of automatic debugging logs, so we have to get a bit more creative. In this case, you say that when you upload the code to the Arduino, things no longer seem to work. Since you're using a soft UART, I'd suggest starting there. Try to figure out if the problem is with the Arduino's serial or the RFID board. One way to do that would be to reset the RFID board as mentioned above. If you figure out which half isn't working (or perhaps they just disagree on baud rates?) then you can start figuring out why things aren't working. Are spurious characters written to the RFID board during reprogramming of the Arduino? Does the software serial port cleanly and completely reset? Are the RFID and Arduino out of sync? (I.e. does the Arduino only start listening in the middle of a sent character?) An oscilloscope or logic analyzer is extremely useful for this kind of troubleshooting. You can get a software-based device that supports both for less than you paid for the RFID board. I use a <a href=\"http://www.bitscope.com/\" rel=\"nofollow noreferrer\">BitScope</a> but there are other similar devices out there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T16:21:18.630",
"Id": "450601",
"Score": "2",
"body": "I think saying that arduino language isn't C++ is a bit of an overstatement. It is, it's just wrapped in something that adds some `include`s and calls `setup` and `loop`. But all C++ stuff is valid and I can't think of any non-standard syntax. I had used `constexpr` expressions to populate arrays on arduino, it worked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T16:33:25.477",
"Id": "450602",
"Score": "1",
"body": "@TomášZato It's based on what Arduino has said about it. \"The Arduino language is based on C/C++\" but I see that they have removed that statement from their web site. They [now say](https://www.arduino.cc/en/Main/FAQ#toc13) \"the Arduino language is merely a set of C/C++ functions that can be called from your code.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T17:23:51.740",
"Id": "450603",
"Score": "0",
"body": "Thank you ever so much for such a helpful and thorough review. I shall certainly implement most if not all of the suggestions you've made regarding the code. The `while(true)` loop is embarrassing! My only defense is that it works, and that it grew piece by piece through debugging. But your way's much better. I'll get back to you about resetting the reader board in the code. Don't hold your breath, though! My company has literally just suspended this project so I can build them a website. Luckily, I'm a lot better at JavaScript than C++!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T18:43:35.210",
"Id": "450612",
"Score": "0",
"body": "I'm glad it was useful. With any luck you'll be able to get back to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T21:33:17.220",
"Id": "450640",
"Score": "0",
"body": "@opa I've updated to clarify. Writing Arduino sketches and writing generic C++ is different even if they may derive from a common inspiration. I've explained the differences by reference to specifics and the Arduino website's own words."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T12:15:31.203",
"Id": "452482",
"Score": "1",
"body": "If anyone's still paying attention to this question... @Edward was absolutely right about taking control of the external hardware using a jumper wire between the EN pin on the reader and a GPIO pin on the Arduino. Using such a connection, I was able to make the reader go through a hard reset each time the `setup()` part of the Arduino is called. And - touch wood - the \"Module failed to respond...\" error hasn't cropped up since!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-10T17:06:05.060",
"Id": "453206",
"Score": "0",
"body": "@Tom Hosker\nIs that to say you just did the jumper wire from EN pin to, say, pin 4 on the arduino and put `int Reset = 4;` `void setup() { digitalWrite(Reset, LOW);`\nAnd it resolved the issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-11T09:00:54.660",
"Id": "453224",
"Score": "0",
"body": "I've made put a new function towards the top of `setup()`, called `resetReader()`. This new function reads: `pinMode(RESET_PIN, OUTPUT); digitalWrite(RESET_PIN, LOW); delay(1000); digitalWrite(RESET_PIN, HIGH);`. I don't want to tempt fate, but this seems to have solved the issue completely."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T13:43:31.293",
"Id": "231142",
"ParentId": "231131",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "231142",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T07:54:49.213",
"Id": "231131",
"Score": "9",
"Tags": [
"c++",
"arduino"
],
"Title": "Arduino Code for Talking to an RFID Reader"
}
|
231131
|
<p>I have a string, for example: <code>dashboard/12398911/overzicht</code> and I want to check that string for 2 values. For <code>dashboard</code> and <code>overzicht</code>. If the first check is false, then the second check doesn't need to happen.</p>
<p>This is my current code:</p>
<pre><code>private pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
private subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];
private isOnPageWithFilter(currentUrl: string): boolean {
for (const pageType of this.pageTypes) {
if (currentUrl.includes(pageType)) {
for (const subType of this.subTypes) {
if (currentUrl.includes(subType)) {
return true;
}
}
}
}
return false;
}
</code></pre>
<p>I was wondering if there's a way of doing this where I don't need a nested for loop.</p>
<p>Plunkr: <a href="https://plnkr.co/edit/FXhbCr9aaXcL61g3q7Fe?p=preview" rel="nofollow noreferrer">https://plnkr.co/edit/FXhbCr9aaXcL61g3q7Fe?p=preview</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T13:41:13.507",
"Id": "450583",
"Score": "0",
"body": "split your string using the delimiter `/` then check the index 0 and the index 2?"
}
] |
[
{
"body": "<p>You can simplify it by using <a href=\"http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\">Array.prototype.some</a> method and lazy evaluation of <code>&&</code> operator</p>\n\n<pre><code>const pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];\nconst subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];\n\nfunction isOnPageWithFilter(currentUrl) {\n return pageTypes.some(x => currentUrl.includes(x)) && subTypes.some(x => currentUrl.includes(x));\n}\n\nconsole.log(isOnPageWithFilter('foobar.com?dashboard')); // false\nconsole.log(isOnPageWithFilter('foobar.com?dashboard&overzicht')); // true\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T07:02:47.067",
"Id": "451953",
"Score": "0",
"body": "Wouldn't this return `true` for `eenfinancieelramp#onwilligeklantenkaartoon`? (How do I check *lazy evaluation*?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T08:40:17.080",
"Id": "452101",
"Score": "0",
"body": "In JavaScript (and many other languages) logical operators (&&,||) are evaluated lazily. This means that if first part of expression `a && b`, that is `a`, is evaluated to false then whole expression is false and there is no need to evaluate `b`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T12:39:40.100",
"Id": "231139",
"ParentId": "231138",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231139",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T12:12:00.300",
"Id": "231138",
"Score": "4",
"Tags": [
"javascript",
"typescript"
],
"Title": "Check a string for 2 values"
}
|
231138
|
<p>I wanted to build a bot for playing <a href="https://boardgamegeek.com/boardgame/54043/jaipur" rel="noreferrer">Jaipur</a> board game. I started by implementing a simplified version of the game without bot. Want to make sure I'm going in the right direction.
Few of the simplifications from the actual game: </p>
<ul>
<li>Prices of commodities are fixed</li>
<li>No camels</li>
<li>Only one card is visible and can be picked from the market</li>
<li>Cards are not shuffled at the start</li>
</ul>
<p><strong>Code:</strong></p>
<pre><code>import random
import numpy as np
DIAMOND = 0
GOLD = 1
SILVER = 2
SILK = 3
SPICE = 4
LEATHER = 5
commodities = [DIAMOND, GOLD, SILVER, SILK, SPICE, LEATHER]
price = [7, 6, 5, 3, 3, 1] # DIAMOND, GOLD, SILVER, SILK, SPICE, LEATHER
TAKE = 0
SELL = 1
actions = [TAKE, SELL]
class Jaipur():
def __init__(self, player1, player2):
self.market = [DIAMOND] * 6 + [GOLD] * 6 + [SILVER] * 6 + [SILK] * 8 + [SPICE] * 8 + [LEATHER] * 10
player1 = globals()[player1]
player2 = globals()[player2]
self.player1 = player1(tag='P1')
self.player2 = player2(tag='P2')
self.winner = None
self.player_turn = self.player1
def play_game(self):
# while len(self.market != 0):
while self.winner is None:
self.state = self.play_move()
self.game_winner()
if self.winner is not None:
print('P1 score: ', self.player1.score)
print('P2 score: ', self.player2.score)
print('Winner is ', self.winner)
def play_move(self, learn=False):
if self.player_turn == self.player1:
self.print_game()
new_market = self.player1.make_move(self.market, self.winner)
self.player_turn = self.player2
elif self.player_turn == self.player2:
self.print_game()
new_market = self.player2.make_move(self.market, self.winner)
self.player_turn = self.player1
def print_game(self):
print(self.market)
print('turn: ', self.player_turn.tag)
print('market: ', self.market)
print('player hand: ', self.player_turn.hand)
print('player score: ', self.player_turn.score)
def game_winner(self):
if len(self.market) == 0:
if self.player1.score > self.player2.score:
self.winner = self.player1.tag
else:
self.winner = self.player2.tag
return self.winner
class Player():
def __init__(self, tag):
self.tag = tag
self.hand = [0] * len(commodities)
self.score = 0
def hand_size(self):
return sum(self.hand)
def take(self, market):
print('taking..')
if self.hand_size() == 7:
return market
if len(market) == 0:
return market
taken = market.pop()
self.hand[taken] += 1
return market
def sell(self, market, commodity=None):
print('selling..')
if commodity is None:
commodity = np.argmax(self.hand)
if commodity in [DIAMOND, GOLD, SILVER] and self.hand[commodity] < 2:
return market
if self.hand[commodity] < 1:
return market
self.score += self.hand[commodity] * price[commodity]
if self.hand[commodity] == 3:
self.score += 2
elif self.hand[commodity] == 4:
self.score += 5
elif self.hand[commodity] >= 5:
self.score += 9
self.hand[commodity] = 0
return market
def make_move(self, market, winner):
# move = int(input('0: Take, 1: Sell. Choose move..'))
move = random.randint(0, 1)
new_market = market
if move == 0:
new_market = self.take(market)
elif move == 1:
new_market = self.sell(market)
return new_market
def play():
game = Jaipur('Player', 'Player')
game.play_game()
play()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T21:49:30.810",
"Id": "454430",
"Score": "0",
"body": "Updated question can be found here: https://codereview.stackexchange.com/questions/232662/jaipur-board-game-learning-agent"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T21:51:00.660",
"Id": "454433",
"Score": "0",
"body": "Repository: https://github.com/t-thirupathi/jaipur-board-game"
}
] |
[
{
"body": "<p>Here are a couple of first-glance observations:</p>\n\n<ol>\n<li><p>Use <a href=\"https://docs.python.org/3/library/enum.html?highlight=enum#module-enum\" rel=\"noreferrer\"><code>enum</code></a>. If you are going to have all-caps names with integers, you might as well import the module and get all the benefits.</p></li>\n<li><p>Don't pass classes by name. Pass them by value. Change this: <code>game = Jaipur('Player', 'Player')</code> into something like <code>game = Jaipur(Player, Player)</code> (note: no quotes).</p>\n\n<p>Classes are first-class objects in Python. You can pass them around just like any other object.</p></li>\n<li><p>Use the game class to enforce the rules. You have code in your Player class to check on things like the minimum number of commodities to trade. Put that in the game class instead. Also, make the game class the keeper of records. If your Player class is supposed to be an AI, then let the game handle the record-keeping and have the player just tell the game what it wants.\n(An example of the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\"><strong>Single Responsibility Principle</strong>.</a>)</p></li>\n<li><p>Don't <code>import numpy</code> just to use <code>argmax</code>! Python defines a <code>max()</code> builtin. </p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:07:41.950",
"Id": "450730",
"Score": "0",
"body": "Thanks for the valuable suggestions. I'm not used to oops concepts in python, so your answer was very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T14:54:14.737",
"Id": "231146",
"ParentId": "231141",
"Score": "8"
}
},
{
"body": "<p>Complex refactorings and optimizations:</p>\n\n<p><strong><em>Relation</em></strong><br>\nWhen starting restructuring the initial program we need to reconsider the relation between game (<code>Jaipur</code>) and players.<br>The current approach tries to instantiate players from global scope by class name:</p>\n\n<pre><code>player1 = globals()[player1]\nplayer2 = globals()[player2]\n</code></pre>\n\n<p>which is definitely a bad way. Instead, let's pass players names/tags to the game constructor:</p>\n\n<pre><code>game = Jaipur('P1', 'P2')\n</code></pre>\n\n<p>We are doing so to internally create <code>Player</code> instances and pass back-reference to the same game <code>Jaipur</code> instance for each player. Thus, each player can access/request the needed features/behavior from <em>game</em>'s public interface.<br>When looking at <code>Player</code>s all crucial methods <code>take(self, market)</code>, <code>sell(self, market, commodity=None)</code>, <code>make_move(self, market, winner)</code> we see that they all expect <code>market</code> and return that <code>market</code> although all the <em>callers</em> aren't using that return value.<br>\nBut the <code>market</code> is <strong>owned</strong> by the <em>game</em>.\nSo we make a <em>player</em> to request a copy of the current <em>market</em> state from the <em>game</em>.</p>\n\n<hr>\n\n<p><strong><em>The commodities</em></strong><br>\nAs was mentioned in previous answer, the commodity list presented as consecutive integer numbers is a good candidate to be <em>enumeration</em>. <br>But we'll go further and apply <a href=\"https://docs.python.org/3/library/enum.html#enum.unique\" rel=\"nofollow noreferrer\"><code>enum.unique</code></a> decorator that ensures only one name is bound to any one value. To proceed with new <em>enum</em> let's look at <code>Player</code>'s <code>sell</code> method and its condition:</p>\n\n<pre><code>if commodity in [DIAMOND, GOLD, SILVER] ...\n</code></pre>\n\n<p>it checks if a particular commodity is the <em>most costly</em> one.<br>\nWe'll give such a responsibility to our <code>Commodity</code> enum class so eventually it'll look as below:</p>\n\n<pre><code>@unique\nclass Commodity(Enum):\n DIAMOND = 0\n GOLD = 1\n SILVER = 2\n SILK = 3\n SPICE = 4\n LEATHER = 5\n\n @classmethod\n def is_costly(cls, val):\n return val in [cls.DIAMOND.value, cls.GOLD.value, cls.SILVER.value]\n</code></pre>\n\n<p>We'll set the current prices for commodities as a constant attribute of the <em>game</em>:</p>\n\n<pre><code>C_PRICES = [7, 6, 5, 3, 3, 1] # DIAMOND, GOLD, SILVER, SILK, SPICE, LEATHER\n</code></pre>\n\n<hr>\n\n<p><strong><code>Jaipur</code></strong> (game) class refactoring:</p>\n\n<ul>\n<li><p><code>play_game</code> method. The crucial <code>while</code> loop with condition <code>self.winner is None</code> inefficiently checks for <code>if self.winner is not None:</code> on each iteration. <br>\nInstead, we'll apply a convenient Python's feature <a href=\"https://docs.python.org/3/reference/compound_stmts.html#the-while-statement\" rel=\"nofollow noreferrer\"><code>while ... else</code></a></p></li>\n<li><p><code>play_move</code> method. Essentially initiates the current player action (take or sell) and switches/sets to another player. This is a good case for <code>itertools.cycle</code> feature (to infinitely switch to next player) <code>cycle([self.player1, self.player2])</code>. See the implementation in bottom full code.</p></li>\n<li><p>finding price for a commodity (initially based on global list access <code>price[commodity]</code>) is now moved to a <em>game</em> class:</p>\n\n<pre><code>@classmethod\ndef get_price(cls, commodity):\n return cls.C_PRICES[commodity]\n</code></pre></li>\n<li><p><em>game</em> class is able to pick a commodity from the market for a player by request:</p>\n\n<pre><code>def pick_commodity(self):\n return self._market.pop()\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p><strong><code>Player</code></strong> class refactoring:</p>\n\n<ul>\n<li><p>the constructor is now also accepts <code>game</code> parameter (<code>Jaipur</code>(game) instance) as a reference for the current game the player plays in.</p>\n\n<pre><code>def __init__(self, tag, game)\n</code></pre></li>\n<li><p><code>take</code> method. It tells that the player can only pick a commodity if he hasn't already took 7 ones (<code>if self.hand_size() == 7</code>) or he can't pick from the <em>empty</em> market <code>if len(market) == 0</code>. That's a sign for <a href=\"https://refactoring.com/catalog/consolidateConditionalExpression.html\" rel=\"nofollow noreferrer\">Consolidate conditional</a> refactoring technique.</p></li>\n<li><p><code>sell</code> method. <code>np.argmax(self.hand)</code> is aimed to return a list of indices of maximum value. Instead we'll return a position/index of the most frequent commodity in player's hand: <code>self.hand.index(max(self.hand))</code>.<br> The method also tells that the player can not sell the costly commodity of one <code>if commodity in [DIAMOND, GOLD, SILVER] and self.hand[commodity] < 2</code> and can't sell an <em>empty</em> commodity <code>if self.hand[commodity] < 1</code>. That's also a sign for <a href=\"https://refactoring.com/catalog/consolidateConditionalExpression.html\" rel=\"nofollow noreferrer\">Consolidate conditional</a> refactoring technique. See below.</p></li>\n<li><code>make_move(self, market, winner)</code> method. Accepts/passes/assigns and returns <code>new_market</code> though it's not used neither by caller or the method itself. This method would be significantly simplified/optimized. </li>\n</ul>\n\n<hr>\n\n<p>From theory to practice, the final version:</p>\n\n<pre><code>import random\nfrom enum import Enum, unique\nfrom itertools import cycle\n\n\n@unique\nclass Commodity(Enum):\n DIAMOND = 0\n GOLD = 1\n SILVER = 2\n SILK = 3\n SPICE = 4\n LEATHER = 5\n\n @classmethod\n def is_costly(cls, val):\n return val in [cls.DIAMOND.value, cls.GOLD.value, cls.SILVER.value]\n\n\nclass Jaipur:\n C_PRICES = [7, 6, 5, 3, 3, 1] # DIAMOND, GOLD, SILVER, SILK, SPICE, LEATHER\n\n def __init__(self, player1_tag, player2_tag):\n self._market = [Commodity.DIAMOND.value] * 6 + [Commodity.GOLD.value] * 6 + [Commodity.SILVER.value] * 6 + \\\n [Commodity.SILK.value] * 8 + [Commodity.SPICE.value] * 8 + [Commodity.LEATHER.value] * 10\n\n self.player1 = Player(tag=player1_tag, game=self)\n self.player2 = Player(tag=player2_tag, game=self)\n\n self.winner = None\n self._players_gen = cycle([self.player1, self.player2]) # cycling `players` generator\n self.player_turn = next(self._players_gen)\n\n @property\n def market(self):\n return self._market.copy()\n\n @classmethod\n def get_price(cls, commodity):\n return cls.C_PRICES[commodity]\n\n def pick_commodity(self):\n return self._market.pop()\n\n def play_game(self):\n while self.winner is None:\n self.switch_player()\n self.game_winner()\n else:\n print('P1 score:', self.player1.score)\n print('P2 score:', self.player2.score)\n print('Winner is', self.winner)\n\n def switch_player(self, learn=False):\n self.player_turn.make_move()\n self.player_turn = next(self._players_gen)\n self.print_game()\n\n def print_game(self):\n print('turn: ', self.player_turn.tag)\n print('_market: ', self._market)\n print('player hand: ', self.player_turn.hand)\n print('player score: ', self.player_turn.score)\n\n def game_winner(self):\n if len(self._market) == 0:\n if self.player1.score > self.player2.score:\n self.winner = self.player1.tag\n else:\n self.winner = self.player2.tag\n return self.winner\n\n\nclass Player:\n def __init__(self, tag, game):\n self.tag = tag\n self.hand = [0] * len(Commodity)\n self.score = 0\n\n self._game = game\n\n def hand_size(self):\n return sum(self.hand)\n\n def take(self):\n print('taking..')\n if len(self._game.market) > 0 and self.hand_size() < 7:\n taken = self._game.pick_commodity()\n self.hand[taken] += 1\n\n def sell(self, commodity=None):\n print('selling..')\n if commodity is None:\n commodity = self.hand.index(max(self.hand))\n\n if (Commodity.is_costly(commodity) and self.hand[commodity] > 1) or self.hand[commodity] > 0:\n self.score += self.hand[commodity] * Jaipur.get_price(commodity)\n\n if self.hand[commodity] == 3:\n self.score += 2\n elif self.hand[commodity] == 4:\n self.score += 5\n elif self.hand[commodity] >= 5:\n self.score += 9\n\n self.hand[commodity] = 0\n\n def make_move(self):\n # move = int(input('0: Take, 1: Sell. Choose move..'))\n move = random.randint(0, 1)\n self.take() if move == 0 else self.sell()\n\n\ndef play():\n game = Jaipur('P1', 'P2')\n game.play_game()\n\n\nplay()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:13:31.453",
"Id": "450734",
"Score": "1",
"body": "Thanks for the amazing answer. Great idea to have commodities as a separate class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:14:18.093",
"Id": "450736",
"Score": "0",
"body": "Also using generator to cycle through users will be handy for board games with more than two players."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:14:52.317",
"Id": "450737",
"Score": "0",
"body": "@ThirupathiThangavel, you're welcome. I've tried to provide a comprehensive solution/refactoring, it's great if people would find it useful for their needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:19:36.770",
"Id": "450738",
"Score": "0",
"body": "Question: I don't want player to access the entire game class. The player should not be able to see what's in other player's hand etc. But passing game as an argument to Player class allows that, right? How can I restrict that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:26:09.553",
"Id": "450740",
"Score": "0",
"body": "@ThirupathiThangavel, *The player should not be able to see what's in other player's hand* - that's quite feasible. You can just rearrange/adjust game's public interface and close direct access to players with changing `self.player` to `self._player`. Look at the `market` property, `Player` instance can not access it directly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T14:29:35.127",
"Id": "450755",
"Score": "1",
"body": "Nice answer. On the enums, I would not keep the values of the commodities in the market, but the actual commodities. If you change the `player.hand` to a [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter), the only thing you need to change is `def hand_size(self): return sum(self.hand.values())` and in Player.sell: `if commodity is None: commodity=self.hand.most_common(1)[0]`, but the rest of the code becomes more expressive. You could even assign the cost of the item to the value of the enum"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:21:16.470",
"Id": "450780",
"Score": "0",
"body": "@MaartenFabré, Thanks. As for \"keeping actual commodity enum objects\" in the market - honestly, I took that way from the very start, but it caused me to inconvenient \"dancing\"/check for controlling such a commodity enum object in places where it should be extracted and used as scalar int (indexing/equality comparison/containment check operations). As for presenting player's hand `self.hand = collections.Counter()`: this `commodity=self.hand.most_common(1)[0]` unfortunately would not work because `Counter.most_common()` returns a list of **tuples** like [('a', 5), ('b', 2), ('r', 2)]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:22:30.863",
"Id": "450781",
"Score": "0",
"body": "@MaartenFabré, continuing my previous comment (text limit exceeded). On initial \"empty\" hand it requires a more verbose check `commodity = self.hand.most_common(1)\n commodity = commodity[0][0] if commodity else 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:23:11.250",
"Id": "450782",
"Score": "0",
"body": "If you use the counter, you don't need the int to index. And I forgot a `[0]` to extract the index from the tuple"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:25:43.093",
"Id": "450783",
"Score": "0",
"body": "@MaartenFabré, yes, with the line `commodity = self.hand.most_common(1)[0][0]` it'll throw `IndexError: list index out of range`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:28:16.743",
"Id": "450784",
"Score": "0",
"body": "That only works when the hand is a dict (or counter)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:38:32.767",
"Id": "450789",
"Score": "0",
"body": "Or the hand is empty"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:51:12.543",
"Id": "450794",
"Score": "0",
"body": "@MaartenFabré, the hand must be empty at start and the above mentioned error occurs on hand being set as `self.hand = Counter()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:27:58.157",
"Id": "450883",
"Score": "1",
"body": "Giving the enum the cost as value won't work if 2 items cost the same: https://docs.python.org/3/library/enum.html#duplicating-enum-members-and-values"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T08:57:18.780",
"Id": "231181",
"ParentId": "231141",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231181",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T13:33:18.877",
"Id": "231141",
"Score": "13",
"Tags": [
"python",
"game"
],
"Title": "Implementing simplified Jaipur board game"
}
|
231141
|
<p>I've implemented a wrapper for AES 256 CTR mode using the cryptography.hazmat module, I am wondering if there are any vulnerabilities in my implementation, specifically about the counter and its encoding. Here is the code:</p>
<pre><code>from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CTR
from cryptography.hazmat.backends import default_backend as backend
from base58 import b58encode,b58decode
import os
#AES Cipher Class
class AES_Cipher:
#Initialise Class, Set Countner And Key
def __init__(self,key):
self.counter = 0
self.key = key
#AES 256 Requirement
assert len(self.key) == 32
#Encryption Function
def encrypt(self,plain_text):
plain_text = plain_text.encode()
self.counter += 1
cipher = Cipher(AES(self.key),CTR(self.padCounter()),backend())
encryption_engine = cipher.encryptor()
cipher_text = self.padCounter() + encryption_engine.update(plain_text) + encryption_engine.finalize()
return b58encode(cipher_text)
#Decryption Function
def decrypt(self,cipher_text):
cipher_text = b58decode(cipher_text)
self.counter = cipher_text[:16]
cipher = Cipher(AES(self.key),CTR(self.counter),backend())
decryption_engine = cipher.decryptor()
plain_text = decryption_engine.update(cipher_text[16:]) + decryption_engine.finalize()
return plain_text.decode()
#Pad The Counter Into 16 Bytes
def padCounter(self):
return bytes(str(self.counter).zfill(16),"ascii")
</code></pre>
<p>Usage:</p>
<pre><code> key = os.urandom(32)
aes_engine = AES_Cipher(key)
aes_engine.encrypt("hello world")
aes_engine.decrypt(b"7WkHvZEJRr8yMEasvh3TESoW8nBTkEUNVu2Li")
</code></pre>
|
[] |
[
{
"body": "<h2>A warning</h2>\n\n<p>You probably already saw this coming, but: I would be remiss if I didn't say it. 'Rolling your own to learn' is fine, but perhaps the most difficult and dangerous place to do it is cryptography. Cryptographic security is notoriously difficult to ascertain. The less you do yourself and the more you leave to well-reviewed, well-established libraries, the better.</p>\n\n<h2>Indentation</h2>\n\n<p>Python code typically sees three- or four-space tabs by convention; two is a little low.</p>\n\n<h2>Type hints</h2>\n\n<p>PEP484 allows for this:</p>\n\n<pre><code>def __init__(self,key):\n</code></pre>\n\n<p>to be (at a guess)</p>\n\n<pre><code>def __init__(self, key: bytes):\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>def encrypt(self,plain_text):\n</code></pre>\n\n<p>to become</p>\n\n<pre><code>def encrypt(self,plain_text: str) -> str:\n</code></pre>\n\n<h2>Helpful comments</h2>\n\n<p>This isn't one:</p>\n\n<pre><code>#Encryption Function\n</code></pre>\n\n<p>you're better off either deleting it, or writing a docstring with non-obvious documentation:</p>\n\n<pre><code>def encrypt(self,plain_text):\n \"\"\"\n Encrypts a string using this object's key and the AES algorithm.\n Returns the encrypted result, as a base58-encoded string.\n \"\"\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T18:31:14.593",
"Id": "450607",
"Score": "0",
"body": "Do you have any reference where 3 spaces are recommended for indentation? I would be very interested to hear that :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T18:33:04.557",
"Id": "450608",
"Score": "0",
"body": "@AlexV Four is the standard: https://www.python.org/dev/peps/pep-0008/#indentation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T18:34:26.723",
"Id": "450609",
"Score": "0",
"body": "For sure! The [Google Style Guide](http://google.github.io/styleguide/pyguide.html#s3.4-indentation) also lists 4 as the way to got. I was just curious about 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T18:35:49.300",
"Id": "450610",
"Score": "1",
"body": "It's a continuum, and unless you have a really good reason, just use four. Three might make for more easily-read code if you have deeply nested structures, but then again... just don't do that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T17:27:28.263",
"Id": "231150",
"ParentId": "231148",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T15:24:24.687",
"Id": "231148",
"Score": "4",
"Tags": [
"python",
"reinventing-the-wheel",
"cryptography",
"aes"
],
"Title": "Python Secure Implementation Of AES-256-CTR Using Cryptography.Hazmat"
}
|
231148
|
<p>I'm implementing this date class based on <code><ctime></code>
I'll appreciate your comments, critics and advice.</p>
<p>Please review, thank you!.</p>
<p><strong>Date.h</strong></p>
<pre><code>/*
* Date.h
*
* Usage:
* Create object, and then call Set(day, month, year)
* Throws invalid argument exception if Teb 29th is set with the wrong year (is not leap year)
* TODO: throw invalid argument exception if date is invalid
* Use GetDate() to get date formatted as "dd/mm/yyy"
* Use GetAscTime() to get date formatted as "ddd mmm yy hh:mm:ss yyyy"
* Substraction can be done between dates, it will return the differences in days
* i.e. Date today - Date yesterday = 1
* TODO: overload + operator as Date + int
* TODO: overload - operator as Date - int
*/
#include <ctime>
#include <string>
#ifndef DATE_H_
#define DATE_H_
class Date
{
public:
Date();
void Set(int day, int month, int year);
int operator - (const Date& rhs);
const char* GetDate() const;
const char* GetAscTime() const;
time_t GetDateValue() const;
private:
std::time_t ttTime;
std::tm tmTime;
mutable char szTimeBuffer[255];
static constexpr int nSecPerDay = 60 * 60 * 24;
};
#endif /* DATE_H_ */
</code></pre>
<p><strong>Date.cpp</strong></p>
<pre><code>/*
* Date.cpp
*/
#include "Date.h"
#include <stdexcept>
Date::Date()
: ttTime(0), tmTime({0}), szTimeBuffer("")
{
std::time(&ttTime);
localtime_s(&tmTime, &ttTime);
}
void Date::Set(int day, int month, int year)
{
tmTime.tm_mday = day;
tmTime.tm_mon = month - 1;
tmTime.tm_year = year - 1900;
ttTime = std::mktime(&tmTime);
// Temp date constructed to check if Feb 29th for the specified year exists
// checks if the value of 29/Feb/YYYY is the same as 01/Mar/YYYY
// if true, means that year is not leap year and should not have Feb 29th
// throws invalid argument exception
std::tm tmTemp = {0};
std::time_t ttTemp = 0;
// Specify march 1st, use same year as input
tmTemp.tm_mday = 1;
tmTemp.tm_mon = month;
tmTemp.tm_year = tmTime.tm_year;
ttTemp = std::mktime(&tmTemp);
if(ttTemp == ttTime)
{
std::string errMsg("Error!, Feb 29th doesn't exist in year ");
errMsg.append(std::to_string(tmTime.tm_year + 1900));
errMsg.append("!!");
throw( std::invalid_argument(errMsg) );
}
}
int Date::operator -(const Date& rhs)
{
return (std::difftime(ttTime, rhs.ttTime) / nSecPerDay);
}
const char* Date::GetDate() const
{
std::strftime(szTimeBuffer, 255, "%d/%m/%y", &tmTime);
return szTimeBuffer;
}
const char* Date::GetAscTime() const
{
asctime_s(szTimeBuffer, 255, &tmTime);
return szTimeBuffer;
}
time_t Date::GetDateValue() const
{
return ttTime;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:41:28.243",
"Id": "450773",
"Score": "0",
"body": "Usually, `nSecPerDay = 60 * 60 * 24` - but not when there's a leap second!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T20:31:33.120",
"Id": "450825",
"Score": "0",
"body": "Well you got me in a trouble there :D. As far as I've read, there's 1 leap second every year either at June 30th or Dec 31st. So, I can probably make it float and add **0.0027f** (_1 second divided by 365 [366 if is leap year]_) to nSecPerDay to compensate the leap second. As keeping track of dates instead of time, won't be much of a difference, at least for **86400** years, isn't it? :("
}
] |
[
{
"body": "<p>A few things I see:</p>\n\n<p>The subtraction(<code>-</code>) operator would make more sense to return a <code>Date</code> object instead of an <code>int</code>. This would also fit in with standard practice. If such a function is needed, I would suggest naming a specific function for that,<code>DiffDays</code> perhaps. This has the advantage being more intuitive for the user.</p>\n\n<p>Instead of requiring each instance of the <code>Date</code> object to require the user calling <code>Set</code>, it would be more intuitive to overload the constructor.</p>\n\n<p>It seems to me that returning a <code>string</code> instead of a <code>char*</code> would be more in fitting with a c++ program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T21:24:14.410",
"Id": "450638",
"Score": "0",
"body": "Thanks!, you're right. I just overloaded the + operator, returning a Date, but for \"-\", I didn't see it that way. I had the constructor overloaded, but had to remove it temporarily because couldn't use it outside try{} scope. But I will add it again. std::string was coming next (thats why I included <string>\" :D. Thank you for your replies, they are very useful to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:42:42.413",
"Id": "450774",
"Score": "0",
"body": "I would say that that subtraction ought to return a `Duration` object of some sort (and we should be able to add and subtract durations to/from dates and to/from each other)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T20:15:40.473",
"Id": "450822",
"Score": "0",
"body": "Duration as in `std::chrono::duration`?. if that so, then it would change the whole purpose of the class, which is date (no time). or what other kind of duration object are you refering to?. thanks for the suggestion, BTW :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T20:35:34.623",
"Id": "231156",
"ParentId": "231154",
"Score": "3"
}
},
{
"body": "<p>Ok, this is the updated class. Added your suggestions</p>\n\n<p><strong>Main.h</strong></p>\n\n<pre><code>/*\n * Date.h\n *\n * Usage:\n * Create object, and then call Set(day, month, year)\n * Throws invalid argument exception if Teb 29th is set with the wrong year (is not leap year)\n * TODO: throw invalid argument exception if date is invalid\n * Use GetDate() to get date formatted as \"dd/mm/yyyy\"\n * Use GetAscTime() to get date formatted as \"ddd mmm yy hh:mm:ss yyyy\"\n * Substraction can be done between dates with DateDiff(), it will return the differences in days\n * i.e. Date today - Date yesterday = 1\n */\n#include <ctime>\n#include <string>\n\n#ifndef DATE_H_\n#define DATE_H_\n\nclass Date\n{\npublic:\n Date();\n Date(int day, int month, int year);\n void Set(int day, int month, int year);\n std::string GetDate() const;\n std::string GetAscTime() const;\n std::string GetUTC();\n int DateDiff(const Date& rhs);\n time_t GetDateValue() const;\n bool operator == (const Date& rhs);\n Date operator + (int days);\n Date operator - (int days);\n\nprivate:\n std::time_t ttTime;\n std::tm tmTime;\n mutable char szTimeBuffer[255];\n static constexpr int nSecPerDay = 60 * 60 * 24;\n};\n\n#endif /* DATE_H_ */\n</code></pre>\n\n<p><strong>Main.cpp</strong></p>\n\n<pre><code>/*\n * Date.cpp\n */\n#include \"Date.h\"\n#include <stdexcept>\n\nDate::Date()\n : ttTime(0), tmTime({0}), szTimeBuffer(\"\")\n{\n std::time(&ttTime);\n localtime_s(&tmTime, &ttTime);\n}\n\nDate::Date(int day, int month, int year)\n : ttTime(0), tmTime({0}), szTimeBuffer(\"\")\n{\n Set(day, month, year);\n}\n\nvoid Date::Set(int day, int month, int year)\n{\n tmTime.tm_mday = day;\n tmTime.tm_mon = month - 1;\n tmTime.tm_year = year - 1900;\n\n ttTime = std::mktime(&tmTime);\n\n // Temp date constructed to check if Feb 29th for the specified year exists\n // checks if the value of 29/Feb/YYYY is the same as 01/Mar/YYYY\n // if true, means that year is not leap year and should not have Feb 29th\n // throws invalid argument exception\n\n std::tm tmTemp = {0};\n std::time_t ttTemp = 0;\n\n // Specify march 1st, use same year as input\n tmTemp.tm_mday = 1;\n tmTemp.tm_mon = month;\n tmTemp.tm_year = tmTime.tm_year;\n\n ttTemp = std::mktime(&tmTemp);\n\n if(ttTemp == ttTime)\n {\n std::string errMsg(\"Error!, Feb 29th doesn't exist in year \");\n errMsg.append(std::to_string(tmTime.tm_year + 1900));\n errMsg.append(\"!!\");\n throw( std::invalid_argument(errMsg) );\n }\n\n}\n\nint Date::DateDiff(const Date& rhs)\n{\n return (std::difftime(ttTime, rhs.ttTime) / nSecPerDay);\n}\n\nstd::string Date::GetDate() const\n{\n std::strftime(szTimeBuffer, 255, \"%d/%m/%y\", &tmTime);\n return std::string(szTimeBuffer);\n}\n\nstd::string Date::GetAscTime() const\n{\n asctime_s(szTimeBuffer, 255, &tmTime);\n return std::string(szTimeBuffer);\n}\n\ntime_t Date::GetDateValue() const\n{\n return ttTime;\n}\n\nbool Date::operator ==(const Date &rhs)\n{\n return (\n (tmTime.tm_year == rhs.tmTime.tm_year) &&\n (tmTime.tm_mday == rhs.tmTime.tm_mday) &&\n (tmTime.tm_mon == rhs.tmTime.tm_mon)\n );\n}\n\nDate Date::operator +(int days)\n{\n std::tm tmTemp = {0};\n std::time_t ttTemp = ttTime + (days * nSecPerDay);\n localtime_s(&tmTemp, &ttTemp);\n Date dTemp(tmTemp.tm_mday, tmTemp.tm_mon + 1, tmTemp.tm_year + 1900);\n return dTemp;\n}\n\nstd::string Date::GetUTC()\n{\n std::tm tmTemp = {0};\n gmtime_s(&tmTemp, &ttTime);\n std::strftime(szTimeBuffer, 255, \"%c %z\", &tmTemp);\n\n return std::string(szTimeBuffer);\n}\n\nDate Date::operator -(int days)\n{\n return operator+(-days);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T21:58:17.297",
"Id": "231162",
"ParentId": "231154",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231156",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T18:33:40.343",
"Id": "231154",
"Score": "1",
"Tags": [
"c++",
"datetime"
],
"Title": "Date Class, implemented"
}
|
231154
|
<p>I wanted to ask if this is a better way to find a latest file in given directory. This is my current approach:</p>
<pre><code>import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.ZoneId;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FilesOperations {
public static void main(String[] args) throws IOException {
Set<Path> pathSet = getFilesFromDirectory("C:some/path/");
iteratePaths(pathSet);
getLatestFile(pathSet);
}
public static Set<Path> getFilesFromDirectory(String directory) {
Set<Path> pathSet = new HashSet<>();
Pattern pattern = Pattern.compile("(test\\d-)(\\d{12})(\\.txt)");
Path lookUpPath = Paths.get(directory);
Stream<Path> stream = null;
try {
stream = Files.find(lookUpPath, 1, (path, basicFileAttributes) -> {
File file = path.toFile();
return !file.isDirectory() && pattern.matcher(file.getName()).matches();
});
stream.forEach(path -> {
pathSet.add(path);
});
} catch (IOException e) {
e.printStackTrace();
}
stream.close();
return pathSet;
}
public static void iteratePaths(Set<Path> pathSet) {
pathSet.stream().forEach(path -> {
System.out.println(path);
});
}
public static Path getLatestFile(Set<Path> pathSet) throws IOException {
long fileTime = 0;
Path pathToReturn = null;
BasicFileAttributes attr = null;
for (Path path : pathSet) {
attr = getBasicFileAttributes(path);
if (attr.creationTime().toMillis() > fileTime) {
fileTime = attr.creationTime().toMillis();
pathToReturn = path;
}
}
attr = getBasicFileAttributes(pathToReturn);
System.out.println("Latest file: " + pathToReturn + " - " + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
return pathToReturn;
}
private static BasicFileAttributes getBasicFileAttributes(Path pathToReturn) throws IOException {
BasicFileAttributes attr;
attr = Files.readAttributes(pathToReturn, BasicFileAttributes.class);
return attr;
}
}
</code></pre>
<p>I know this is quite simple without any sophisticated solutions, but it works. I hope you can point some places for improvements. If you have some ideas, how to refactor code to use more streams, it would be great (e.g. in <code>getLatestFile()</code> ).</p>
|
[] |
[
{
"body": "<p>some minore issues only...</p>\n\n<h2>naming / return type</h2>\n\n<p><code>public static Path getLatestFile()</code> assumes that you return only <strong>ONE</strong> file, but it's easily possible that you have two files of the same date... so you should maybe return a <code>Set<Path></code> from your method <code>getLatestFiles()</code>. This method would return <strong>all</strong> files with the latest time stamp.</p>\n\n<h2>use a logging framework</h2>\n\n<p>you should write infos into a proper logging stream:</p>\n\n<pre><code>System.out.println(\"Latest file: \" + pathToReturn + \" - \" + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());\n</code></pre>\n\n<h2>note:</h2>\n\n<p>you could write the corresponding information <strong>directly</strong> inside the loop. </p>\n\n<pre><code>for (Path path : pathSet) {\n attr = getBasicFileAttributes(path);\n if (attr.creationTime().toMillis() > fileTime) {\n fileTime = attr.creationTime().toMillis();\n pathToReturn = path;\n //here\n System.out.println(\"Latest file: \" + pathToReturn + \" - \" + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());\n }\n }\n\n //instead of here:\n //attr = getBasicFileAttributes(pathToReturn);\n //System.out.println(\"Latest file: \" + pathToReturn + \" - \" + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());\n</code></pre>\n\n<h2>more significant code (tell, don't ask):</h2>\n\n<p>maybe it's just my style but i would really directly return what is said:</p>\n\n<pre><code>private static BasicFileAttributes getBasicFileAttributes(Path pathToReturn) throws IOException {\n return Files.readAttributes(pathToReturn, BasicFileAttributes.class);\n}\n</code></pre>\n\n<h2>use a test case</h2>\n\n<p>instead of testing your code in a main-methode write a junit test. that makes the code clearer to read and you can get rid of the methods <code>getFilesFromDirectory()</code> and <code>iteratePaths()</code> which are only for testing.</p>\n\n<p>ever since the test methods are still in review let me advise you about these:</p>\n\n<h2>possible NPE</h2>\n\n<p>it's possible to create a <code>NullPointerException</code>:</p>\n\n<pre><code>Stream<Path> stream = null;\ntry {...} catch (IOException e) {...}\n//if an exception is raised within this block above an NPE will be thrown!\nstream.close();\n</code></pre>\n\n<p>maybe you could consider a try-with-resources block? maybe you don't care because it's a mere test method, haha =)</p>\n\n<h2>use a Logger / Handle Exceptions</h2>\n\n<p>what do you do if an exception really happens? you should implement the actions that should happen in case of exception - not just printing to stacktrace:</p>\n\n<pre><code>Stream<Path> stream = null;\n try {...} catch (IOException e) {\n //don't print - take actions instead!\n //e.printStackTrace();\n }\n</code></pre>\n\n<p>as said above, maybe you don't care because it's a mere test method...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:28:28.753",
"Id": "450785",
"Score": "1",
"body": "Hi, thank you for your advices. In this particular case, I don't expect more then one file from the exact same time, but in more general approach it is a very good idea. I was writing this in hurry, thats why there are no loggers and exceptions handling - but yes - this are must have. Regarding NPE, I will think about `Optional` (I have no idea right now if it is possible for `Stream`. Thank you for your time, to explaining the topic in details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T17:21:16.560",
"Id": "450796",
"Score": "1",
"body": "@Fangir thank **you** very much for sharing your code!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T05:29:23.753",
"Id": "231170",
"ParentId": "231155",
"Score": "4"
}
},
{
"body": "<p>Unless you'll be using the regular expression pattern for other things it can be simplified by removing the unnecessary brackets. Also since it never changes it would make sense to keep it as a constant in the class. A better name would also be a good idea:</p>\n\n<pre><code>private static final Pattern FILENAME_PATTERN = Pattern.compile(\"test\\\\d-\\\\d{12}\\\\.txt\");\n</code></pre>\n\n<p>Setting <code>stream</code> to null runs the danger that <code>stream.close()</code> will cause a <code>NullPointerException</code>, if something goes wrong. Better use \"try with resources\" as @MartinFrank suggests.</p>\n\n<p>Instead of using <code>.forEach</code> on the stream use <code>.collect</code> to create a <code>Set</code>:</p>\n\n<pre><code>public static Set<Path> getFilesFromDirectory(String directory) {\n\n Path lookUpPath = Paths.get(directory);\n\n try (Stream<Path> stream = Files.find(lookUpPath, 1, (path, basicFileAttributes) -> {\n File file = path.toFile();\n return !file.isDirectory() && FILENAME_PATTERN.matcher(file.getName()).matches();\n })) {\n return stream.collect(Collectors.toSet());\n } catch (IOException e) {\n e.printStackTrace();\n return Collections.emptySet();\n }\n\n}\n</code></pre>\n\n<p>In <code>getLatestFile</code> don't declare <code>BasicFileAttributes attr</code> outside the loop. The use after the loop is a \"different\" variable, so it should be declared separately. </p>\n\n<p>Actually you shouldn't be be printing to <code>System.out</code> in this method at all. Either it's a debugging help, then you should be using proper logging, or it's part of the functionality to display information about the file to the user, then this should happen outside this method. </p>\n\n<pre><code>public static Path getLatestFile(Set<Path> pathSet) throws IOException {\n\n long fileTime = 0;\n Path pathToReturn = null;\n\n for (Path path : pathSet) {\n BasicFileAttributes attr = getBasicFileAttributes(path);\n if (attr.creationTime().toMillis() > fileTime) {\n fileTime = attr.creationTime().toMillis();\n pathToReturn = path;\n }\n }\n return pathToReturn;\n}\n</code></pre>\n\n<p>If you need creation time (or more attributes of the file) later, then you should have the method return that too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T10:37:02.857",
"Id": "231254",
"ParentId": "231155",
"Score": "2"
}
},
{
"body": "<p>Improvements:</p>\n\n<ul>\n<li>End-to-end use of <code>Stream<Path></code>, avoiding reading all <code>Path</code>s into memory</li>\n<li>Written as a utility method (better for unit testing)</li>\n<li>Use of <a href=\"https://www.baeldung.com/java-sneaky-throws\" rel=\"nofollow noreferrer\">sneaky throws</a> to \"downgrade\" (checked) <code>IOException</code> for use in a lambda.</li>\n<li>NOT DONE. Cache <code>Pattern</code> once <em>ever</em></li>\n<li>NOT DONE. Some level of Javadoc.</li>\n<li>NOT DONE. Swallow <code>IOException</code> and return <code>Optional.absent()</code></li>\n<li>NOT DONE. Side-caching of attributes to avoid re-reading them</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) throws IOException {\n Optional<Path> f = getLatestFile(Path.of(\".\"), \".*\\\\.java\");\n System.out.println(f);\n }\n\n public static Optional<Path> getLatestFile(Path root, String filenameRegex) throws IOException {\n Pattern pattern = Pattern.compile(filenameRegex);\n return Files.find(\n root,\n 6,\n (p, attr) ->\n !attr.isDirectory() &&\n pattern.matcher(p.getFileName().toString()).matches())\n .max(Comparator.comparing(FilesNewest::creationTime));\n }\n\n private static <E extends Throwable> FileTime creationTime(Path p) throws E {\n try {\n return Files.readAttributes(p, BasicFileAttributes.class).creationTime();\n } catch (IOException e) {\n //noinspection unchecked\n throw (E)e; // Sneaky throws\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-10T22:41:55.480",
"Id": "232164",
"ParentId": "231155",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231170",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T19:59:14.710",
"Id": "231155",
"Score": "5",
"Tags": [
"java",
"file",
"file-system",
"io",
"stream"
],
"Title": "Proper way to find newest file in a directory"
}
|
231155
|
<p>I have a simple lock-free queue, which supports multiple producers, but only one consumer. It is based on a constant-sized ring buffer and stores only pointers to a class and not actual instances. Also it uses pre-C++11 and GCC-specific functions.</p>
<p>Is is implemented properly or does it have a data race? I only care that it works properly on x64/x86 Linux.</p>
<pre><code>// header
class LockFreeQueue {
public:
LockFreeQueue(unsigned long size);
~LockFreeQueue();
bool Enqueue(Element* element);
bool Dequeue(Element** element);
bool Peek(Element** element);
unsigned long Size();
private:
unsigned long size_;
volatile Element** elements_;
volatile unsigned long idx_r_; // index of read
volatile unsigned long idx_w_; // index of write
volatile unsigned long idx_w_cas_;
};
// impl
LockFreeQueue::LockFreeQueue(unsigned long size) {
size_ = size;
idx_r_ = 0;
idx_w_ = 0;
idx_w_cas_ = 0;
elements_ = (volatile Element**)(new Element*[size]);
}
LockFreeQueue::~LockFreeQueue() {
delete[] elements_;
}
bool LockFreeQueue::Enqueue(Element* element) {
while (true) {
unsigned long prev_idx_w = idx_w_cas_;
unsigned long next_idx_w = (prev_idx_w + 1) % size_;
if (next_idx_w == idx_r_) return false;
if (__sync_bool_compare_and_swap(&idx_w_cas_, prev_idx_w, next_idx_w)) {
elements_[prev_idx_w] = element;
while (!__sync_bool_compare_and_swap(&idx_w_, prev_idx_w, next_idx_w)) {}
break;
}
}
return true;
}
bool LockFreeQueue::Dequeue(Element** element) {
if (idx_r_ == idx_w_) return false;
unsigned long next_idx_r = (idx_r_ + 1) % size_;
*element = (Element*) elements_[idx_r_];
idx_r_ = next_idx_r;
return true;
}
bool LockFreeQueue::Peek(Element** element) {
if (idx_r_ == idx_w_) return false;
*element = (Element*) elements_[idx_r_];
return true;
}
unsigned long LockFreeQueue::Size() {
if (idx_w_ >= idx_r_) return idx_w_ - idx_r_;
return size_ - idx_r_ + idx_w_;
}
</code></pre>
<p>Note that I don't have any tests for the code. It also was written by someone else I cannot reach.</p>
<p>I know that <code>volatile</code> alone does not guarantee correctness, but I wonder if is sufficient together with CAS.</p>
<p>EDIT:</p>
<p>Usage in existing code goes like this:</p>
<p>Producer thread (x4):</p>
<pre><code>LockFreeQueue* theQueue = ...
while (true) {
Element* element = new Element();
// do some short work
//
while(!theQueue->Enqueue(element)) {}
}
</code></pre>
<p>Consumer thread:</p>
<pre><code>LockFreeQueue* theQueue = ...
while (true) {
Element* element;
if (theQueue->Dequeue(&element)) {
// do some work with the element
//
delete element;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:51:06.897",
"Id": "450694",
"Score": "5",
"body": "`volatile` doesn't protect your variables from race conditions. You can read more about that [here](https://stackoverflow.com/questions/2484980/why-is-volatile-not-considered-useful-in-multithreaded-c-or-c-programming)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:18:12.070",
"Id": "450765",
"Score": "3",
"body": "You might want to `#include <atomic>` rather than relying on compiler-specific extensions. BTW, you should consider including your test code in the question, so we can see how you expect this to be used (and perhaps identify tests you've missed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T14:55:29.957",
"Id": "450951",
"Score": "0",
"body": "I wish I had tests for the code. I inherited it as is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T19:00:12.567",
"Id": "450987",
"Score": "0",
"body": "Even if the `volatile` would be the right thing to use, it probably should have been `Element *volatile *elements`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T21:03:16.177",
"Id": "231159",
"Score": "6",
"Tags": [
"c++",
"queue",
"lock-free"
],
"Title": "Simple lock-free queue - multiple producers, single consumer"
}
|
231159
|
<p>I'm trying to implement a multi-variate, multiple-step model to forecast the day ahead electricity prices (h+1,h+2,...,h+24). I know how to do one forecast, but I'm confused with how to implement a multiple output approach where each forecast gives a vector of predictions for each hour in the day head for one shot (the multiple output strategy in <a href="https://machinelearningmastery.com/multi-step-time-series-forecasting/" rel="nofollow noreferrer">https://machinelearningmastery.com/multi-step-time-series-forecasting/</a>).</p>
<p>The gist of what I've done is get the code that predicts one time step, and modify it by converting the output into a sequence for the next 24 hours time shift, instead of just say one ElecPrice shifted 24 hours into the future:</p>
<pre><code>Y['ElecPrice1'] = df['RT_LMP'].shift(-1)
Y['ElecPrice2'] = df['RT_LMP'].shift(-2)
Y['ElecPrice3'] = df['RT_LMP'].shift(-3)
...
Y['ElecPrice3'] = df['RT_LMP'].shift(-24)
</code></pre>
<p>I also changed the number of output signals my model has to predict.</p>
<p>Basically I made an entire 24 new columns instead of just one for my predictions. I have adjusted my dataset accordingly (no dangling NaNs, etc.). It seems too simple that I'm worrying if all I'm doing is making a prediction for one hour and copying that for the rest of the hours.</p>
<p>The sample code can be viewed in this link <a href="https://nbviewer.jupyter.org/github/Joichiro666/Forecasting-sharing/blob/master/LSTM-DNN%203.ipynb" rel="nofollow noreferrer">https://nbviewer.jupyter.org/github/Joichiro666/Forecasting-sharing/blob/master/LSTM-DNN%203.ipynb</a> (ignore anything below generate predictions)</p>
<p>I just want to confirm if what I'm doing is correct or not.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T22:33:10.170",
"Id": "450641",
"Score": "0",
"body": "I could show you how to automate the creation of all the `Y['ElecPrice3'] = df['RT_LMP'].shift(-24)` lines, but if you aren't sure if the code is correct, it isn't on topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T22:45:10.137",
"Id": "450642",
"Score": "0",
"body": "Yes, please. And, yes I'm also not sure if its correct - is there a more correct board for this question?"
}
] |
[
{
"body": "<p>Similar to my recent review <a href=\"https://codereview.stackexchange.com/questions/231064/anipop-the-anime-downloader/231067#231067\">here</a>, you can automate the simple repetition of each line by thinking about what's the same in each line, and what's different.</p>\n\n<p>Each line seems to be, essentially:</p>\n\n<pre><code>Y['ElecPriceN'] = df['RT_LMP'].shift(-N)\n</code></pre>\n\n<p>The only thing that changes each time is <code>N</code>, so just loop over a <code>range</code> that generates numbers:</p>\n\n<pre><code>for n in range(1, 25): # range(24) if you started at 0 instead of 1\n Y['ElecPrice' + str(n)] = df['RT_LMP'].shift(-n)\n</code></pre>\n\n<ul>\n<li><p>Construct a key string by taking <code>n</code>, stringifying it using <code>str</code>, then concatenating it to the name.</p></li>\n<li><p>Generate a <code>shift</code> value by just negating <code>n</code>. <code>-n</code> is the same as <code>n * -1</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>As for \"I just want to confirm if what I'm doing is correct or not.\", that's offtopic here, and too broad of a question for anywhere on Stack Exchange. A broad site like Reddit may be able to help you though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T23:01:38.433",
"Id": "231163",
"ParentId": "231161",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T21:52:50.937",
"Id": "231161",
"Score": "-1",
"Tags": [
"python",
"beginner",
"algorithm",
"machine-learning"
],
"Title": "How to write a multivariate multi-step forecasting from a multivariate single step"
}
|
231161
|
<p>I built a merge sort in python just to have a more thorough understanding of how the algorithm works. What I have written works fine, but I assume there is room for improvement and ways to make my implementation more efficient. </p>
<p>I would appreciate any feedback or critiques! </p>
<pre><code>"""
2019-10-17
This project simply re-creates common sorting algorithms
for the purpose of becoming more intimately familiar with
them.
"""
import random
import math
#Generate random array
array = [random.randint(0, 100) for i in range(random.randint(5, 100))]
print(array)
#Merge Sort
def merge(array, split = True):
split_array = []
#When the function is recursively called by the merging section, the split will be skipped
continue_splitting = False
if split == True:
#Split the array in half
for each in array:
if len(each) > 1:
split_array.append(each[:len(each)//2])
split_array.append(each[len(each)//2:])
continue_splitting = True
else:
split_array.append(each)
if continue_splitting == True:
sorted_array = merge(split_array)
#A return is set here to prevent the recursion from proceeding once the array is properly sorted
return sorted_array
else:
sorted_array = []
if len(array) != 1:
#Merge the array
for i in range(0, len(array), 2):
#Pointers are used to check each element of the two mergin arrays
pointer_a = 0
pointer_b = 0
#The temp array is used to prevent the sorted array from being corrupted by the sorting loop
temp = []
if i < len(array) - 1:
#Loop to merge the array
while pointer_a < len(array[i]) or pointer_b < len(array[i+1]):
if pointer_a < len(array[i]) and pointer_b < len(array[i+1]):
if array[i][pointer_a] <= array[i + 1][pointer_b]:
temp.append(array[i][pointer_a])
pointer_a += 1
elif array[i + 1][pointer_b] < array[i][pointer_a]:
temp.append(array[i + 1][pointer_b])
pointer_b += 1
#If the pointer is equal to the length of the sub array, the other sub array will just be added fully
elif pointer_a < len(array[i]):
for x in range(pointer_a, len(array[i])):
temp.append(array[i][x])
pointer_a += 1
elif pointer_b < len(array[i + 1]):
for x in range(pointer_b, len(array[i + 1])):
temp.append(array[i + 1][x])
pointer_b += 1
else:
for each in array[i]:
temp.append(each)
sorted_array.append(temp)
if len(sorted_array) != 1:
#Recursively sort the sub arrays
sorted_array = merge(sorted_array, False)
return sorted_array
sorted_array = merge([array])[0]
print()
print(sorted_array)
</code></pre>
|
[] |
[
{
"body": "<p>At the end of the code, it looks like <code>merge()</code> is called by nesting the array in a list and the result is the 0th element of the returned list. This is an unusual calling convention, is different than the way the built in sorted() is called, and it is not documented, which would likely lead to many errors. If this interface is needed for the algorithm to work, it would be better if <code>merge()</code> handled these details an then called another function. For example:</p>\n\n<pre><code>def merge(array):\n return _merge([array], True)\n\ndef _merge(array, True):\n ... same as your original code ...\n</code></pre>\n\n<p>The boolean argument <code>split</code> appears to control whether <code>merge()</code> splits the array into two smaller parts or merges two smaller parts together. This complicates the logic and makes it more difficult to follow. It would be better two have two separate functions.</p>\n\n<p>It is also appears that the code takes parts of a recursive implementation and parts from an iterative implementation. For example, <code>merge</code> is called recursively to split the array into smaller arrays, but <code>for i in range(0, len(array), 2):</code> loops over a list of subarrays and merges them in pairs.</p>\n\n<p>The essence of merge sort is: if the array isn't sorted, split it into two parts, sort both parts separately, and then merge the two parts together. Here is a recursive implementation:</p>\n\n<pre><code>def merge_sort(array):\n if is_not_sorted(array):\n # split array in two\n middle = len(array) // 2\n left_half = array[:middle]\n right_half = array[middle:]\n\n # sort each part\n left_half = merge_sort(left_half)\n right_half = merge_sort(right_half)\n\n array = merge_halves(left_half, right_half)\n return array\n\n else:\n # array is already sorted\n return array\n</code></pre>\n\n<p>Usually, <code>if is_not_sorted():</code> is implemented as <code>if len(array) > 1:</code> (if there is more than one item in the array, it is presumed to be unsorted). But some implementations (like Python's builtin sorted or list.sort) check small lists to see if they are already sorted. Also, the two halves are usually sorted using a recursive call to <code>merge_sort()</code>, but some implementations may use a different sorting algorithm if the array is small.</p>\n\n<p><code>merge_halves()</code> is then basically the same as the <code>while pointer_a < len(array[i])...</code> loop in your code (with a few simplifications):</p>\n\n<pre><code>def merge_halves(left, right):\n merged_array = []\n pointer_a = 0\n pointer_b = 0\n while pointer_a < len(left) and pointer_b < len(right):\n if left[pointer_a] <= right[pointer_b]:\n merged_array.append(left[pointer_a])\n pointer_a += 1\n\n elif right[pointer_b] < left[pointer_a]:\n merged_array.append(right[pointer_b])\n pointer_b += 1\n\n #At the end of one subarray, extend temp by the other subarray\n if pointer_a < len(left):\n merged_array.extend(left[pointer_a:])\n\n elif pointer_b < len(right):\n merged_array.extend(right[pointer_b:])\n\n return merged_array\n</code></pre>\n\n<p>An iterative version might look something like this (code on the fly, so may have errors):</p>\n\n<pre><code>def merge(array):\n # make all the sub arrays 1 item long. A more intelligent version might\n # split it into runs that are already sorted\n array = [[item] for item in array]\n\n while len(array) > 1:\n temp = []\n\n for i in range(0, len(array), 2):\n #Pointers are used to check each element of the two mergin arrays\n pointer_a = 0\n pointer_b = 0\n\n #Loop to merge the array\n while pointer_a < len(array[i]) and pointer_b < len(array[i+1]):\n if array[i][pointer_a] <= array[i + 1][pointer_b]:\n temp.append(array[i][pointer_a])\n pointer_a += 1\n\n else:\n temp.append(array[i + 1][pointer_b])\n pointer_b += 1\n\n if pointer_a < len(array[i]):\n temp.extend(array[i][x])\n\n elif pointer_b < len(array[i + 1]):\n temp.extend(array[i + 1][x])\n\n\n #there were an odd number of sub_arrays, just copy over the last one\n if len(sub_arrays) % 2:\n temp.append(sub_arrays[-1])\n\n array = temp\n\n return array[0]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:39:43.987",
"Id": "231174",
"ParentId": "231168",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231174",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T02:22:52.607",
"Id": "231168",
"Score": "4",
"Tags": [
"python",
"sorting",
"mergesort"
],
"Title": "Merge Sort from Scratch in Python"
}
|
231168
|
<p>I'm trying to implement a simple service in the true OOP way. This means for me that the domain objects has no technical or non-business-related methods (in practice no getters/setters).</p>
<p>Here are the domain interfaces to implement:</p>
<pre><code>public interface Person {
void register();
void changeName(String name);
}
public interface Persons {
Person register(String name);
Person findByName(String name);
}
</code></pre>
<p><strong>Solution #1</strong></p>
<pre><code>@AllArgsConstructor
public class RegisteredPerson implements Person {
private Long id;
private String name;
private final PersonRegistry registry;
public RegisteredPerson(String name, PersonRegistry registry) {
this.name = name;
this.registry = registry;
}
public void register() {
if (id != null) {
throw new PersonAlreadyRegisteredException(name);
}
id = registry.register(name);
}
public void changeName(String name) {
this.name = name;
if (id != null) {
registry.changeName(id, name);
}
}
}
@RequiredArgsConstructor
public class RegisteredPersons implements Persons {
private final PersonRegistry registry;
public Person register(String name) {
if (registry.byName(name).isPresent()) {
throw new PersonAlreadyRegisteredException(name);
}
Person person = new RegisteredPerson(name, registry);
person.register();
return person;
}
public Person findByName(String name) {
return registry.byName(name)
.orElseThrow(() -> new PersonNotFoundException(name));
}
}
</code></pre>
<p>I introduced a new non-public interface for a repository:</p>
<pre><code>interface PersonRegistry {
long register(String name);
Optional<Person> byName(String name);
void changeName(long id, String name);
}
class InMemoryPersonRegistry implements PersonRegistry {
private final Map<Long, PersonEntry> personEntries = new HashMap<>();
private final AtomicLong idSequence = new AtomicLong();
public long register(String name) {
long id = idSequence.incrementAndGet();
personEntries.put(id, new PersonEntry(id, name));
return id;
}
public Optional<Person> byName(String name) {
return personEntries.values().stream()
.filter(entry -> name.equals(entry.name))
.findAny()
.map(entry -> new RegisteredPerson(
entry.id, entry.username, this
));
}
public void changeName(long id, String name) {
if (personEntries.containsKey(id)) {
personEntries.get(id).name = name;
}
}
@AllArgsConstructor
@EqualsAndHashCode(of = "id")
private class PersonEntry {
public long id;
public String name;
}
}
</code></pre>
<p>What I don't like about this solution it the coupling between <code>InMemoryPersonRegistry</code> and <code>RegisteredPerson</code>. For example, In a situation when the <code>RegisteredPerson</code> has more dependencies, all of them must be known to the <code>InMemoryPersonRegistry</code>. Possible solution for this would be to introduce a factory and make the repository (registry) dependent only on that factory. But the coupling still doesn't feel alright.</p>
<p>The repository is hard to test as well, because the returned object has no getters to prove correctness of the persistence.</p>
<p><strong>Solution #2</strong></p>
<p>In this version I implemented the registry as a dumb DAO with no business meaning, only as a tool to persistent entries. This breaks the coupling and makes the repository implementation independent of the other world. </p>
<pre><code>interface PersonEntries {
long save(PersonEntry entry);
Optional<PersonEntry> byName(String name);
void updateName(long id, String name);
@RequiredArgsConstructor
class PersonEntry {
public final Long id;
public final String name;
}
}
</code></pre>
<p>On the other hand it's much more boiler-plate code on the client side:</p>
<pre><code>public class RegisteredPerson implements Person {
private final PersonEntries entries;
/* ... */
public void register() {
if (id != null) {
throw new PersonAlreadyRegisteredException(name);
}
id = entries.save(new PersonEntries.PersonEntry(null, name));
}
public void changeName(String name) {
this.name = name;
if (id != null) {
entries.updateName(id, name);
}
}
}
public class RegisteredPersons implements Persons {
private final PersonEntries entries;
/* ... */
public Person findByName(String name) {
return entries.byName(name)
.map(entry -> new RegisteredPerson(entry.id, entry.name, entries))
.orElseThrow(() -> new PersonNotFoundException(name));
}
}
</code></pre>
<p>When a Person structure changes, a lot of places in code must be modified.</p>
<p>Question is whether it makes sense to have the method <code>updateName</code> in the <code>PersonEntries</code> or would it be better to update everyting via <code>save</code> method.</p>
<p>Another point is the return value of the <code>save</code>, would it be better to update the entry and have <code>void</code> instead:</p>
<pre><code>// RegisteredPerson.register():
PersonEntries.PersonEntry entry = new PersonEntries.PersonEntry(null, name);
entries.save(entry);
this.id = entry.id;
</code></pre>
<p>Any thoughts and ideas are appreciated! Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T08:00:13.907",
"Id": "450683",
"Score": "2",
"body": "Welcome to Code Review! I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code 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)*."
}
] |
[
{
"body": "<p>I find it a bit conflicting that the <code>register()</code> method has been put in the <code>Person</code> interface. Should the Person be responsible for registering itself at all? It also creates a bit of a confusion in the <code>RegisteredPerson</code> class, whose name implies that it is registered when it is in fact unregistered until it's register() method is called successfully.</p>\n\n<p>In true OO fashion, if RegisteredPerson is a public class, it should not be possible to be instantiate it unless it is actually registered in the registry. In my opinion, if you want to differentiate <code>UnregisteredPerson</code> and RegisteredPerson in the class hierarchy, they should have their own interfaces and the implementation should be made in a way that the instantiation (and existence) of concrete RegisteredPerson objects is completely hidden inside the registry.</p>\n\n<p>Something along these lines:</p>\n\n<pre><code>interface PersonRegistry {\n RegisteredPerson findByName(String name);\n RegisteredPerson register(UnregisteredPerson person);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:36:37.710",
"Id": "450671",
"Score": "1",
"body": "I guess in OOP should only the object know how to persist itself, otherwise we need getters and have an anemic bag of data. But that's a really good point regarding the name. As the Person is not registered until `register` was called and it's not registered after `unregister` was potentially called, the name is definitely not correct. Maybe a `RegistrablePerson` would make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:45:59.557",
"Id": "450672",
"Score": "1",
"body": "How would the `UnregisteredPerson` need look like to make it work? What if the object creates some internals like a username based on the name and so far, those attributes should be encapsulated and not the part of its API, which makes it impossible for the registry to persist the Person in this way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:48:52.177",
"Id": "450673",
"Score": "0",
"body": "Username would not be part of the UnregisteredPerson, as unregistered people do not have usernames. I would make it a part of a \"RegistrationRequest\" object, which would contain the UnregisteredPerson instance and whatever data is needed to turn it into a RegisteredPerson (e.g. requested username)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:51:57.377",
"Id": "450674",
"Score": "0",
"body": "Having the unregistered and registered person represented by the same interface requires you to have accessors for their registration status, which may or may not be considered anemic, and requires you to check the status if you have operations that only apply to either type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:59:37.183",
"Id": "450676",
"Score": "0",
"body": "One approach could be UnregisteredPerson to have a register() method that performs the registration, returns a RegisteredPerson and invalidates itself so that it can not be used anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T07:22:43.153",
"Id": "450679",
"Score": "0",
"body": "**1.** Maybe the username is not a good example, but let's image that the object parses the name into a firstName, lastName and initials or something like that. If it was a User a password hash could be generated based on only-Person-knowhow algorithm, a salt could be generated etc. **2.** I guess `RegistrationRequest` doesn't solve the problem because it could be again instantiate only from the Person within as only this knows its internals. **3.** I think this might be a good OOP approach! Unfortunately seems already too complex for me. **4.** Thanks for your great thougts! :-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T06:24:16.997",
"Id": "231173",
"ParentId": "231171",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T05:41:34.463",
"Id": "231171",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"ddd"
],
"Title": "OOP at the boundary"
}
|
231171
|
<p>I'm writing a code to read data from text file in Rust. The target files have two columns and non-fixed length rows, for example,</p>
<p>example.txt</p>
<pre><code>1 1
2 4
3 9
4 16
</code></pre>
<p>To achieve this, I wrote following code.</p>
<pre class="lang-rust prettyprint-override"><code>use std::fs::read_to_string;
pub fn open_file(filename: &str) -> (Vec<f32>, Vec<f32>){
let data = read_to_string(filename);
let xy = match data {
Ok(content) => content,
Err(error) => {panic!("Could not open or find file: {}", error);}
};
let xy_pairs: Vec<&str> = xy.trim().split("\n").collect();
let mut x: Vec<f32> = Vec::new();
let mut y: Vec<f32> = Vec::new();
for pair in xy_pairs {
let p: Vec<&str> = pair.trim().split(" ").collect();
x.push(p[0].parse().unwrap());
y.push(p[1].parse().unwrap());
}
(x, y)
}
</code></pre>
<p>I'm a beginner of Rust, so I don't know that I follow the best practice in Rust and this is the most efficient code.</p>
<p>I want some advice about this function.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T17:33:33.943",
"Id": "450797",
"Score": "0",
"body": "You should copy your already working code here and then don't modify it manually. That's a general rule. You didn't follow it because your code cannot compile as-is with the unknown `f33` type in line 3. Since fixing this typo doesn't invalidate any existing answer you may still do that."
}
] |
[
{
"body": "<p>I honestly think you should be breaking up the treatment of the file into two parts, as you are already (implicitly) doing so in your function. One part to read the file into a line iterator, another to actually parse.</p>\n\n<p>The \"reading into an iterator\" is a simple combination of <code>std::fs::File::read_line</code>; I'll instead focus on the other part:</p>\n\n<pre><code>pub fn read_xy_pairs(i: impl Iterator<Item = String>) -> (Vec<f32>, Vec<f32>) {\n i\n .map(|string| -> Vec<f32> {\n string.split(\" \")\n .take(2)\n .map(|element| element.parse::<f32>())\n .filter(|element| element.is_ok())\n .map(|element| element.unwrap())\n .collect()\n })\n .filter(|item| item.len() == 2)\n .map(|mut item| (item.swap_remove(0), item.swap_remove(0)))\n .unzip()\n}\n</code></pre>\n\n<p>The processing is clearly laid out, in order:</p>\n\n<ol>\n<li>I convert each element of the iterator, in turn, into an iterator of <code>&str</code> via <code>String::split()</code></li>\n<li>I then truncate this iterator to only take the first two elements lazily</li>\n<li>Each element of this iterator gets <code>parsed()</code> and I filter any element that isn't okay, unwrapping those that are</li>\n<li>This iterator gets collected into a <code>Vec<f32></code></li>\n<li>From there, I filter out any element that does not have <strong>exactly</strong> 2 components, and convert those that do into a tuple2 of (f32, f32)</li>\n<li>I then <code>unzip</code> this iterator of <code>(f32, f32)</code> into a <code>(Vec<f32>, Vec<f32>)</code> to fit your type signature</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T14:28:58.547",
"Id": "450754",
"Score": "0",
"body": "Thank you for your polite answer, but I have some questions. i) you use `map` twice (one with arrow operator (?) and another without), what is the difference? ii) I cannot understand the behavior of `swap_remove` enough. Could you teach me more or give me some references?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T14:40:09.940",
"Id": "450950",
"Score": "0",
"body": "Hey @Y.P, and sorry about the delay. In order, 1) is not an arrow operator but a type definition. I am specifically telling the compiler the `map` closure will output a `Vec<_>` in order to not have to store it as an intermediate variable for `collect()` to be able to infer the return type. ii) `swap_remove()` removes the element at position N and returns it. As I am removing items, I need to make sure I remove the first one twice (as the second element will have shifted to position 1 after the first removal). Let me know if you have any other questions!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T08:14:22.250",
"Id": "451025",
"Score": "0",
"body": "Thank you. I understood."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T11:17:25.340",
"Id": "231189",
"ParentId": "231184",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231189",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T09:43:00.927",
"Id": "231184",
"Score": "6",
"Tags": [
"beginner",
"csv",
"rust"
],
"Title": "Rust code that reads two columns of data from .txt file"
}
|
231184
|
<p>I wrote a code to calculate the lengths of strongly connected components in a graph. The results I get are correct but it scales horribly. </p>
<p>This is the code I have. I understand that the runtime complexity of a graph traversals should be <code>O(V+E)</code> and as far as I understand, I am not visiting any node twice. And yet it takes forever for bigger graphs (875714 nodes and 5105043 edges)</p>
<pre><code>class Graph:
def __init__(self):
self.graph = {}
self.rev_graph = {}
self.num_vertices = 0
def addEdge(self, tail, head):
if tail in self.graph:
self.graph[tail].append(head)
else:
self.graph[tail]=[head]
if head in self.rev_graph:
self.rev_graph[head].append(tail)
else:
self.rev_graph[head] = [tail]
def dfs(self, visited, start_node, stack):
visited[start_node] = True
if start_node in self.graph:
for i in self.graph[start_node]:
if not visited[i]:
self.dfs(visited, i, stack)
# del self.rev_graph[start_node]
stack.append(start_node)
def dfs_counter(self, visited, start_node, delim=' '):
l1 = sum(visited)
visited[start_node] = True
if start_node in self.rev_graph:
# print(delim, 'rev graph neighbors: ', start_node, self.rev_graph[start_node])
for i in self.rev_graph[start_node]:
if not visited[i]:
self.dfs_counter(visited, i, 2*delim)
l2 = sum(visited)
return l2 - l1
# print(stack)
def find_scc_lens(self):
self.num_vertices = len(set(list(self.graph.keys()) + list(self.rev_graph.keys())))
visited = [False]*self.num_vertices
stack = []
self.dfs(visited, 0, stack)
# stack = stack[::-1]
# print(stack)
# del(self.graph)
visited = [False] * self.num_vertices
scc_lengths = []
for k,i in enumerate(stack[::-1]):
if not visited[i]:
# print("rev graph node count", k, i)
scc_lengths.append(self.dfs_counter(visited, i))
return scc_lengths
</code></pre>
<p>This exercise is from an online course I am taking. I tried a few other solutions online I found elsewhere and they are really fast compared to my runtimes. </p>
<p>What parts of the code can I optimize to improve the runtimes?</p>
<hr>
<p>Example:</p>
<pre><code>g = Graph()
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(3, 4);
g.find_scc_lens()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T11:12:48.267",
"Id": "450698",
"Score": "2",
"body": "Graph traversal is an NP class of problem. That ALL algorithms we are aware off scale horribly. While I can't claim to be intimately familiar with graph traversal, I also don't see any glaring issues. How big, exactly, is the size of the Graphs when you get MemoryErrors? Does \"really big\" mean 1000 nodes or 1000000 nodes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T11:14:04.437",
"Id": "450699",
"Score": "1",
"body": "Also, welcome to Code Review. Please read the [tour] if you haven't, or [ask] if you want to know more about what questions exactly we want. Note that if it turns out you're looking for mathematical help, this question may be migrated towards a more suitable site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:54:11.093",
"Id": "450745",
"Score": "2",
"body": "I understand there might be a need for a little bit more information but I really don't think this post should be closed, the code is there, works to OPs knowledge and the title is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:10:26.960",
"Id": "450778",
"Score": "0",
"body": "@Gloweye, graph traversal is indeed in NP, but it's also in P, and OP is correct to say that it's in \\$O(V + E)\\$ (although this particular implementation isn't)."
}
] |
[
{
"body": "<blockquote>\n<pre><code>class Graph:\n def __init__(self):\n self.graph = {}\n self.rev_graph = {}\n self.num_vertices = 0\n</code></pre>\n</blockquote>\n\n<p>This looks reasonable. Note that the PEP8 style guide wants you to add a blank line after each method.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def addEdge(self, tail, head):\n if tail in self.graph:\n self.graph[tail].append(head)\n else:\n self.graph[tail]=[head]\n if head in self.rev_graph:\n self.rev_graph[head].append(tail)\n else:\n self.rev_graph[head] = [tail]\n</code></pre>\n</blockquote>\n\n<p>The failure to update <code>self.num_vertices</code> here does not look reasonable. I suspect that the reason is that <code>num_vertices</code> shouldn't be a property of the class.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def dfs(self, visited, start_node, stack):\n visited[start_node] = True\n if start_node in self.graph:\n for i in self.graph[start_node]:\n if not visited[i]:\n self.dfs(visited, i, stack)\n # del self.rev_graph[start_node]\n stack.append(start_node)\n</code></pre>\n</blockquote>\n\n<p>In future, please remove commented code before submitting the code for review.</p>\n\n<p>I could use a comment to explain the purpose of <code>stack</code>, and why it adds in post-order rather than pre-order.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def dfs_counter(self, visited, start_node, delim=' '):\n l1 = sum(visited)\n visited[start_node] = True\n if start_node in self.rev_graph:\n # print(delim, 'rev graph neighbors: ', start_node, self.rev_graph[start_node])\n for i in self.rev_graph[start_node]:\n if not visited[i]:\n self.dfs_counter(visited, i, 2*delim)\n l2 = sum(visited)\n return l2 - l1\n # print(stack)\n</code></pre>\n</blockquote>\n\n<p><code>sum(visited)</code> is expensive: too expensive to use in this method, which is called inside a loop. If you refactor to track the sum directly then I expect you'll see a notable speedup.</p>\n\n<p><code>2*delim</code> probably isn't really desirable: it should probably be <code>delim + ' '</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def find_scc_lens(self):\n self.num_vertices = len(set(list(self.graph.keys()) + list(self.rev_graph.keys())))\n</code></pre>\n</blockquote>\n\n<p>It should be possible to do this without using <code>list</code>.</p>\n\n<blockquote>\n<pre><code> visited = [False]*self.num_vertices\n</code></pre>\n</blockquote>\n\n<p>This is buggy. <code>num_vertices</code> is the number of vertices, <em>not</em> the largest vertex. Consider the graph</p>\n\n<pre><code>g = Graph()\ng.addEdge(2, 3)\ng.addEdge(3, 2)\n</code></pre>\n\n<p>The output should be either <code>[2]</code> (vertices with no edges don't exist) or some permutation of <code>[1, 1, 2]</code> (with vertices <code>0</code> to <code>3</code>).</p>\n\n<blockquote>\n<pre><code> stack = []\n self.dfs(visited, 0, stack)\n # stack = stack[::-1]\n # print(stack)\n # del(self.graph)\n</code></pre>\n</blockquote>\n\n<p>This is also buggy. What about vertices which aren't reachable from <code>0</code>? Even if you add documentation saying that this method only works for connected graphs, that doesn't rule out</p>\n\n<pre><code>g = Graph()\ng.addEdge(1, 2)\ng.addEdge(2, 1)\ng.addEdge(1, 0)\n</code></pre>\n\n<blockquote>\n<pre><code> visited = [False] * self.num_vertices\n scc_lengths = []\n for k,i in enumerate(stack[::-1]):\n if not visited[i]:\n # print(\"rev graph node count\", k, i)\n scc_lengths.append(self.dfs_counter(visited, i))\n return scc_lengths\n</code></pre>\n</blockquote>\n\n<p>In order to validate the correctness of this implementation, it would be immensely useful to have a comment which says which algorithm it implements (and ideally links to reference material).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:29:42.253",
"Id": "450786",
"Score": "0",
"body": "Thanks for the nice detailed comments, Peter. I didn't realize the `sum` could be a potential issue. That was sort of a revelation. I went through a couple of videos online after this post and realized the implementation is indeed buggy and works only for a few cases which I was using as examples. I am not sure if we are supposed to keep up the posts that are coming out of incorrect understanding. I threw away this code and rewrote it which resolves all the current issues. I was going through meta posts and meanwhile, you answered. It's a pickle for me now. I...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:32:41.300",
"Id": "450788",
"Score": "0",
"body": "If the sequence of operations had been different, you could have deleted your question temporarily, edited it with the fixed code, and undeleted it. But once you have an answer, that option is removed. What you can do now is to post a new question with the new code and link back to this one for context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:38:51.053",
"Id": "450790",
"Score": "0",
"body": "Okay. But my new question wouldn't have any issues (as far as I know). I have fixed the code since I put up the post. Is it okay to put up posts with no real issues? And wouldn't I be downvoted a lot?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T22:58:05.337",
"Id": "450840",
"Score": "0",
"body": "If you think the new version is fine, you don't have to ask for it to be reviewed, but the option is there if you want it. There's a sense in which the better the code, the more advanced the review can be, so you might still learn something. See https://codereview.stackexchange.com/search?q=Iterative+review for reassurance about downvotes."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:09:17.007",
"Id": "231212",
"ParentId": "231186",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:32:58.777",
"Id": "231186",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"graph",
"depth-first-search"
],
"Title": "Find the lengths of strongly connected components in a graph"
}
|
231186
|
<p>As part of my training, I implemented a n-body class in C++ to simulate gravitational interaction of bodies and to get more familiar with features that C++ offers such as object oriented programming.</p>
<p>This implementation uses a direct integration (Verlet integration) of the differential equations which results in a time complexity of <span class="math-container">\$\mathcal{O}(n^2)\$</span>, where <span class="math-container">\$n\$</span> is the number of particles.</p>
<p>Please be as hard as possible with this implementation and give me constructive feedback. </p>
<p>I would appreciate advice especially in the following areas:</p>
<ol>
<li>Code style (readability, naming conventions) </li>
<li>Class design </li>
<li>Efficieny (how to avoid unnecessary complexity) </li>
<li>Reinventing the wheel (does the STL offer functionality I should use in my code?)</li>
<li>Memory usage</li>
</ol>
<p><strong>main.cpp</strong></p>
<pre><code>#include "nbody.h"
int main(int argc, char* argv[]) {
Nbody nbody(16, 0.001, 1);
nbody.timeIntegration();
return 0;
}
</code></pre>
<p><strong>nbody.h</strong></p>
<pre><code>#ifndef NBODY_H
#define NBODY_H
// Parameters
const int DIM = 2; // dimensions
const double EPS = 1e-4; // smoothing parameter
// Function prototypes
inline double sqr(double);
struct Particle{
double m; // mass
double x[DIM]; // position
double v[DIM]; // velocity
double F[DIM]; // force
double F_old[DIM]; // force past time step
};
// Nbody class
class Nbody {
private:
int step = 0;
double t = 0;
const int n; // number of particles
const double dt; // step size
const double t_max; // max simulation time
Particle *p = new Particle[n]; // allocate memory
void init_data();
public:
~Nbody();
Nbody(int n_, double dt_, double t_max_);
inline void print_parameter() const;
inline void print_data() const;
inline void write_data(int step) const;
void timeIntegration();
void comp_force();
void force(Particle*, Particle*);
void comp_position();
void comp_velocity();
void update_position(Particle*);
void update_velocity(Particle*);
};
#endif
</code></pre>
<p><strong>nbody.cpp</strong></p>
<pre><code>#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include "nbody.h"
// Class methods
Nbody::Nbody(int n_, double dt_, double t_max_) : n(n_), dt(dt_), t_max(t_max_) {
init_data();
}
Nbody::~Nbody() {
delete[] p;
p = 0;
}
void Nbody::timeIntegration() {
comp_force();
for(; t<t_max; t+=dt, step+=1) {
comp_position();
comp_force();
comp_velocity();
if (step % 10 == 0) {
write_data(step);
//print_data();
}
}
}
void Nbody::update_velocity(Particle *p) {
double a = dt * 0.5 / p->m;
for (int d=0; d<DIM; d++) {
p->v[d] += a * (p->F[d] + p->F_old[d]);
}
}
void Nbody::update_position(Particle *p) {
double a = dt * 0.5 / p->m;
for (int d=0; d<DIM; d++) {
p->x[d] += dt * (p->v[d] + a * p->F[d]);
p->F_old[d] = p->F[d];
}
}
void Nbody::comp_velocity() {
for (int i=0; i<n; i++) {
update_velocity(&p[i]);
}
}
void Nbody::comp_position() {
for (int i=0; i<n; i++) {
update_position(&p[i]);
}
}
void Nbody::comp_force() {
for (int i=0; i<n; i++) {
for (int d=0; d<DIM; d++) {
p[i].F[d] = 0;
}
}
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
force(&p[i], &p[j]);
}
}
}
void Nbody::force(Particle *i, Particle *j) {
double r=EPS; // smoothing
for (int d=0; d<DIM; d++) {
r += sqr(j->x[d] - i->x[d]);
}
double f = i->m * j->m / (sqrt(r) * r);
for (int d=0; d<DIM; d++) {
i->F[d] += f * (j->x[d] - i->x[d]);
j->F[d] -= f * (j->x[d] - i->x[d]);
}
}
void Nbody::write_data(int step) const {
std::ofstream results;
std::string file_name = "data_" + std::to_string(step) + ".log";
results.open(file_name);
if (results.fail()) { // or (!results) ?
std::cerr << "Error\n" << std::endl;
} else {
for (int i=0; i<n; i++) {
results << t << " ";
results << p[i].m << " ";
for (int d=0; d<DIM; d++) {
results << p[i].x[d] << " ";
}
for (int d=0; d<DIM; d++) {
results << p[i].v[d] << " ";
}
for (int d=0; d<DIM; d++) {
results << p[i].F[d] << " ";
}
results << std::endl;
}
results.close();
}
}
void Nbody::print_data() const {
std::cout.setf(std::ios_base::scientific);
std::cout.precision(5);
for (int i=0; i<n; i++) {
std::cout << t << " ";
std::cout << p[i].m << " ";
for (int d=0; d<DIM; d++) {
std::cout << p[i].x[d] << " ";
}
for (int d=0; d<DIM; d++) {
std::cout << p[i].v[d] << " ";
}
for (int d=0; d<DIM; d++) {
std::cout << p[i].F[d] << " ";
}
std::cout << std::endl;
}
}
void Nbody::init_data() {
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> distribution_x(0.0,1.0);
std::uniform_real_distribution<double> distribution_v(-1.0,1.0);
for (int i=0; i<n; i++) {
p[i].m = 1./n;
for (int d=0; d<DIM; d++) {
p[i].x[d] = distribution_x(generator);
p[i].v[d] = distribution_v(generator);
p[i].F[d] = 0.0;
p[i].F_old[d] = 0.0;
}
}
}
inline void Nbody::print_parameter() const {
std::cout << n << " " << dt << " " << t_max << std::endl;
}
// Other Functions
inline double sqr(double x) {
return x*x;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:56:42.037",
"Id": "450746",
"Score": "2",
"body": "@Samuel If you want to provide more information, I think it'd be great to have an explanation of what is the N body simulation. This way, people could understand what your code is supposed to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T14:31:11.367",
"Id": "450756",
"Score": "0",
"body": "Do you have a specific version of C++ you are targeting (C++11, C++14, C++17)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T19:43:03.410",
"Id": "450813",
"Score": "0",
"body": "@pacmaninbw I'm not sure which version to take. What makes sense? Which version should I use when writing a C++ programm?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T21:17:59.170",
"Id": "450830",
"Score": "0",
"body": "You can add the comments, but at this point don't change the code. The version you should probably learn and use at this point is C++17."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T05:54:27.133",
"Id": "450867",
"Score": "5",
"body": "@Samuel after considering our review feedback and possibly incorporating it into your code, you are very welcome to post it in a follow-up question. I am interested in how this piece of code develops further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:44:37.680",
"Id": "451096",
"Score": "0",
"body": "Just curious, based on what I see everything is in a single plane (I see x and y axis's but not the z axis). Is there a reason for this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T17:29:48.687",
"Id": "451101",
"Score": "0",
"body": "@pacmaninbw For `DIM=3` the simulation is three dimensional."
}
] |
[
{
"body": "<p>Your code is written in a hybrid C/C++ style. For instance your destructor has a <code>delete</code> (I can't find where the corresponding <code>new</code> is) and that is basically never needed. Use a <code>std::vector</code> to store array-like data.</p>\n\n<p>Also you do a lot of parameter passing like <code>void Nbody::update_position(Particle *p)</code>. Use references instead, and use <code>const Particle &p</code> if the particle is only read.</p>\n\n<p>Otherwise it looks like an n-body code to me. It's quadratic rather than something more sophisticated/efficient, but that's probably ok.</p>\n\n<p>Oh, I've found the <code>new</code>: you have\n<code>Particle *p = new Particle[n];</code> \nin the class definition, but <code>n</code> is uninitialized. That is probably undefined behavior, definitely extremely dangerous, and most likely completely wrong.</p>\n\n<p>Don't use <code>new</code> to allocate an array! Use <code>std::vector</code>, as follows:</p>\n\n<pre><code>std::vector<Particle> the_particles;\npublic:\n Particles(int n) : the_particles(vector<Particle>(n)) {}\n}```\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T20:13:58.817",
"Id": "450821",
"Score": "0",
"body": "Indeed. As part of writing my answer, I refactored the code to use a `std::vector<Particle>`, and it felt much nicer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T21:47:12.447",
"Id": "450835",
"Score": "0",
"body": "I use `new` in the class definition. Did I use it the wrong way? What exactly is wrong with parameter passing? Don't I change the particle when I update it's velocity or position? Wouldn't it be wrong the use a constant reference then? Can you be more specific how `comp_velocity()` and `update_velocity()` would look like then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T07:28:02.780",
"Id": "451021",
"Score": "0",
"body": "Can you please explain your code in more detail? I am not very familiar with the STL. Do I define `std::vector<Particle> the_particles` as `private`? What exactly is `ParticleS`? Where is it defined? How do I use it in the rest of my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T07:33:09.750",
"Id": "451022",
"Score": "0",
"body": "My compiler throws an error: `error: expected unqualified-id before ‘int’\n Particle(int n) : p(vector<Particle>(n)) {};`. Do you see what I am doing wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T15:48:18.407",
"Id": "451088",
"Score": "0",
"body": "1. This uses C++17 idioms. Make sure to use the appropriate compiler flag!\n2. Yes, make the vector private.\n3. I used my own naming. It takes too much scrolling to find everything in your code. I'm sure you know what I mean."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:47:12.707",
"Id": "231211",
"ParentId": "231191",
"Score": "10"
}
},
{
"body": "<h2>The Great!</h2>\n<p>You're not making the basic beginner error of using <code>using namespace std;</code>! The <code>main()</code> function is only 3 lines of code.</p>\n<p>The function declarations in the <code>nbody</code> class that don't change things include <code>const</code> which will help optimization later.</p>\n<p>The code utilizes the C++ random number generation rather than the C <code>srand()</code> and <code>rand()</code> functions.</p>\n<p>Because Nbody was implemented as a class it is very easy to change <code>main()</code> so that it can accept user input for the values of <code>n</code>, <code>dt</code> and <code>t_max</code>.</p>\n<h2>Missing Header</h2>\n<p>The <code>#include <string></code> is missing from <code>nbody.cpp</code>; this is necessary when compiling the code in most cases.</p>\n<h2>The Obsolete</h2>\n<p>The use of <code>inline</code> function declarations is <a href=\"https://en.cppreference.com/w/cpp/language/inline\" rel=\"noreferrer\">now only a suggestion to the compiler</a>. Optimizing compilers can and will do a better job of optimizing by inlining code based.</p>\n<p>The body of the <code>Nbody</code> constructor uses an obsolete form of initialization, rather than using <code>()</code> as in the following code</p>\n<pre><code>Nbody::Nbody(int n_, double dt_, double t_max_) : n(n_), dt(dt_), t_max(t_max_) {\n init_data();\n}\n</code></pre>\n<p>use braces <code>{}</code>:</p>\n<pre><code>Nbody::Nbody(int n_, double dt_, double t_max_)\n: n{n_}, dt{dt_}, t_max{t_max_}\n{\n init_data();\n}\n</code></pre>\n<p>Putting the initialization on a separate line makes it easier to find.</p>\n<h2>Prefer STL Container Classes</h2>\n<p>Prefer STL container classes such as <code>std::vector</code> or <code>std::array</code> over old C style arrays. The <code>std::array<type, size></code> class is a fixed size array. The <code>std::vector<type></code> is a variable sized array. STL container classes provide iterators so that pointers aren't necessary. The use of <code>std::vector<Particle> p;</code> might reduce the number of parameters to the constructor. It would definitely remove the need for the variable <code>n</code> within the <code>Nbody</code> class since <code>p.size()</code> would always contain the number of particles after <code>Nbody::init_data()</code> has run. Also after <code>Nbody::init_data()</code> has run iterators could be used to access the particles in <code>p</code> and would allow the code to use a ranged for loop such as</p>\n<pre><code>void Nbody::write_data(int step) const {\n std::ofstream results;\n std::string file_name = "data_" + std::to_string(step) + ".log";\n results.open(file_name);\n if (results.fail()) { // or (!results) ?\n std::cerr << "Error\\n" << std::endl;\n } else {\n for (auto particle : p) {\n results << t << " ";\n results << particle.m << " ";\n for (int d=0; d<DIM; d++) {\n results << particle.x[d] << " ";\n }\n for (int d=0; d<DIM; d++) {\n results << particle.v[d] << " ";\n }\n for (int d=0; d<DIM; d++) {\n results << particle.F[d] << " ";\n }\n results << std::endl;\n }\n results.close();\n }\n}\n</code></pre>\n<p>Another benefit of making <code>p</code> an STL container class is that the destructor for the class <code>Nbody</code> can then be a default constructor and the array of particles doesn't need to be allocated in the class declaration.</p>\n<h2>Variable Names</h2>\n<p>It's not really clear by just reading the code what the variables <code>n_</code>, <code>n</code>, <code>dt_</code>, <code>dt</code>, <code>t_max_</code>, <code>t_max</code>, <code>x</code>, <code>F</code> and <code>v</code> and <code>p</code> are. For instance, I assume <code>dt</code> means Delta Time, but it is not clear that this is true. The array <code>p</code> might be renamed <code>particles</code>, if I'm correct about <code>dt</code> than deltaTime might be more appropriate.</p>\n<p>Yes there are comments for some of the variable names, but if I had to maintain the code I'd rather work with code that was self-documenting than depending on comments.</p>\n<p>Example</p>\n<pre><code>void Nbody::write_data(int step) const {\n std::ofstream results;\n std::string file_name = "data_" + std::to_string(step) + ".log";\n results.open(file_name);\n if (results.fail()) { // or (!results) ?\n std::cerr << "Error\\n" << std::endl;\n } else {\n for (auto particle : particles) {\n results << t << " ";\n results << particle.mass << " ";\n for (int d=0; d<DIM; d++) {\n results << particle.position[d] << " ";\n }\n for (int d=0; d<DIM; d++) {\n results << particle.velocity[d] << " ";\n }\n for (int d=0; d<DIM; d++) {\n results << particle.Force[d] << " ";\n }\n results << std::endl;\n }\n results.close();\n }\n}\n</code></pre>\n<h2>Style</h2>\n<p>Some, not all, developers prefer to see the public declarations of a class before the private declarations of a class. This is because it becomes easier to find the public interface of the class.</p>\n<p>The function <code>void init_data()</code> is not necessary unless you are planning to have multiple constructors, it might be better to move that code into the constructor.</p>\n<p>If the functions <code>print_parameter()</code> and <code>print_data()</code> are debug functions it might be better to put them within <code>#ifdef DEBUG</code> and <code>#endif</code>.</p>\n<p>In the current implementation <code>return 0;</code> from <code>main()</code> is not necessary. If error handling code is added and there is a <code>return 1;</code> it might be better to keep it. It might also be better to use <code>return EXIT_SUCCESS;</code> and <code>EXIT_FAILURE</code> which are defined in <code>cstdlib</code> (<code>#include <cstdlib></code>).</p>\n<h2>Suggestions</h2>\n<p>It might be better to allow the user to name the output file that the results go into, either by input through a user interface or as part of the command line arguments. The name could default to the current file name in case the user doesn't specify one.</p>\n<p>It might also be better to have only one output file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T21:41:55.767",
"Id": "450834",
"Score": "27",
"body": "The variable names are very self descriptive for this kind of domain in my opinion. I think it is also safe to assume that a maintainer of a n-body interaction program has a physics background."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:00:36.713",
"Id": "450888",
"Score": "5",
"body": "You never know whos gonna maintain your code next. Might be a person with a totally different background. The cost for the naming the variables properly is neglible, but the potential benefit large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:15:17.087",
"Id": "450905",
"Score": "8",
"body": "@Hakaishin the cost is that anyone with the domain knowledge to maintain the code has to translate from the common notation of the domain, $dt$, each time they read the code. IMO this makes it less maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:51:46.190",
"Id": "450915",
"Score": "1",
"body": "But you know what is the common notation of all domains? Language. Everybody understands velocity and I doubt that your thinking will be slower because you read a word which you understand instead of v. I might be touchy, because I had a project from an electrical engineer with many such short notation variables and I tool me a while to understand the code. As said my point above stands. But lets agree to disagree"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:44:31.827",
"Id": "450975",
"Score": "10",
"body": "@Hakaishin The physics equations use mathematical symbols (variables) and not their names and sentences for a reason. To make everything more readable. By using long names the code that implements mathematical equations (e.g. numerical methods) becomes *harder* to parse."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T19:30:36.467",
"Id": "450989",
"Score": "3",
"body": "I've seen a lot of code with terse, mathematical-seeming variable names that were totally made-up (or came from one obscure paper), and _those_ codebases are terrible. But `d` for change, and `t` for time, `m` for mass, `F` for force, etc., are really such basic, well-known notation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T07:03:45.103",
"Id": "451019",
"Score": "2",
"body": "I never really worked with containers before. Do I use `std::array` or `std::vector` in my case? Could you roughly sketch out how I'd have to adjust my code. Does moving `init_data()` into the constructor mean, that I define `init_data()` outside the class? Do I define `DEBUG` like `#define DEBUG TRUE`? Or how do I decide between debug and non-debug mode?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:37:48.697",
"Id": "451056",
"Score": "1",
"body": "Because this is an N body simulation I would use `std::vector` because the size can change. Remove the variable `n` declaration from the `Nbody` class, in the constructor `n` will be still be input but it will only be used once as the number of times to create particles. SRP is mentioned in another answer, `Particle` should probably be promoted to a class and the constructor for that class should fill in the data fields for each particle, in that case the constructor for `Nbody` would just loop n times to create particles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:39:00.087",
"Id": "451057",
"Score": "1",
"body": "You can do the #define DEBUG TRUE, but a better way is to use the `-D` flag in the compiler command line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T15:22:40.703",
"Id": "451081",
"Score": "0",
"body": "@Samuel did you get my answers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T15:25:50.403",
"Id": "451082",
"Score": "1",
"body": "@pacmaninbw Yes, I'm still processing all that information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:06:06.830",
"Id": "451109",
"Score": "0",
"body": "Why the suggestion to use braces when parenthesis worked fine? I wouldn't call it obsolete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:14:15.647",
"Id": "451120",
"Score": "1",
"body": "Does it make more sense to use `for (const auto particle : particles)` instead of `for (auto particle : particles)` in this case? What about `for (const auto& particle : particles)`? Wouldn't that be the most efficient one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:22:39.570",
"Id": "451182",
"Score": "2",
"body": "Taken to the extreme, the variable names should be `velocity_component_in_meters_per_second`, but that would make me shudder. But re the claim that any later maintainer would have a physics background - it could just as well be someone who only wants to prettify output routines ... --- Oops! I just noted that `velocity_component_in_meters_per_second` would even be wrong as the code uses a gravitational constant of `1`; see, even I with physics background might have guessed a few things wrong during maintenance ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T13:33:52.760",
"Id": "451261",
"Score": "0",
"body": "@Samuel Your last question about efficiency would be answered in a code review of the new code once it is written, or you can get the answer on stack overflow. Many of us would like to see a second version of the code to continue helping you to improve your code. The new question should link to this question."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:33:16.257",
"Id": "231216",
"ParentId": "231191",
"Score": "30"
}
},
{
"body": "<p>In addition to the other answers:</p>\n\n<ul>\n<li>Use unsigned integer type for <code>DIM</code>, <code>Nbody.step</code>, and <code>Nbody.n</code> since none of this can be negative;</li>\n<li>Use <a href=\"https://en.cppreference.com/w/cpp/language/constexpr\" rel=\"noreferrer\"><code>constexpr</code></a><sup>since C++11</sup> instead just <code>const</code> for both <code>DIM</code> and <code>EPS</code>;</li>\n<li>Get rid of the unused <code>argc</code> and <code>argv</code> arguments in <code>main</code>;</li>\n<li>Consider more usage of <code>const</code>. For example <code>f</code> in <code>Nbody::force()</code> can be <code>const</code>, and <code>a</code> in <code>Nbody::update_position</code> can be <code>const</code> and so on.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:27:11.130",
"Id": "451094",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/100289/discussion-on-answer-by-eanmos-simple-n-body-class-in-c)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:36:43.460",
"Id": "231217",
"ParentId": "231191",
"Score": "10"
}
},
{
"body": "<p>In addition to the other answers:</p>\n\n<p>The <code>init_data</code> function does not belong in the <code>Nbody</code> class. Nowhere in the definition of the N-body problem will you find the word \"random\", and using random input data is only connected to your particular situation, therefore this code should be moved into <code>main.cpp</code>.</p>\n\n<p>In the constructor of <code>Nbody</code>, there's no need for the trailing underscore in the parameter names. The following code looks cleaner and is otherwise equivalent to your current code:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>Nbody::Nbody(int n, double dt, double t_max)\n: n(n), dt(dt), t_max(t_max) {\n init_data(); // should be removed, as I said above\n}\n</code></pre>\n\n<p>For debugging purposes it would be good to have not only the <code>timeIntegration</code> method, but also a simple <code>step</code> method that only does a single step. This allows you to write better unit tests. It also makes another of the constructor parameters, namely <code>t_max</code> unnecessary.</p>\n\n<p>Still in <code>timeIntegration</code>, instead of <code>step+=1</code> you should write <code>++step</code>. Writing <code>step++</code> would be equivalent, but that would tell every reader that you don't know C++ well. In C++ the <code>++</code> usually comes before the variable, in other languages like Java or C or Go it usually comes after the variable. See <a href=\"https://stackoverflow.com/a/17367081/225757\">this Stack Overflow answer</a> for some more details.</p>\n\n<p>Comparing the code of <code>timeIntegration</code> with <code>update_velocity</code> reveals that you use an inconsistent programming style. You should decide for yourself whether to use camelCase or snake_case identifiers. Then, use that style consistently. Another thing is that you placed spaces around the operators <code>*</code> and <code>/</code>, but not around <code>+</code>. I would have expected it the other way round, since <code>*</code> and <code>/</code> bind the operands more tightly than <code>+</code>. The usual style is to always surround binary operators with spaces. Therefore <code>t < t_max; t += dt; step++</code>.</p>\n\n<p>Your Nbody class does not account for tricky situations where the particles are so close together that <code>dt</code> becomes too large for a realistic simulation. This is something that you must document.</p>\n\n<p>I like it that you separated <code>updated_velocity</code> and <code>update_position</code> into two separate methods. This makes them easy to read. (Plus, it's necessary from an implementation's point of view since you must first update the velocity of all particles before you can update any particle's position, otherwise the result depends on the ordering of the particles.)</p>\n\n<p>The abbreviation <code>comp</code> in <code>comp_position</code> is ambiguous. It could mean compare or compute. You should spell it out.</p>\n\n<p>In <code>Nbody::force</code> you should not name the parameters <code>i</code> and <code>j</code>, since these variable names are reserved for integers, by convention. I'd rather choose p and q. And if you rename <code>Nbody::p</code> to <code>ps</code> since it is plural anyway, there's no naming collision anymore.</p>\n\n<p>In <code>write_data</code> the parameter <code>step</code> is not necessary since <code>Nbody::step</code> is accessible by the same name. You can just remove the parameter.</p>\n\n<p>The method <code>print_parameter</code> should be called <code>print_parameters</code> since it is about <em>all</em> parameters, not just a single one.</p>\n\n<p>At the API level, I would not put <code>dt</code> and <code>t_max</code> in the constructor but rather pass <code>dt</code> as parameter to the <code>step</code> method, and <code>t_max</code> as parameter to the <code>timeIntegration</code> method.</p>\n\n<p>In <code>nbody.h</code> there is the <code>EPS</code> constant, which looks dubious. For a <code>dt</code> of 0.001 it may have an appropriate value of <code>0.0001</code>, but what if I want to simulate using <code>dt = 1.0e-9</code>? I don't think it should be a global constant. Not even the speed of light should be, because there are so many different speeds of light, depending on the exact experiment.</p>\n\n<p>In <code>Nbody::init_data</code> you wrote <code>1.</code> without a trailing 0. Sure, it may save a single key stroke, but in my opinion it's not worth it. Just write the canonical <code>1.0</code>, as you already did in several other places in the same function.</p>\n\n<p>The data you write to the <code>data_*.log</code> files is quite imprecise. The typical <code>double</code> type provides 16 to 17 digits of precision, yet you only write out 6 of them, which is the C++ default. Since 2017, <a href=\"https://stackoverflow.com/a/54370758\">C++ finally supports printing floating point numbers accurately</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:02:41.083",
"Id": "450875",
"Score": "2",
"body": "C and Java both have pre-increment and post-increment just like C++ (I don't know Go, but would be surprised if that differed). It's true to say that we generally prefer pre-increment when the value is to be discarded (though you ignore that where writing the `for` loop's increment expression - why?), and that it may be more efficient for non-inlinable types, but post-increment does have its place in C++, and should be used when it's what's required. Perhaps that paragraph could be re-worded?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:37:09.037",
"Id": "450974",
"Score": "0",
"body": "@TobySpeight Thanks, did that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:51:03.477",
"Id": "451112",
"Score": "0",
"body": "Thank you for this nice review! Is it correct to remove the trailing underscore also in the n-body class? Or is that a bad style? What do you mean by adding `dt` to the `step` method? Where would you put `EPS` then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T06:34:50.287",
"Id": "451150",
"Score": "0",
"body": "Yes, it's ok to remove the underscores everywhere. Regarding the `step` method: I would define `Nbody::step(double dt, double eps)`. This gives full control to the caller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:16:53.567",
"Id": "451363",
"Score": "0",
"body": "You said that `init_data()` does not belong in the `Nbody` class. Can you elaborate on this point a little? How do I initialize the particles then? Does it also make sense to add `init_data()` to the `Particle` struct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T17:38:37.823",
"Id": "451372",
"Score": "0",
"body": "The method `init_data` doesn't belong in the `Nbody` class because the `Nbody` has a single job: provide the physics simulation for arbitrary particles. Having particles with random masses and random locations is not generally useful. A more useful pattern is to provide a method to add a particle to the simulation. As I said, the definition of the N-body problem does not in any way contain the word \"random\", therefore the code shouldn't either."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:29:22.183",
"Id": "231223",
"ParentId": "231191",
"Score": "9"
}
},
{
"body": "<h1>First Of All</h1>\n\n<p>You are doing a great job as a beginner. I have been programming for 10 years and my code for a long time was much, much less readable that what you have written. That said:</p>\n\n<h1>What needs Fixing</h1>\n\n<p>I'm not privy of all of the details of the n-body problem but I have an idea of what it does. I'm not an expert on numerical accuracy so I won't comment on the arithmetic you are performing. Here are a few things that I see from a design perspective.</p>\n\n<h2>This class is effectively Impossible to test</h2>\n\n<p>Between randomizing the input data upon construction and having one method that does the vast majority of the work, it is very difficult to write meaningful automated tests for this class. This is in part because this class does way too much.</p>\n\n<h2>The Public interface does not reflect its usage</h2>\n\n<p>The public interface is much broader than what a client would use. As far as I can tell, the only thing a client would need to do is construct one of these objects and immediately call <code>timeIntegration()</code> upon it, then record the results somehow. More on this later.</p>\n\n<h2>You use Non standard ways to convey standard concepts</h2>\n\n<p>You provide a \"print_data\" and a \"write_data\" method. The dependency on <code><iostream></code> & <code><fstream></code> is needless for this class and will make it very difficult to test in an automated (read: unit test) fashion. You should provide a <code><<</code> operator for the particle class instead and allow the client to decide what to do with the results. </p>\n\n<h2>There's no way to get at the raw data for this class</h2>\n\n<p>Furthermore, since the <code>print_data()</code> and <code>write_data()</code> methods are seemingly the only way get data from this class, the use of this class in anything other than a simple command prompt program is limited. A method to get the internal data in non-printed form would be helpful. </p>\n\n<h2>What to do</h2>\n\n<p>A better design for this class may be a public constructor with the necessary parameters which immediately calls everything necessary to compute the integration, and then a method to get the data that has been processed. Nothing else would be public. This way, it is very difficult for a client to use this class incorrectly. A class with a getter for its only owned data should raise a red flag in an OOP design, so all of this rethinking is really leading to a bigger realization that...</p>\n\n<h1>This shouldn't be a class</h1>\n\n<p>My biggest consideration would be to not have this be a class at all. None of the data that it owns are invariant across the useful public interface. <a href=\"https://en.wikipedia.org/wiki/Class_invariant\" rel=\"noreferrer\">More on invariants in class design here on Wikipedia</a>. There is no reason for the state that has been introduced to be owned by this class across its lifetime and there are plenty of opportunities to use this class in ways that produce completely invalid data. This instead should have an interface that consists of one high, level function.</p>\n\n<p>The public interface to the n-body calculator should take in two or three things: </p>\n\n<ol>\n<li>A settings struct. This will include all necessary pieces to properly run the calculation other than the \"hot\" data. this will be initialized by the client. If the struct data is not valid (i.e. something that will be a denominator of zero), the function should exit with a return code of some sort (or exception if that's allowed in your environment and that's your thing). This should probably be taken by const l-value reference</li>\n<li>A <code>std::vector<Particle></code> by (possibly const l-value) reference, this is the input data to the n-body calculator</li>\n<li>a time step to run for. This could be part of the settings struct, but in my mind it's distinctly different than the other concepts that would be in the settings struct.</li>\n</ol>\n\n<p>This function should guarantee to either modify the <code>std::vector<Particle></code> in place or return a transformed <code>std::vector<Particle></code>. My personal preference is the latter, however depending on which version of C++ you are using, that can be inhibitive to good performance. In essence, all that this function is doing is transforming a list of particle states. It can (and should) use other helper functions to do its work, and these functions would very likely get reused in other parts of a larger particle framework. All functions should be stateless other than the particle set passed in.</p>\n\n<p>The value add from this multi-fold:</p>\n\n<ol>\n<li>It is more obvious how to use this interface correctly. See the principle of least surprise. <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"noreferrer\">Wiki article</a>.</li>\n<li>It is much, much easier to test a set of stateless functions than it is to test a big, entangled class.</li>\n<li>This will allow much higher reuse of basic operations as this code base expands. </li>\n</ol>\n\n<h1>Other Suggestions</h1>\n\n<h2>Names</h2>\n\n<p>I would suggest better names for the <code>Particle</code> struct members. If they are used correctly in a larger program they will likely become ubiquitous as the base data types. There is nothing wrong with typing out mass, position, velocity and force. While it's true that people will probably know what you mean when you talk about position as x, they will definitely know what you mean when you type position. </p>\n\n<h2>Strong Types</h2>\n\n<p>I would use strong types for the particle members. Jonathan Bocarra has some excellent blog articles on it on cppfluent (e.g. <a href=\"https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/\" rel=\"noreferrer\">CppFluent Strong types</a>). They can be treated the same as doubles, with the advantage of making it much more difficult to switch arguments around in function calls, and making the code more expressive. </p>\n\n<h2>Get Rid Of The Globals</h2>\n\n<p>Globals are a bad thing, and should be avoided. Regardless of whether the object-oriented approach is gotten rid of, these should be incorporated into a settings struct of some kind.</p>\n\n<h2>Use the STL more than you are</h2>\n\n<p>A lot of your summing <code>for</code> loops can use <code>std::accumulate()</code>; you should be using <code>std::vector</code>s rather than raw c-style arrays. You should be using range-based <code>for</code> loops where you can't use <code>std::vector</code> or an STL algorithm. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T10:28:55.347",
"Id": "450898",
"Score": "3",
"body": "You totally misunderstand the single responsibility principle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:13:26.820",
"Id": "450931",
"Score": "2",
"body": "You are right! I did. I will edit my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:25:13.910",
"Id": "451121",
"Score": "0",
"body": "Thank you! Great review in my opinion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T03:51:23.950",
"Id": "231241",
"ParentId": "231191",
"Score": "15"
}
},
{
"body": "<p>I can't comment due to being new here, but Roland Illig's assertion that it should be <code>++step</code> and not <code>step++</code> and that it shows that you do not understand C++ is incorrect.</p>\n\n<p>In C++, the position of the <code>++</code> determines the order of how the expression is evaluated. So in <code>++step</code>, the variable is incremented before any action with it is performed, while in <code>step++</code>, the action is performed before the value is incremented. Just having a <code>step++</code> or <code>++step</code> as a single line of code is basically equivalent, but the difference is apparent in an example like so:</p>\n\n<pre><code>int step = 0;\nstd::cout << ++step << std::endl; // would print 1\nstd::cout << step << std::endl; // would print 1\n</code></pre>\n\n<p>while</p>\n\n<pre><code>int step = 0;\nstd::cout << step++ << std::endl; // would print 0\nstd::cout << step << std::endl; // would print 1\n</code></pre>\n\n<p>Just clarifying this, as you should understand the difference as opposed to preferring one over the other for stylistic/reputation reasons!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T06:52:39.477",
"Id": "450874",
"Score": "1",
"body": "I think that Rolan Illig meant that `++i` usually is [faster](https://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c) than `i++`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:03:14.493",
"Id": "450876",
"Score": "1",
"body": "@eanmos, that is possible, but in the link you provided it states that this performance hit is usually only present if the type being incremented is not a primitive type. However in OP's post, `step` is of type `int`, which should be optimized correctly by the compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:11:17.217",
"Id": "450878",
"Score": "1",
"body": "yes, but it is a good habit to write `++i` by default and use post increment only when it is need to be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:12:47.390",
"Id": "450879",
"Score": "1",
"body": "@eanmos fair enough. It was more of the assertion that \"In C++ the ++ comes before the variable, in other languages like Java or C or Go it comes after the variable.\" But yes, the convention would be to use `++i`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T10:31:28.150",
"Id": "450899",
"Score": "0",
"body": "@eanmos Should I always use `++i` instead of `i++` in for-loops? Why is it faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T10:42:35.420",
"Id": "450900",
"Score": "2",
"body": "@Samuel, in short. `i++` must create a copy of the old value, \"return\" it and then increment `i`. In the same time `++i` doesn't have to create a copy and \"return\" it, it increments `i` and just \"return\" it. For build-in types (such as `int`) the compiler probably be able to optimize your code. But `i` can be an instance of a C++ class so `i++` and `++i` making calls to one of the `operator++` function. In that case the compiler probably not be able to optimize and then copying of an object `i` when using `i++` can be really slow. So in general case just use `++i`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T06:46:48.820",
"Id": "231245",
"ParentId": "231191",
"Score": "3"
}
},
{
"body": "<p>I will focus on one thing already addressed by another answer but that I think deserve more attention: the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle.</a></p>\n\n<p>Your <code>NBody</code> class has several functionalities merged into one, which would be advisable to separate. It, as far as I can see:</p>\n\n<ul>\n<li>it represent a group of N particles</li>\n<li>it provides the algorithm to perform the physics simulation</li>\n<li>it provides the facilities to print the results of the simulation</li>\n</ul>\n\n<p>I think there is enough material to separate these into three separate entities, leaving more flexibility for changing in the future.</p>\n\n<p>Also, some of the methods in your <code>NBody</code> class actually act only on the given <code>Particle</code>, so they could be refactored as methods of the <code>Particle</code> struct.</p>\n\n<p>Another suggestion is to take a look at the <a href=\"https://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow noreferrer\">Template Method Pattern</a>, which could be a useful starting point for the simulation framework to provide the right flexibility to change the integration method if it ever becomes necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:08:18.783",
"Id": "450962",
"Score": "0",
"body": "Do you mean by separating that I write different classes? A particle class, a simulation class and a class that prints the results?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:28:20.407",
"Id": "231259",
"ParentId": "231191",
"Score": "3"
}
},
{
"body": "<h1>Use a vector math library</h1>\n\n<p>Find a suitable library that implements coordinate vectors, so you don't have to implement them as arrays of doubles. Ideally your <code>struct Particle</code> should look like:</p>\n\n<pre><code>struct Particle {\n double m; // mass\n vec3 x; // position\n vec3 v; // velocity\n vec3 F; // force\n vec3 F_old; // force past time step\n};\n</code></pre>\n\n<p>And a suitable library will provide functions and operator overloads to make working with these types very easy. You should be able to write something like:</p>\n\n<pre><code>void Nbody::update_position(Particle *p) {\n double a = dt * 0.5 / p->m;\n p->x += dt * (p->v + a * p->F);\n p->F_old = p->F;\n}\n</code></pre>\n\n<p>There are many libraries available. I am partial to GLM myself. For a discussion of possible libraries, see <a href=\"https://stackoverflow.com/questions/1380371/what-are-the-most-widely-used-c-vector-matrix-math-linear-algebra-libraries-a\">https://stackoverflow.com/questions/1380371/what-are-the-most-widely-used-c-vector-matrix-math-linear-algebra-libraries-a</a>.</p>\n\n<h1>Make function manipulating <code>Particle</code>s member functions of <code>Particle</code></h1>\n\n<p>You have a lot of functions that mainly manipulate a particle's state, but they are not part of <code>struct Particle</code> itself. For example, <code>update_position()</code> is something that apart from the timestep <code>dt</code> only manipulates a <code>Particle</code>'s member variables. If you make it a member function of <code>Particle</code>, it becomes a much cleaner looking function:</p>\n\n<pre><code>struct Particle {\n ...\n void update_position(double dt);\n};\n\nvoid Particle::update_position(double dt) {\n double a = dt * 0.5 / m;\n x += dt * (v + a * F);\n F_old = F;\n}\n</code></pre>\n\n<p>And you call it like so:</p>\n\n<pre><code>void Nbody::comp_position() {\n for (auto &p: particles) {\n p.update_position(dt);\n }\n}\n</code></pre>\n\n<p>You can do the same for <code>update_velocity()</code>, and even <code>force()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T07:51:46.137",
"Id": "451023",
"Score": "0",
"body": "I tried to incorporate first the second part of your answer but get the following errors: `nbody.cpp: In member function ‘void Particle::update_position(double)’:\nnbody.cpp:47:33: error: ‘p’ was not declared in this scope\n const double a = dt * 0.5 / p->m;\n ^\nnbody.cpp: In member function ‘void Nbody::comp_position()’:\nnbody.cpp:55:19: error: ‘particles’ was not declared in this scope\n for (auto &p: particles) {\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T15:36:45.527",
"Id": "451085",
"Score": "0",
"body": "Is it recommended to use `for (auto &p: particles)` or is `for (Particle &p: particles)` better? When should I not use `auto`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:14:45.027",
"Id": "451092",
"Score": "0",
"body": "I recommend you use `auto` whenever the type is already clear from the context, or when you don't care about the type. Here, it should be obvious that `p` is a `Particle`, because it's an element of `particles`. Using `auto` in these cases avoids repeating types unnecessarily, and potentially avoids mistakes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:24:23.683",
"Id": "451093",
"Score": "0",
"body": "Can you please outline how you would compute the force with your approach? I have difficulties since I have in the case of the force computation a nested loop and I am not sure how to do that in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T18:28:46.303",
"Id": "451105",
"Score": "1",
"body": "Once you've written `void force(Particle &other)` as a member function of `struct Particle`, change `force(&p[i], &p[j])` to `p[i].force(p[j])` inside the nested loop. Here you should probably keep using `int i` and `int j` as iterator variables, as that's the easiest to ensure each pair is only visited once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:05:41.663",
"Id": "451108",
"Score": "0",
"body": "Am I correct in assuming that I then have to use `void Particle::force(Particle& other)` and inside `force()` I remove all `i->` and replace `j->` by `other->`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:52:41.163",
"Id": "451113",
"Score": "0",
"body": "Yes, that's correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:32:03.690",
"Id": "451122",
"Score": "0",
"body": "Can I also use `std::array<double, DIM>` instead of a vector math library as you suggested? Could I then also get rid of the for loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:38:46.473",
"Id": "451123",
"Score": "0",
"body": "You could use `std::valarray<>` as @Davislor suggested, but that lacks more interesting functions, like calculating the length of a vector. Math libraries will do that for you."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T19:28:40.690",
"Id": "231277",
"ParentId": "231191",
"Score": "7"
}
},
{
"body": "<p>In addition to G. Sliepen’s idea, you could use the STL’s <code>std::valarray<double></code>. This would let you replace something like</p>\n\n<pre><code>for (int d = 0; d < DIM; ++d) {\n p->x[d] += dt * (p->v[d] + a * p->F[d]);\n p->F_old[d] = p->F[d];\n}\n</code></pre>\n\n<p>with something like</p>\n\n<pre><code>p->F_old = p->F;\np->x += dt * (p->v + a * p->F);\n</code></pre>\n\n<p>It would also be possible to lay out a structure of arrays rather than an array of structures. If there are more particles than dimensions, this could let you perform wider vector operations on all the x-coordinates, then all the y-coordinates and all the z-coordinates, rather than being limited to the width of the coordinate system. That is, each <code>p</code> might have only two or three parallel computations, but if you have a number of <code>std::array<std::valarray<double>, DIM></code> with the x-coordinates in <code>x[0]</code>, the y-coordinates in <code>x[1]</code> and the z-coordinates in <code>x[2]</code>, the velocities in <code>v[0]</code>, etc., that might look like:</p>\n\n<pre><code>for (size_t i = 0; i < x.size(); ++i) {\n F_old[i] = F[i];\n x[i] += dt * (v[i] + a * F[i]);\n}\n</code></pre>\n\n<p>and be able to use the full width of your vector registers. This would not, however, work as well if the computations are not so cleanly separable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T23:54:29.253",
"Id": "231289",
"ParentId": "231191",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231216",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T12:00:46.833",
"Id": "231191",
"Score": "32",
"Tags": [
"c++",
"beginner",
"simulation",
"physics"
],
"Title": "Simple n-body class in C++"
}
|
231191
|
<p>I just want to create masonry vertical layout with two divider <code>.card-lef`` and</code>.card-right`. Anyone have an idea to place <code>#cardTemplate</code> in left or right based on data Odd/Even? Or maybe in my .ts separate odd/even array?</p>
<p>HTML:</p>
<p>
</p>
<pre><code><ng-template let-data="data" #cardTemplate>
<div class="card">
</div>
</ng-template>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T01:52:12.890",
"Id": "450848",
"Score": "0",
"body": "It's likely that the even-odd distinction should be made entirely in CSS, not in Angular."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T20:33:51.337",
"Id": "450991",
"Score": "0",
"body": "@200_success yeah it should on css part, but how to get it when we need vertical masonry layout."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T12:41:51.333",
"Id": "231194",
"Score": "2",
"Tags": [
"html",
"angular-2+"
],
"Title": "Angular ng-for Odd/Even Scenario"
}
|
231194
|
<p>I wrote a feature. And it works correctly. But in my opinion it is not optimal. But I have not found what standard features you can use to unleash it. Since I made it a simple sort of values. And it takes a long time to execute.</p>
<pre><code>char getMaxOccuringChar(char* str)
{
int count[ASCII_SIZE] = {0};
int len = strlen(str);
int max = 0;
char result;
for (int i = 0; i < len; i++) {
count[str[i]]++;
if (max < count[str[i]]) {
max = count[str[i]];
result = str[i];
}
}
return result;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:48:47.723",
"Id": "450714",
"Score": "0",
"body": "@SamerTufail The explanation in your comment is either inverted, or confusing: `str[i]` *must* be converted to an unsigned int, otherwise it risks being out of bounds, because `char` might be signed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:33:52.383",
"Id": "450715",
"Score": "0",
"body": "Well, you could keep temporary values of `x = str[i]` and `y = count[x]`, in order to reduce the number of memory-access operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:35:11.567",
"Id": "450716",
"Score": "1",
"body": "If your string is huge, it's probably more efficient to loop through `count` once to determine the max element at the end instead of doing the `if (max < count[str[i]]) { ` for every character in the string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:35:12.810",
"Id": "450717",
"Score": "0",
"body": "`count[str[i]]++; ` are you sure this is what you want? and not str[i] - 'a' or -'A' ? to map it correctly to an index within your count array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:35:13.323",
"Id": "450718",
"Score": "2",
"body": "BTW, you may as well tag this question `C`, as there is no `C++` syntax involved here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:35:16.897",
"Id": "450719",
"Score": "0",
"body": "What if len equals zero? Why `char*` iso `std::string_view` (or `const char *` pre 17)? What makes you think this ain't optimal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:46:59.400",
"Id": "450722",
"Score": "0",
"body": "@JVApen Because I think it is possible to use some functions rather than to walk and to look in cycles by yourself. But I have not found any that can be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:51:20.657",
"Id": "450723",
"Score": "0",
"body": "@Konrad Rudolph having read it again, confusing probably, none the less it requires conversion to an unsigned int, which makes the above code wrong. Would horribly fail on a lot of test cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T22:26:05.120",
"Id": "450838",
"Score": "0",
"body": "This looks exactly like [this GeeksForGeeks solution](https://www.geeksforgeeks.org/return-maximum-occurring-character-in-the-input-string/) ..."
}
] |
[
{
"body": "<p>Here’s how I’d write this using the standard library:</p>\n\n<pre><code>#include <algorithm>\n#include <unordered_map>\n#include <string_view>\n\nchar most_frequent_char(std::string_view str) {\n std::unordered_map<char, int> counts;\n for (auto c : str) counts[c] += 1;\n return std::max_element(\n begin(counts), end(counts),\n [](auto a, auto b) {return a.second < b.second;}\n )->first;\n}\n</code></pre>\n\n<p>But to be honest I’m not happy with manually iterating over the string to counts its characters. In actual code I’d probably abstract away the creation of a <em>frequency table</em>, which would presumably also have a <code>max</code> function. In Python this directly corresponds to the <code>collections.Counter</code> class. If we assume the existence of this utility class (<a href=\"https://gist.github.com/klmr/b7f6b540ad04d291ccdb842b56b669e2\" rel=\"nofollow noreferrer\">left as an exercise to the reader</a>), the implementation becomes</p>\n\n<pre><code>char most_frequent_char(std::string_view str) {\n return max(freq_table{str}).first;\n}\n</code></pre>\n\n<p>Incidentally, in statistics this property is known as the <em>“mode”</em> of a distribution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:56:38.403",
"Id": "450725",
"Score": "1",
"body": "I'd suggest adding the explicit mentioning of that you use a lambda expression? Assuming the guy who wrote the question is a beginner, this might not be clear to that person, or the concept might be alien altogether. With the term being explicitly named, one has something to search for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T11:08:20.980",
"Id": "450726",
"Score": "2",
"body": "@Aziuth \nI'm a girl. I know what lambda is))"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:43:54.860",
"Id": "231197",
"ParentId": "231195",
"Score": "9"
}
},
{
"body": "<p>We don't modify the passed string, so we should accept a <code>const char*</code>.</p>\n<p><code>ASCII_SIZE</code> isn't a standard identifier. A better size for the storage would be <code>UCHAR_MAX+1</code> (found in the <code><climits></code> header).</p>\n<p>The counting elements can be unsigned - I recommend <code>std::size_t</code>, as that's the maximum length of a string.</p>\n<p>Any character greater than <code>ASCII_SIZE</code> or less than zero will index out of range, which is undefined behaviour (a bug).</p>\n<p>We don't need to call <code>std::strlen()</code> to measure the string before we start. We can just advance the index (or pointer) until we reach the terminating NUL character.</p>\n<p>There's a bug if an empty string is passed as argument: in that case, <code>result</code> is never assigned, so we return an indeterminate result.</p>\n<hr />\n<h1>Alternative version</h1>\n<p>Keeping the existing logic, but fixing the above issues and using a more modern <code>std::array</code> instead of a raw (C style) array:</p>\n<pre><code>#include <array>\n#include <climits>\n#include <cstdio> // for EOF\n\n/*\n * Returns the most frequent character, represented as unsigned char.\n * If the string is empty, returns EOF\n */\nint getMaxOccuringChar(char const* s)\n{\n std::array<std::size_t, UCHAR_MAX+1> count = {};\n\n std::size_t max = 0;\n int result = EOF;\n\n while (*s) {\n auto const c = static_cast<unsigned char>(*s++);\n auto current = ++count[c];\n if (max < current) {\n max = current;\n result = c;\n }\n }\n\n return result;\n}\n</code></pre>\n<p>A simple test:</p>\n<pre><code>#include <iostream>\nint main()\n{\n std::cout << static_cast<char>(getMaxOccuringChar("QQMMMX")) << '\\n';\n}\n</code></pre>\n<p>If the input is likely to be more than <code>UCHAR_MAX</code> characters, then it may be better to omit updating <code>max</code> as we update <code>count</code>, and instead find the maximum count after the loop (using <code>std::max_element()</code>, from <code><algorithm></code>).</p>\n<hr />\n<h1>Multiset version</h1>\n<p>We could instead use a multiset to count each character (in its constructor), and then use <code>std::max_element()</code> to find the mode, like this:</p>\n<pre><code>#include <algorithm>\n#include <string_view>\n#include <unordered_set>\n\n/*\n * Returns the most frequent character, represented as unsigned char.\n * If the string is empty, returns the null character\n */\nint getMaxOccuringChar(std::string_view s)\n{\n auto const count = std::unordered_multiset<char>{s.begin(), s.end()};\n if (count.empty()) {\n return 0;\n }\n\n auto const comparator =\n [count](auto a, auto b){ return count.count(a) < count.count(b); };\n return *std::max_element(count.begin(), count.end(), comparator);\n}\n</code></pre>\n<p>You might find that more satisfying (though performance may suffer through having to re-allocate as the set grows, which isn't a problem when we use an array).</p>\n<hr />\n<h1>Consider other character types</h1>\n<p>The second version can be made a template, to work with other character types, such as <code>wchar_t</code>:</p>\n<pre><code>template<typename Char>\nChar getMaxOccuringChar(std::basic_string_view<Char> s)\n{\n auto const count = std::unordered_multiset<Char>{s.begin(), s.end()};\n if (count.empty()) {\n return Char{};\n }\n\n auto const comparator =\n [count](auto a, auto b){ return count.count(a) < count.count(b); };\n return *std::max_element(count.begin(), count.end(), comparator);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T21:46:09.500",
"Id": "231233",
"ParentId": "231195",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231197",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T10:31:02.590",
"Id": "231195",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Function which takes a string as input and returns the most frequent character"
}
|
231195
|
<p>Below are the two things I'm trying to solve, logically. This is just a proof of concept; and I'm not implementing this on real data nor via full plugin at this time. Just looking at logic and syntax solutions. </p>
<p><strong>Below are the (2) requirements.</strong></p>
<p><strong>1.)</strong> Given an API route for retrieving a specific record, do the following:</p>
<ul>
<li>Get the id param</li>
<li>Return a 404 if the record isn't found</li>
<li>Return a response with the record if it is found</li>
</ul>
<p>Route format:</p>
<pre><code>/publishers/(?P<id>\d+)
/publishers/397
</code></pre>
<p><strong>2.)</strong> Add a WordPress hook to determine the value of the visible property on some item. Then use that hook elsewhere to change the value to false;</p>
<p>Below is what I have so far. Which appears correct; but just would like to see if there is a more optimal way, and/or this is still best approach. Just some feedback on my code solution; via the above two points.</p>
<p><strong>My Code solutions:</strong></p>
<hr>
<pre><code><?php
function get_publisher( \WP_REST_Request $request ) {
$request = json_decode( $request );
$publisher_id = $request[ 'ID' ];
if ( empty( $publisher ) ) {
$response = [
'status' => 404,
'data' => [
'errors' => [
'general' => 'Sorry, no record was found.'
],
],
];
return json_encode( $response );
}
$response = [
'status' => 200,
'data' => [
'publisher' => $publisher,
]
];
return json_encode( $response );
}
function modify_item( $item ) {
$item->visible = apply_filters( 'item_visibility', true );
return $item;
}
function hide_item() {
return false;
}
add_filter( 'item_visibility', 'hide_item' );
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>You will need to settle on the variable name containing <code>$request[ 'ID' ];</code>. At the moment, you are using <code>$publisher_id</code> and <code>$publisher</code> ...which of course is a script fouling typo. I'd probably avoid declaring the variable, because I don't find a declarative coding style to be very beneficial in this case.</p></li>\n<li><p>You could use a different syntax to declare your array to be less verbose. For example:</p>\n\n<pre><code> $response['status'] = 404;\n $response['data']['errors']['general'] = 'Sorry, no record was found.';\n</code></pre></li>\n<li><p>By writing an <code>if-else</code>, you can avoid rewriting <code>json_encode()</code>.</p></li>\n</ul>\n\n<p>..I don't WP so I cannot say if there any native techniques to leverage.</p>\n\n<p>The first function could look like this:</p>\n\n<pre><code>function get_publisher(\\WP_REST_Request $request) { \n $request = json_decode($request);\n if (empty($request['ID'])) {\n $response['status'] = 404;\n $response['data']['errors']['general'] = 'Sorry, no record was found.';\n } else {\n $response['status'] = 200;\n $response['data']['publisher'] = $request['ID'];\n }\n return json_encode($response);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T22:01:23.113",
"Id": "231282",
"ParentId": "231201",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:54:15.483",
"Id": "231201",
"Score": "3",
"Tags": [
"php",
"api",
"wordpress"
],
"Title": "WP/PHP getting API data and using hook"
}
|
231201
|
<p>I have the following sample data:</p>
<pre><code>target <- "Stackoverflow"
candidates <- c("Stackflow", "Stackflow", "Stckoverfow")
</code></pre>
<p>I would like to filter the string from <code>candidates</code> that has the lowest (levensthein) distance to the target string.</p>
<p>I decided to use the pipe operator to improve readability. However, i find it suboptimal that adist doesnt return the strings that corresponds to the distances.</p>
<p><strong>My attempts:</strong></p>
<p>Version 1) </p>
<pre><code>library(magrittr)
candidates %>%
adist(y = target) %>%
which.min %>%
`[`(x = candidates, i = .)
</code></pre>
<p>Version 2)</p>
<pre><code>library(dplyr)
candidates %>%
adist(y = target) %>%
data.frame(dist = ., candidates = candidates) %>%
filter(dist == min(dist)) %>% select(candidates)
</code></pre>
<p><strong>Goal:</strong></p>
<p>I want to Improve readability. Memory usage or performance do not matter as data
is pretty small. Using additional packages, like dplyr, is also fine.</p>
<p>In version 1 i think
`[`(...) is bad to read.</p>
<p>Version 2 seems better to me. But it does not seem optimal to me, that i have to add the strings to the data.frame after having applied <code>adist()</code> to them: <code>data.frame(dist = ., candidates = candidates)</code>.</p>
|
[] |
[
{
"body": "<p>What is wrong with simple code like?:</p>\n\n<pre><code>distances <- adist(candidates, target)\ncandidates[distances == min(distances)]\n</code></pre>\n\n<p>This is shorter and, in my opinion, easier to read, as it do not require any knowledge of additional packages.</p>\n\n<p>Also, you mentioned that your data is small and it looks like you are working with vectors, in that case I do not see a point to use <code>data.frame</code>, <code>dplyr</code> etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:55:59.140",
"Id": "450776",
"Score": "0",
"body": "hmm...:) Ileft out some preprocessing steps in the question (which let me choose to go for pipes). But yeah, given me question this is far easier :) Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T14:57:12.770",
"Id": "231207",
"ParentId": "231202",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "231207",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T13:56:07.890",
"Id": "231202",
"Score": "1",
"Tags": [
"comparative-review",
"r",
"edit-distance"
],
"Title": "Filter string with min distance in r"
}
|
231202
|
<p>So, I'm coding a simple Bloom filter. Current implementation works as expected, but I'm looking for ways to improve efficiency / speed. The code is being tested on a large chunk of data (~30k+ lines), so every little bit counts. </p>
<blockquote>
<p>Also: Is there any way I can initialize a vector only one time, not using <code>resize()</code>?</p>
</blockquote>
<pre><code>set() computes number of hashes and size of bit array
add() adds element to filter
search() gives an approximate answer, if filter contains element or not
print() prints bit array
</code></pre>
<p><code>main()</code> mostly contains parsing</p>
<p>Here is the test example: <a href="https://pastebin.com/3edmX2vH" rel="noreferrer">https://pastebin.com/3edmX2vH</a></p>
<p>Here is the code itself:</p>
<pre><code>#include <cmath>
#include <vector>
#include <sstream>
const unsigned long M = 2147483647;
const unsigned long long Primes[] =
{
0, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179,
181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 263, 269, 271, 277, 281
};
template <class T>
class Filter
{
std::vector<bool> bits;
size_t size;
size_t numHashes;
size_t getHash(const T& key,const size_t& hashIndex);
public:
Filter() {};
~Filter() {};
bool Set(const int& n, const double& p);
void Add(const T& key);
void Print();
bool Search(const T& key);
};
template <class T>
bool Filter<T>::Set(const int& n, const double& prob)
{
size = round((-n * log2(prob)) / log(2));
numHashes = round(-log2(prob));
if (size == 0 || numHashes == 0)
{
std::cout << "error" << std::endl;
return false;
}
else
{
bits.resize(size);
std::cout << size << " " << numHashes << std::endl;
return true;
}
}
template <class T>
void Filter<T>::Add(const T& key)
{
for (size_t i = 0; i < numHashes; i++)
{
size_t index = getHash(key, i);
bits[index] = true;
}
}
template <class T>
bool Filter<T>::Search(const T& key)
{
for (size_t i = 0; i < numHashes; i++)
{
size_t index = getHash(key, i);
if (!bits[index])
{
return false;
}
}
return true;
}
template <class T>
void Filter<T>::Print()
{
for (size_t i = 0; i < size; i++)
{
std::cout << bits[i];
}
std:: cout << std::endl;
}
template <class T>
size_t Filter<T>::getHash(const T& key, const size_t& hashIndex)
{
return (((hashIndex + 1) * (key % M) + Primes[hashIndex + 1]) % M) % size;
}
int main()
{
Filter<uint64_t> filter;
std::string command, line;
uint64_t element;
double prob;
bool setFlag = false;
bool empty = false;
while (std::getline(std::cin, line))
{
std::istringstream is(line);
if (is.rdbuf()->in_avail() == 0)
{
empty = true;
}
command.clear();
is >> command >> element >> prob;
if (command == "set")
{
if (!setFlag && element != 0 && prob != 0 && prob < 1)
{
setFlag = filter.Set(element, prob);
}
else
{
std::cout << "error" << std::endl;
}
}
else if (command == "add")
{
is >> element;
if (is.rdbuf()->in_avail() == 0 && setFlag)
{
filter.Add(element);
}
else
{
std::cout << "error" << std::endl;
}
}
else if (command == "search")
{
is >> element;
if (is.rdbuf()->in_avail() == 0 && setFlag)
{
std::cout << filter.Search(element) <<std::endl;
}
else
{
std::cout << "error" << std::endl;
}
}
else if (command == "print" && setFlag)
{
if (is.rdbuf()->in_avail() == 0)
{
filter.Print();
}
else
{
std::cout << "error" << std::endl;
}
}
else
{
if (!empty)
std::cout << "error" << std::endl;
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>The idiom for setting a vector contained in a class is</p>\n\n<pre><code>Filter::Filter( int s ) : bits( vector<bool>(s) ) { ... };\n</code></pre>\n\n<p>In your case <code>s</code> is somewhat tricky, so you'll have to write a function for it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:40:48.627",
"Id": "231210",
"ParentId": "231203",
"Score": "1"
}
},
{
"body": "<p>Some minor things that will improve just a bit, you should precomputed the value of log(2) and put as a constant if is not precomputed by the compiler, and the increments on your loops should be ++i, instead i++</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T20:04:06.423",
"Id": "231227",
"ParentId": "231203",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T14:30:50.377",
"Id": "231203",
"Score": "6",
"Tags": [
"c++",
"bloom-filter"
],
"Title": "Bloom Filter, Simple C++ Implementation"
}
|
231203
|
<p>I wrote a function that downloads a file <code>https://www.ohjelmointiputka.net/tiedostot/junar.zip</code> if it not already downloaded, unzips it and returns the content of <code>junar1.in</code> found in this zip. I have PEP8 complaints about the length of lines that I would like to fix. Is there a way to make the code more readable?</p>
<p>My code :</p>
<pre><code>import os.path
import urllib.request
import shutil
import zipfile
def download_and_return_content():
if not os.path.isfile('/tmp/junar.zip'):
url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'
with urllib.request.urlopen(url) as response, open('junar.zip', 'wb') as out:
data = response.read() # a `bytes` object
out.write(data)
shutil.move('junar.zip','/tmp')
with zipfile.ZipFile('/tmp/junar.zip', 'r') as zip_ref:
zip_ref.extractall('/tmp/')
with open('/tmp/junar1.in') as f:
return f.read()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:10:15.217",
"Id": "450764",
"Score": "1",
"body": "Hey juniorprogrammer, I edited your question to make it more to the \"CodeReview Format\"' please check it out. Feel free to rollback the edit if you don't like it, but I think your question will receive more attention this way :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:26:48.803",
"Id": "450771",
"Score": "1",
"body": "You seem to have omitted the `import` statements when pasting here - could you please reinstate them? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:58:26.247",
"Id": "450777",
"Score": "0",
"body": "True. I edited my code."
}
] |
[
{
"body": "<h1>PEP-8 Line Length</h1>\n\n<p>For particularly lengthy lines, you can always use parentheses to wrap them instead of the usual <code>\\</code> sign:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = (1 + 2 + 3 +\n 4 + 5 + 6)\n</code></pre>\n\n<h1>Function Refactor</h1>\n\n<p>I would skip the step in your <code>if</code> statement where you use <code>shutil.move</code>, just save the file in <code>/tmp</code> directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def download_and_return_content():\n if not os.path.isfile('/tmp/junar.zip'):\n url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'\n with urllib.request.urlopen(url) as response, open('/tmp/junar.zip', 'wb') as out:\n data = response.read() # a `bytes` object\n out.write(data)\n</code></pre>\n\n<p>Furthermore, if you are just looking to extract a single file, you can open one of the archives directly using <a href=\"https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.open\" rel=\"nofollow noreferrer\"><code>ZipFile.open</code></a></p>\n\n<pre class=\"lang-py prettyprint-override\"><code> with ZipFile('/tmp/junar.zip') as myzip:\n with myzip.open('junar1.in') as f:\n return f.read()\n</code></pre>\n\n<p><code>ZipFile</code> can also take a file-like object, so you can use a <code>BytesIO</code> object to hold your zip-file bytes, since <code>/tmp</code> implies you might not need to hold onto this data:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from io import BytesIO\n\ndef download_and_return_content():\n # your temporary file-handle\n tmp_file = BytesIO()\n\n url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'\n with urllib.request.urlopen(url) as response:\n tmp_file.write(response.read())\n\n tmp_file.seek(0)\n\n with ZipFile(tmp_file) as myzip:\n with myzip.open('junar1.in') as fh:\n return fh.read()\n</code></pre>\n\n<p>Lastly, the <code>if</code> check implies that maybe you want to cache the data somehow. You could <em>in theory</em> use <code>BytesIO</code> as a mutable default. You can use <code>BytesIO.tell()</code> as your check if it has content:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_content(tmp=BytesIO()):\n # buffer is at position 0, it has not been read or written to\n # therefore it is probably empty\n if not tmp.tell():\n tmp.truncate() # just in case\n url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'\n with urllib.request.urlopen(url) as response:\n tmp.write(response.read())\n\n # set buffer to position 0 to read content\n tmp.seek(0)\n\n with ZipFile(tmp) as myzip:\n # this will move the buffer to a non-zero position\n # so, now tmp.tell() will be non-zero and will pass the\n # if check on the next function call\n with myzip.open('junar1.in') as fh:\n return fh.read()\n</code></pre>\n\n<p>As a caveat, there are caching libraries in python that can accomplish this as well, I'm just not familiar enough with them to suggest any in a meaningful way.</p>\n\n<p>Before everybody grabs their torches and pitchforks, the non-mutable-default way (usually mutable defaults are seen as bad design) could look something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># refactor into two functions, one that does the actual urllib call\n# for you to retrieve your data\ndef get_data(tmp=None):\n tmp = tmp or BytesIO()\n\n with urllib.request.urlopen(url) as response:\n tmp.write(response.read())\n\n return tmp\n\n# and one to actually extract the file\ndef extract_file(tmp=None):\n tmp = tmp or get_data()\n\n tmp.seek(0)\n\n with ZipFile(tmp) as myzip:\n with myzip.open('junar1.in') as fh:\n return fh.read()\n\n\n# now you can hold that BytesIO object\ntmp_file = get_data()\n\ncontent = extract_file(tmp_file)\n# returns b'10\\r\\n6\\r\\n1\\r\\n4\\r\\n10\\r\\n7\\r\\n2\\r\\n3\\r\\n9\\r\\n5\\r\\n8\\r\\n'\n\n# and if you want to write that temp file somewhere\nwith open('/tmp/somefile.zip', 'wb') as fh:\n tmp_file.seek(0)\n fh.write(tmp_file.read())\n</code></pre>\n\n<p>Of course this all depends on what you need that zipfile for, but this cuts down on the amount of reads and writes you are doing under the hood.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T17:24:41.363",
"Id": "231220",
"ParentId": "231205",
"Score": "2"
}
},
{
"body": "<p>Let's start refactoring/optimizations:</p>\n\n<ul>\n<li><code>urllib</code> should be replaced with <a href=\"https://realpython.com/python-requests/\" rel=\"nofollow noreferrer\"><code>requests</code></a> library which is the de facto standard for making HTTP requests in Python and has reach and flexible interface.</li>\n<li>instead of moving from intermediate location (<code>shutil.move('junar.zip','/tmp')</code>) we can just save the downloaded zip file to a destination path <code>with open('/tmp/junar.zip', 'wb') as out</code></li>\n<li>decompose the initial function into 2 separate routines: one for downloading zipfile from specified location/url and the other - for reading a specified (passed as an argument) zipfile's <em>member/inner file</em></li>\n<li>reading from <code>zipfile.ZipFile.open</code> directly to avoid intermediate extraction. Otherwise zipfile contents should be extracted at once, then - just reading a regular files being extracted (with adjusting the \"reading\" function)</li>\n</ul>\n\n<hr>\n\n<p>From theory to practice:</p>\n\n<pre><code>import os.path\nimport requests\nimport zipfile\nimport warnings\n\n\ndef download_zipfile(url):\n if not os.path.isfile('/tmp/junar.zip'):\n with open('/tmp/junar.zip', 'wb') as out:\n out.write(requests.get(url).content)\n\n\ndef read_zipfile_item(filename):\n with zipfile.ZipFile('/tmp/junar.zip') as zip_file:\n with zip_file.open(filename) as f:\n return f.read().decode('utf8')\n\n# Testing\nurl = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'\ndownload_zipfile(url=url)\nprint(read_zipfile_item('junar1.in'))\n</code></pre>\n\n<p>The actual output (until the input url is accessible):</p>\n\n<pre><code>10\n6\n1\n4\n10\n7\n2\n3\n9\n5\n8\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T20:13:07.033",
"Id": "450819",
"Score": "0",
"body": "That is fine with me - I have deleted mine. Please feel free to add your point 3 back. If you do please add the rational that you stated in the comments, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T20:45:14.067",
"Id": "450826",
"Score": "0",
"body": "@Peilonrayz, mine were deleted. As for turning back the 3rd thesis, I'm not sure whether it's worthwhile as it evoked a negative \"reaction\". I didn't quite follow why just *optionally logging failed downloading attempts (logger.warning(...))* can cause such a critics. In my understanding, if it happened once, then, hypothetically that fragment could be negatively perceived by someone else again. So maybe we may leave it uncovered/hidden."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:54:59.823",
"Id": "450935",
"Score": "0",
"body": "Where to log information can be subjective, but ultimately alerting the user that a different behavior will occur due to X condition is never a bad thing. I think the sticking point may have been using `warning` which implies that something needs attention when maybe `info` might be a bit more appropriate. However, I stand by the premise that having alerting is better than none :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:02:49.910",
"Id": "231221",
"ParentId": "231205",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231221",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T14:43:20.340",
"Id": "231205",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "Download a zip archive and extract one file from it"
}
|
231205
|
<p>As part of the prologue of all my console applications, I need to determine the extents of the current terminal so if there are less than 132 columns or 43 lines the user can be warned output may not appear as expected. Code has been tested with;</p>
<blockquote>
<p>$ AppName <strong>/usr/include/*.h</strong></p>
</blockquote>
<p><strong>Assemble with</strong> <em>source</em> being whatever name you want to give app.</p>
<blockquote>
<pre><code>~$ nasm -felf64 source.asm -source.o
~$ ld -osource -osource
</code></pre>
</blockquote>
<p>which passes 112 arguments to process.</p>
<p>Essentially what I am going for is contiguous flow with the least number of
instructions. Time is an important consideration but it is the least important especially considering if my calculations are near correct, this procedure comes in at 4.18 micro seconds. </p>
<pre><code> USE64
global _start
section .text
; *----* *----* *----* *----* *----* *----* *----* *----* *----* *----* *----*
_start:
%define argc [rbp+ 8]
%define args [rbp+16]
mov rsi, rsp ; Establish pointer to argc.
push rbp ; So argc & **args can easily be addressed
mov rbp, rsp ; via base pointer.
; This application expects a minimum 132 x 43 terminal. If this sessions metrics
; are less than that, then operator needs to be made aware output to screen
; may not be as expected.
; [A] Establish a pointer to the array of QWORD pointers to environment
; strings. It is determined by &argc + (argc+1) * 8
lodsq ; Determine # of args passed via command-line
inc eax ; Bump argument count
shl rax, 3 ; Multiply by 8
add rsi, rax ; Add result to &argc
; [B] Intialize the two registers needed for the loop that determines
; matching entries.
mov edi, Metrics ; Pntr to the two strings that need to be found.
; RDX Bits 07 - 00 = Count of environment variables.
; 15 - 08 = Columns defined by "COLUMNS=".
; 23 - 16 = Rows " " "LINES=".
xor edx, edx
mov ecx, edx ; Should be zero, but just to be safe.
FindMatch:
lodsq ; Get pointer to next environment string.
test eax, eax ; NULL pointer indicates end of array.
jnz .cont
; Now RBP - 1 = Count of environment strings
; RBP - 2 = Current display columns
; RBP - 3 = rows
mov [rbp-4], edx
jmp .done
.cont:
inc dl ; Bump count of environment strings.
mov ecx, 6 ; Length of string first string.
mov bl, [rax] ; Get first character.
; Determine if this string begins with either 'L' or 'C'.
cmp bl, 'L'
jz .cmpstr
cmp bl, 'C'
jnz FindMatch
push rdi
add edi, ecx ; Bump to point to next string
add cl, 2 ; and it is 2 characters longer
jmp .cmpstr + 1 ; No need to save RDI again
; Now that the first character matches, determine if the remaining
; do for a count of CL
.cmpstr:
push rdi
push rsi
mov rsi, rax ; Move pointer to string into source index.
repz cmpsb ; Compare strings for count of CL.
jnz .nextone ; Does not match? Carry on.
mov rax, rcx ; Both registers are NULL now.
.L0: lodsb ; Read ASCII decimal digit.
test eax, eax
jz .J0
; Convert ASCII decimal digits to binary. As it is safe to assume we will
; only be expecting characters '0' - '9', this works quite effectively.
and al, 15 ; Strip high nibble
imul ecx, 10
add ecx, eax
jmp .L0
; Determine which position result will be written based on which
; calculation was done
.J0: shl ecx, 16 ; Assume value is # of rows.
cmp byte [rdi], 0
jnz $ + 5
shr ecx, 8 ; Move back into columns position.
or edx, ecx ; Copy to appropriate position in RDX
.nextone:
pop rsi
pop rdi ; Restore pointer to array of pointers.
jmp FindMatch
.done:
shr edx, 8
sub dx, 0x2b84 ; Equivalent to DH = 43 & DL = 132
test dx, 0x8080 ; Result equal negative in either 8 bit register
jz ParseCmdLine
; TODO -> Put some kind of prompting here for user to respond too.
ParseCmdLine:
; TODO -> Implement something similar to optarg.
Exit:
leave ; Kill empty procedure frame
xor edi, edi ; Set return code EXIT_SUCCESS
mov eax, sys_exit
syscall ; Terminate application
section .rodata
; =============================================================================
Metrics db 'LINES='
db 'COLUMNS=',0,0 ; So next is page aligned.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T01:46:39.990",
"Id": "450846",
"Score": "2",
"body": "Why assembly? If it's for learning, fine. If it's because you think you can beat the performance of an optimizing compiler, then... I find that suspect, to put it lightly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T03:16:20.020",
"Id": "450854",
"Score": "2",
"body": "@Reinderien It is nothing more than a hobby and a relaxing means by which to program and share my invocations with others. However it would be monumentally educational if someone was to implement an HLL version, but of the several times I've suggested this over the years, it's never come to fruition. Why, I don't know, but I suspect it can't be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T03:19:50.707",
"Id": "450855",
"Score": "1",
"body": "Nice I neglected to include \"for fun\", because apparently I've become a stick in the mud."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T18:57:51.460",
"Id": "451107",
"Score": "0",
"body": "Do you have the `tput` command on Linux? It's [a one-liner](https://unix.stackexchange.com/questions/185509) using that command, and on NetBSD the source code for the [tput](https://github.com/NetBSD/src/blob/trunk/usr.bin/tput/tput.c) command is not that complicated either. Written in C, it's probably 20 lines of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T23:52:09.040",
"Id": "451136",
"Score": "0",
"body": "@RolandIllig Yes I do and that source code is going to be very helpful as I'm just starting to work on a snippet that functions like getop(). You link eludes to 160 lines of code, but none the less, examples are always helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T00:09:01.177",
"Id": "451140",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back that last edit to the code."
}
] |
[
{
"body": "<h2>A code-size optimization</h2>\n\n<p>If you move the <code>mov edi, Metrics</code> instruction to just below the <em>FindMatch</em> label and thus have it repeat with each iteration, you can remove 4 instructions from the code. I've marked these with an exclamation mark:</p>\n\n<pre><code> xor edx, edx\n mov ecx, edx\n FindMatch:\n mov edi, Metrics ;Restore it from here\n lodsq \n\n\n\n\n! push rdi\n add edi, ecx\n add cl, 2\n! jmp .cmpstr + 1 ; No need to save RDI again\n .cmpstr:\n! push rdi\n push rsi\n\n ...\n\n .nextone:\n pop rsi\n! pop rdi ; Restore pointer to array of pointers.\n jmp FindMatch\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>cmp bl, 'L'\njz .cmpstr\ncmp bl, 'C'\n</code></pre>\n</blockquote>\n\n<p>Are these environment strings guaranteed to be in uppercase?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T23:13:26.313",
"Id": "451132",
"Score": "0",
"body": "I believe they have been and always will be uppercase although I don't have anything specifically to back that up. @Edward pointing me toward `TIOCGWINSZ` will probably see that part replaced anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T23:17:26.500",
"Id": "451133",
"Score": "0",
"body": "My first revision implemented your example, but I decided to trade space for speed as moving from memory takes 6 cycles and push/pop only take one. I figure on my machine that save about 17 micro seconds but if I was to do that is a thousand places that would amount to 17 millisec."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:55:51.423",
"Id": "231312",
"ParentId": "231209",
"Score": "3"
}
},
{
"body": "<p>Here are some things that may help you improve your program</p>\n\n<h2>Use consistent formatting</h2>\n\n<p>The code as posted has irregular indentation, making it not so easy to read. Assembly language programs are typically very linear and neat. Also, I personally don't use tab characters in my code so that it looks the same everywhere (including printing), but that's a personal preference.</p>\n\n<h2>Provide the complete program</h2>\n\n<p>The program is missing the definition of <code>sys_exit</code> (which should have a value of 60). I'd suggest also telling reviewers how you've compiled and linked the program. Here's what I used:</p>\n\n<pre><code>nasm -o rowcol.o -f elf64 rowcol.asm\nld -o rowcol rowcol.o\n</code></pre>\n\n<h2>Document register use</h2>\n\n<p>The comments in your program are generally quite good, but one thing lacking is documentation on how the registers are being used, which is one of the most important aspects to assembly language programming. The x86 architecture is unlike many others in that particular instructions require particular registers. For that reason, it's useful to identify when you'll need to use such instructions and base the register usage around that.</p>\n\n<h2>Avoid slow instructions</h2>\n\n<p>Although special-purpose instructions such as <code>loop</code> and <code>repnz scasb</code> seem appealing, they are, in fact, relatively slow. Instead, it's usually much faster (and not that many more code bytes) to do things with the more generic instructions.</p>\n\n<h2>Use address multipliers for efficiency</h2>\n\n<p>We can greatly simplify getting a pointer to the environment list into a register:</p>\n\n<pre><code>mov rbp, rsp ; use rbp for stack pointer\nmov rcx, [rbp + 0] ; get argc\nlea rbx, [rbp+8+8*rcx] ; rbx now points to env\n</code></pre>\n\n<h2>Understand environment variables</h2>\n\n<p>In Linux, there is a difference between shell variables and environment variables. Environment variables are what your program is searching, but the <code>LINES</code> and <code>COLUMNS</code> variables are shell variables that are set by the shell but typically <em>not</em> as environment variables. See <a href=\"https://stackoverflow.com/questions/22588272/getenv-not-working-for-columns-and-lines\">this question</a> for details.</p>\n\n<h2>Use an IOCTL</h2>\n\n<p>The reliable way to get the screen dimensions in Linux is to invoke the <code>TIOCGWINSZ</code> <code>ioctl</code> call. In C++ it would might look like this:</p>\n\n<pre><code>#include <sys/ioctl.h>\n#include <unistd.h>\n#include <iostream>\n\nint main () {\n struct winsize w;\n ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);\n std::cout << \"lines = \" << w.ws_row << \"\\ncolumns = \" << w.ws_col << '\\n';\n}\n</code></pre>\n\n<p>So we just need to put that into assembly language. First, some constants:</p>\n\n<pre><code>sys_ioctl equ 0x10\nSTDOUT_FILENO equ 1\nTIOCGWINSZ equ 0x5413\n</code></pre>\n\n<p>Now the <code>winsize</code> structure:</p>\n\n<pre><code>struc winsize\n .ws_row: resw 1\n .ws_col: resw 1\n .ws_xpixel: resw 1\n .ws_ypixel: resw 1\nendstruc\n\nsection .bss\nw resb winsize_size ; allocate enough for the struc\n</code></pre>\n\n<p>Finally the call:</p>\n\n<pre><code>mov edx, w\nmov esi, TIOCGWINSZ\nmov edi, STDOUT_FILENO\nmov eax, sys_ioctl\nsyscall\n; do stuff with window size...\n</code></pre>\n\n<p>If the call was successful (that is, if <code>eax</code> is 0) then the <code>winsize</code> structure is filled in with the current dimensions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T23:40:28.183",
"Id": "451135",
"Score": "0",
"body": "Please provide a little more detail in regard to indentation. Documenting has always been a problem. I think what I should start is writing a large block, get it working the way I want and then document. The tip on `winsize` is going to shave off many bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T00:05:33.900",
"Id": "451139",
"Score": "0",
"body": "I see what you mean by the indentation and if you load code into an editor that is set for tabs of 8, it is a real mess. When I've implemented `TIOCGWINSZ` I will make sure replace tabs with spaces."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:02:22.517",
"Id": "231315",
"ParentId": "231209",
"Score": "3"
}
},
{
"body": "<p>As a result of a alternate method deliniated by <a href=\"https://codereview.stackexchange.com/users/39848/edward\">Edward</a>, overhead has been reduced from 168 bytes to 56 a <em>300%</em> saving. </p>\n\n<blockquote>\n <p>~$ nasm -felf64 appname.asm -oappname.o<br>\n ~$ ld appname.o -oappname</p>\n</blockquote>\n\n<pre><code> USE64\n\n TIOCGWINSZ equ 0x5413\n STDOUT_FILENO equ 1\n\n sys_ioctl equ 16\n sys_exit equ 60\n\n global _start\n\n section .text\n; =============================================================================\n\n _start:\n\n %define argc [rbp+ 8]\n %define args [rbp+16]\n\n push rbp ; So argc & **args can easily be.\n mov rbp, rsp ; addressed via base pointer.\n xor eax, eax\n\n mov edx, winsize ; Point to structure.\n mov esi, TIOCGWINSZ ; Read structure.\n mov edi, eax\n mov di, STDOUT_FILENO\n mov al, sys_ioctl\n syscall\n test ax, ax ; If there is an error just bail.\n jnz Exit ; because the likelihood slim to none.\n\n ; ws_xpixel & ws_ypixel are of no conseqence, so they will be overwritten\n ; with condition bits. Semicolon denotes bit position\n\n ; ws_xpixel:0 != 1 Windows has fewer than 43 rows.\n ; wx_xpixel:1 != 1 132 cols. \n\n cld ; Just to be sure of auto increment.\n mov esi, edx ; Move to source index for LODSW.\n mov edx, eax ; Applications status bits (flags).\n lodsw ; Read rows from ws_row.\n sub ax, 43 ; Minimum rows expected.\n jns $ + 5 ; Skips over next instruction.\n or dl, 1 ; Set bit zero (rows below minimum).\n lodsw ; Read columns from ws_col\n sub ax, 132 ; Minimum columns expected.\n jns $ + 5 ; Skips over next instruction.\n or dl, 2 ; Set bit columns below minimum.\n\n ; Save new data where ws_xpixel was and erase any extraneous\n ; data @ ws_ypixel\n\n mov [rsi], edx ; Overwrite ws_xpixel & ws_ypixel.\n\n Exit: leave ; Kill empty procedure frame.\n xor edi, edi ; Set return code EXIT_SUCCESS.\n mov eax, sys_exit\n syscall ; Terminate application\n\n section .bss\n; =============================================================================\n\n winsize:\n .ws_row resw 1\n .ws_col resw 1\n .ws_xpixel resw 1\n .ws_ypixel resw 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:37:50.043",
"Id": "451183",
"Score": "0",
"body": "Jumps often take longer, and jumps without explicitly named targets are a recipe for future frustration. (What happens if you add an instruction?) So I'd recommend doing this without jumps instead. Remember that a `cmp` instruction conditionally sets the carry flag; we can use that fact to produce a branchless version of the code: \n `xor edx,edx`\n `cmp word [winsize.ws_col], 132`\n `adc edx,edx`\n `shl edx,1`\n `cmp word [winsize.ws_row], 43`\n `adc edx,0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:38:37.537",
"Id": "451184",
"Score": "0",
"body": "That sets the `edx` register exactly the same way your code did."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T04:57:43.080",
"Id": "231329",
"ParentId": "231209",
"Score": "0"
}
},
{
"body": "<p><strong>Edward</strong> wrote:</p>\n\n<blockquote>\n <p>Jumps often take longer, and jumps without explicitly named targets are a recipe for future frustration.</p>\n</blockquote>\n\n<p>Yes, I remember the days when I used to spend hours just for that very reason, but it's become such a habit now, that whenever I anticipate a change, if there isn't an explicit reference I look up in code to see where that register was initialized. What I plan on doing in the future is commenting as such;</p>\n\n<pre><code> cld ; Just to be sure indices auto increment.\n\n; RDX has been set to winsize structure by previous \n; sys_ioctl call to TIOCGWINSZ, as has RAX been set to zero.\n\n cmp word [edx+2], 132 ; Expect a minimum 132 columns\n adc al, al\n shl al, 1 ; Move to next bit position\n cmp byte [edx], 43 ; Expect a minimum 43 rows\n adc al, 0\n\n; Save new data where ws_xpixel was and erase any extraneous\n; data @ ws_ypixel\n\n mov [edx+4], eax ; Overwrite ws_xpixel & ws_ypixel.\n</code></pre>\n\n<p>I think this would be a step in the right direction for those reading my code that they wouldn't have to search all over. This example saves another 5 bytes using implicit references instead of explicit.</p>\n\n<hr>\n\n<p>A significant size and by that extension speed saving was realized with this change.</p>\n\n<pre><code> 22: 89 c2 mov edx,eax\n 24: 66 ad lods ax,WORD PTR ds:[rsi]\n 26: 66 83 e8 2b sub ax,0x2b\n 2a: 79 03 jns 2f <_start+0x2f>\n 2c: 80 ca 01 or dl,0x1\n 2f: 66 ad lods ax,WORD PTR ds:[rsi]\n 31: 66 2d 84 00 sub ax,0x84\n 35: 79 03 jns 3a <_start+0x3a>\n 37: 80 ca 02 or dl,0x2\n 3a: 89 16 mov DWORD PTR [rsi],edx\n\n 0x3c - 0x22 = 26 bytes\n</code></pre>\n\n<p>versus</p>\n\n<pre><code> 20: 66 67 81 7a 02 84 00 cmp WORD PTR [edx+0x2],0x84\n 27: 10 c0 adc al,al\n 29: d0 e0 shl al,1\n 2b: 67 80 3a 2b cmp BYTE PTR [edx],0x2b\n 2f: 14 00 adc al,0x0\n 31: 67 89 42 04 mov DWORD PTR [edx+0x4],eax\n\n 0x35 - 0x20 = 21 bytes\n</code></pre>\n\n<p>Had I used explicit references, then the size saving would have been completely negated, but speed is still significantly improved in either context.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T19:33:19.267",
"Id": "451204",
"Score": "1",
"body": "Using a `BYTE PTR` for the lines count may save one byte, but IMHO it's a poor bargain because it's a latent bug if anyone uses a screen that has 256 or more lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T20:59:39.110",
"Id": "451213",
"Score": "0",
"body": "@Edward Very interesting point as it hadn't dawned on me if someone was to take a 16:9 monitor and use it in portrait mode and change the resolution, the row count could be as high as 475. I've changed the code accordingly as those kind of bugs are really hard to find."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T18:39:56.537",
"Id": "231348",
"ParentId": "231209",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231315",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:03:19.320",
"Id": "231209",
"Score": "7",
"Tags": [
"console",
"linux",
"assembly",
"x86"
],
"Title": "Ubuntu 18.04.3 LTS get terminal columns and rows NASM"
}
|
231209
|
<p>I am trying to find out if there is any difference between two implementations that currently do the same thing - gracefully shutdown applications/servers, for example, when <kbd>Ctrl</kbd>+<kbd>C</kbd> is hit. Both work fine and are based on the <a href="https://golang.org/pkg/net/http/#Server.Shutdown" rel="nofollow noreferrer">documentation</a>.</p>
<p>What a friend of mine says, is that Example 2 handles shutdown at the application level which shuts down all contexts throughout the application. However, Example 1 does it at the HTTP server level which doesn't necessarily shut down all contexts throughout the application. Since I am a beginner I cannot argue back and need your input on this, please.</p>
<p><strong>Example 1</strong></p>
<p>The signals are handled in the http.go file so the whole graceful shutdown has been handled in a single file.</p>
<p><strong>cmd/app/main.go</strong></p>
<pre><code>package main
import (
"context"
"internal/http"
"os"
"os/signal"
"syscall"
)
func main() {
// Bootstrap config, logger, etc
http.Start()
}
</code></pre>
<p><strong>internal/http/server.go</strong></p>
<pre><code>package http
import (
"context"
"github.com/prometheus/common/log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func Start() {
log.Infof("starting HTTP server")
srv := &http.Server{Addr: ":8080", Handler: nil}
idle := make(chan struct{})
go shutdown(srv, idle)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("failed to start/close HTTP server [%v]", err)
}
<-idle
log.Info("gracefully shutdown HTTP server")
}
func shutdown(srv *http.Server, idle chan<- struct{}) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("shutdown HTTP server by interrupting idle connections [%v]", err)
}
close(idle)
}
</code></pre>
<p><strong>Example 2</strong></p>
<p>The signals are handled in the application's main.go file so the whole graceful shutdown has been split within two files. The only addition is this example uses the <code>WithCancel</code> context.</p>
<p><strong>cmd/app/main.go</strong></p>
<pre><code>package main
import (
"context"
"internal/http"
"os"
"os/signal"
"syscall"
)
func main() {
// Bootstrap config, logger, etc
backgroundCtx := context.Background()
withCancelCtx, cancel := context.WithCancel(backgroundCtx)
go shutdown(cancel)
http.Start(withCancelCtx)
}
func shutdown(cancel context.CancelFunc) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-sig
cancel()
}
</code></pre>
<p><strong>internal/http/server.go</strong></p>
<pre><code>package http
import (
"context"
"github.com/prometheus/common/log"
"net/http"
"time"
)
func Start(ctx context.Context) {
log.Infof("starting HTTP server")
srv := &http.Server{Addr: ":8080", Handler: nil}
idle := make(chan struct{})
go shutdown(ctx, srv, idle)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("failed to start/close HTTP server [%v]", err)
}
<-idle
log.Info("gracefully shutdown HTTP server")
}
func shutdown(ctx context.Context, srv *http.Server, idle chan struct{}) {
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("shutdown HTTP server by interrupting idle connections [%v]", err)
}
close(idle)
}
</code></pre>
|
[] |
[
{
"body": "<p>There is no \"magic\" difference between solution 1 and 2. They do the same thing as of now. Both solution 1 and 2 react to Ctrl+C in the same way. The only difference is that by additionally using <code>ctx</code> in solution 2, you allow yet another possibility to trigger a graceful shutdown from software. For now, YAGNI, so I am reviewing the simpler solution 1.</p>\n\n<p>The biggest mistake by far and the biggest lesson (for any language, not in any way Go specific): if you introduce a dependency such as \"github.com/prometheus/common/log\", make a cost-benefit calculation. Always. That is: if you need colorful logs, don't introduce 75 new packages to do that. One line turned a nice slim http server into a super-fragile behemoth. Specifically for Go 1.11+, you can see it here:</p>\n\n<pre><code>go mod init\ncat go.mod\ngo build ./...\ncat go.mod # now populated \ngo mod graph\n (prints one line per each module and version)\n</code></pre>\n\n<p>Also, I think that code becomes less complicated if you <code>Shutdown</code> in the main flow, and <code>ListenAndServe</code> in a goroutine? Take a look at my proposition:</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package http // new line\n\nimport (\n \"context\"\n \"net/http\"\n \"os\"\n \"os/signal\"\n \"syscall\"\n \"time\"\n\n log \"github.com/sirupsen/logrus\" // resulting `go mod graph` prints 7 modules\n // \"log\" // builtin without coloring - 0 modules\n //\"github.com/prometheus/common/log\" // resulting `go mod graph` prints 75 modules\n)\n\nfunc Start() {\n log.Infof(\"starting HTTP server\")\n\n srv := &http.Server{Addr: \":8080\", Handler: nil}\n\n go func() { // change\n if err := srv.ListenAndServe(); err != http.ErrServerClosed {\n log.Fatalf(\"failed to start HTTP server: %v\", err) // change\n }\n }()\n\n sig := make(chan os.Signal, 1)\n\n signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n <-sig\n\n ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // change\n defer cancel()\n\n if err := srv.Shutdown(ctx); err != nil {\n log.Fatalf(\"graceful shutdown of HTTP server: %v\", err) // change\n }\n\n log.Info(\"gracefully shutdown HTTP server\")\n}\n</code></pre>\n\n<p>For <strong>cmd/app/main.go</strong> my only concern is to use fully qualified import path like \"github.com/kubanczyk/myproj/internal/http\" instead of <code>import \"internal/http\"</code>. There are dirty tricks to make short \"internal/http\" work for a short while, but I wouldn't recommend that. It's only intended for built-ins.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T11:58:34.217",
"Id": "231731",
"ParentId": "231213",
"Score": "0"
}
},
{
"body": "<p>So to be helpful to others who might be interested in the final outcome after many R&D days and suggestions from other forum users so on., this is what I ended up with. I hope it helps and comments are welcome.</p>\n\n<p><strong>cmd/myself/main.go</strong></p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package main\n\nimport (\n \"context\"\n \"net/http\"\n \"log\"\n \"os\"\n \"os/signal\"\n \"syscall\"\n\n \"myself/internal/app\"\n)\n\nfunc main() {\n srv := &http.Server{\n Addr: \":8080\",\n Handler: router.New(),\n }\n\n ctx, cancel := context.WithCancel(context.Background())\n\n signalChan := make(chan os.Signal, 1)\n\n go handleSignal(signalChan, cancel)\n\n if err := app.New(srv).Start(ctx); err != nil {\n log.Fatal(err)\n }\n\n log.Info(\"shutdown complete\")\n}\n\nfunc handleSignal(signalChan chan os.Signal, cancel context.CancelFunc) {\n // os.Interrupt: Ctrl-C\n // syscall.SIGTERM: kill PID, docker stop, docker down\n signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)\n\n sig := <-signalChan\n\n log.Infof(\"shutdown started with %v signal\", sig)\n\n cancel()\n}\n</code></pre>\n\n<p><strong>internal/app/mysql.go</strong></p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package app\n\nimport (\n \"context\"\n \"fmt\"\n \"log\"\n \"net/http\"\n \"time\"\n)\n\ntype App struct {\n server *http.Server\n}\n\nfunc New(srv *http.Server) App {\n return App{\n server: srv,\n }\n}\n\nfunc (a App) Start(ctx context.Context) error {\n shutdownChan := make(chan struct{})\n\n go handleShutdown(ctx, shutdownChan, a)\n\n if err := a.server.ListenAndServe(); err != http.ErrServerClosed {\n return fmt.Errorf(\"failed to start [%v]\", err)\n }\n\n <-shutdownChan\n\n return nil\n}\n\nfunc handleShutdown(ctx context.Context, shutdownChan chan<- struct{}, a App) {\n <-ctx.Done()\n\n ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)\n defer cancel()\n\n if err := a.server.Shutdown(ctx); err != nil {\n log.Infof(\"interrupted active connections [%v]\", err)\n } else {\n log.Infof(\"served all active connections\")\n }\n\n close(shutdownChan)\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:58:12.027",
"Id": "510781",
"Score": "0",
"body": "The shutdownChan is surprising to me. I would expect that ListenAndServe returns only after Shutdown is complete, but apparently this is not the case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:11:53.947",
"Id": "510784",
"Score": "0",
"body": "From godoc: When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T16:15:16.887",
"Id": "231900",
"ParentId": "231213",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231900",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:19:42.517",
"Id": "231213",
"Score": "4",
"Tags": [
"go"
],
"Title": "Graceful shutdown of applications/servers"
}
|
231213
|
<h3>Problem</h3>
<p>Write a program to return <code>True</code>, if a string is a strong password.</p>
<hr />
<p>A password is considered strong if below conditions are all met:</p>
<ul>
<li>It should have at least 6 characters and at most 20 characters.</li>
<li>It must contain at least one lowercase, one uppercase and one digit.</li>
<li>It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is fine, assuming other conditions are met).</li>
</ul>
<h3>Code</h3>
<p>I've solved a similar problem to <a href="https://leetcode.com/problems/strong-password-checker/" rel="nofollow noreferrer">LeetCode Strong Password Checker</a>. If you would like to review the code or add other methods or provide any change/improvement recommendations please do so! Thank you!</p>
<pre><code>def strong_password_match(s: str) -> bool:
"""Returns a boolean if a password is correct"""
import re
if re.match(
r'^(?!.*([a-z])\1\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{6,20}$', s) is not None:
return True
return False
def strong_password_search(s: str) -> bool:
"""Returns a boolean if a password is correct"""
import re
if re.search(
r'^(?!.*([a-z])\1\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{6,20}$', s) is not None:
return True
return False
def strong_password_findall(s: str) -> bool:
"""Returns a boolean if a password is correct"""
import re
if re.findall(
r'^(?!.*([a-z])\1\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{6,20}$', s) != []:
return True
return False
if __name__ == '__main__':
# ---------------------------- TEST ---------------------------
import timeit
import cProfile
DIVIDER_DASH_LINE = '-' * 50
GREEN_APPLE = '\U0001F34F'
RED_APPLE = '\U0001F34E'
test_methods = (
("re.match", strong_password_match),
("re.search", strong_password_search),
("re.findall", strong_password_findall),
)
test_inputs = ('abcAb1', 'abcAb1abcAb1abcAb100',
'abcAb1abcAb1abcAb10111', 'aaaAb1abcAb1abcAb100')
# --------------------------------- PROFILING AND BANCHMARK SETTINGS --------------------------------------
NUMBER_OF_RUNS = 1
CPROFILING_ON = False
BENCHMARK_ON = True
for description, method in test_methods:
print((GREEN_APPLE + RED_APPLE) * 5)
for test_input in test_inputs:
if CPROFILING_ON:
print(f'{description} cProfiling: ', cProfile.run("method(test_input)"))
if BENCHMARK_ON:
print(f'{description} Benchmark: ', timeit.Timer(
f'for i in range({NUMBER_OF_RUNS}): {method(test_input)}', 'gc.enable()').timeit())
if method(test_input):
print(f'{GREEN_APPLE} {description}: "{test_input}" is a strong password.')
else:
print(f'{RED_APPLE} {description}: "{test_input}" is not a strong password.')
</code></pre>
<h3>Output</h3>
<pre><code>
re.match Benchmark: 1.8437564770000001
re.match: "abcAb1" is a strong password.
re.match Benchmark: 1.9900512190000006
re.match: "abcAb1abcAb1abcAb100" is a strong password.
re.match Benchmark: 1.782858269
re.match: "abcAb1abcAb1abcAb10111" is not a strong password.
re.match Benchmark: 1.8016775740000002
re.match: "aaaAb1abcAb1abcAb100" is not a strong password.
re.search Benchmark: 1.8374795240000008
re.search: "abcAb1" is a strong password.
re.search Benchmark: 1.8352807049999988
re.search: "abcAb1abcAb1abcAb100" is a strong password.
re.search Benchmark: 1.8023251919999996
re.search: "abcAb1abcAb1abcAb10111" is not a strong password.
re.search Benchmark: 1.9213070860000006
re.search: "aaaAb1abcAb1abcAb100" is not a strong password.
re.findall Benchmark: 1.7806425130000019
re.findall: "abcAb1" is a strong password.
re.findall Benchmark: 1.836686480000001
re.findall: "abcAb1abcAb1abcAb100" is a strong password.
re.findall Benchmark: 1.8053996060000017
re.findall: "abcAb1abcAb1abcAb10111" is not a strong password.
re.findall Benchmark: 1.8203372360000003
re.findall: "aaaAb1abcAb1abcAb100" is not a strong password.
</code></pre>
<hr />
<p>If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of <a href="https://regex101.com/r/OHLPNG/1/" rel="nofollow noreferrer">regex101.com</a>. If you'd like, you can also watch in <a href="https://regex101.com/r/OHLPNG/1/debugger" rel="nofollow noreferrer">this link</a>, how it would match against some sample inputs.</p>
<hr />
<h3>RegEx Circuit</h3>
<p><a href="https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24" rel="nofollow noreferrer">jex.im</a> visualizes regular expressions:</p>
<p><a href="https://i.stack.imgur.com/7UU1X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7UU1X.png" alt="enter image description here" /></a></p>
<h3>Source</h3>
<p><a href="https://leetcode.com/problems/strong-password-checker/" rel="nofollow noreferrer">Strong Password Checker</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T08:00:08.873",
"Id": "451024",
"Score": "2",
"body": "ugh... I vehemently object to the LeetCode challenge for having a really crappy definition of \"strong password\". [These are good guidelines.](https://spycloud.com/new-nist-guidelines/). Rules #1 and #2 actually make your passwords worse and less safe."
}
] |
[
{
"body": "<h1>Imports</h1>\n\n<p>I notice you import <code>re</code> <em>three</em> times, once for each password check function. Why? Just import the library once at the top of the file, and you can use it in all of your functions.</p>\n\n<h1>Returning Booleans</h1>\n\n<p>Instead of returning <code>True</code> or <code>False</code> based on the result of the expression, simply return the expression. It results to a boolean anyway, so returning <code>True</code> and <code>False</code> is unnecessary; just return the expression.</p>\n\n<h1>DRY (Don't Repeat Yourself)</h1>\n\n<p>You have three functions that essentially perform the same task, just with <em>very slightly</em> different function calls. You can compress these regex checks into one method. Then you can pass what type of check you want to perform on the password. See below.</p>\n\n<pre><code>import re\n\ndef strong_password_check(password: str, type_of_check: str) -> bool:\n \"\"\"\n Accepts a password and the type of check to perform on the password\n\n :param password: Password to check\n :param type_of_check: How to check the password. Has to be \"match\", \"search\", or \"findall\"\n\n \"\"\"\n regex = r'^(?!.*([a-z])\\1\\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{6,20}$'\n if type_of_check == \"match\":\n return re.match(regex, password) is not None\n if type_of_check == \"search\":\n return re.search(regex, password) is not None\n if type_of_check == \"findall\":\n return re.findall(regex, password) != []\n</code></pre>\n\n<h1>Test Cases</h1>\n\n<p>Not really sure the usefulness of red and green apples. Again, importing <code>cProfile</code> and <code>timeit</code> should go at the top of the program.</p>\n\n<p>I see you're checking for performance, but not for the actual strength of the password. Would your program agree that <code>Password123</code> is a good password? Any security professional worth his salt wouldn't agree.</p>\n\n<p>I suggest that you use the <a href=\"https://en.wikipedia.org/wiki/Kolmogorov_complexity\" rel=\"nofollow noreferrer\">Kolmgorov Complexity</a> to check the strength of the password.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T22:24:36.740",
"Id": "231284",
"ParentId": "231214",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231284",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:26:16.067",
"Id": "231214",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"strings",
"regex"
],
"Title": "Strong Password Checker (Python)"
}
|
231214
|
<p>Recently I rewrote some methods/functions written by a previous developer mostly due to the fact that the previous implementation overdid the whole 'OO' thing, and used inheritance inappropriately. The code also leaked memory like crazy in production long running tasks, so my rewritten code is a response to that, by being more <strong>functional</strong>, less <strong>OO</strong>, less <strong>state</strong>, hopefully less <strong>leakage</strong>.</p>
<pre><code># This is app/lib/lonestar_bigcommerce.rb
# to use these functions,
# do require 'lonestar_bigcommerce.rb'
# include LonestarBigcommerce
# from anywhere in the rails application
module LonestarBigcommerce
include Temporary
# enumerable, supports .to_a(), each(), etc
# https://thoughtbot.com/blog/modeling-a-paginated-api-as-a-lazy-stream
def bigcommerce_api_v3_get_customers_by_shop(shop, options = {})
params = options.fetch(:params, {})
raise if params['page'] || params['limit'] # prevent manual pagination attempt
pages = options[:pages] # depth to crawl, how many pages
Enumerator.new do |yielder|
params[:page] = 1
params[:limit] = '250'
loop do
r1 = bigcommerce_get_request('https://api.bigcommerce.com' \
"/stores/#{shop.uid}/v3/customers?" +
params.to_query,
shop)
raise StopIteration unless bigcommerce_api_v3_collection_result_valid?(r1)
JSON.parse(r1.body)['data'].map { |item| yielder << item }
# theres one possible optimization here, to save one http reqeust
raise StopIteration if pages && params[:page] >= pages
params[:page] += 1
end
end.lazy
end
def hubspot_api_v1_get_contact_by_vid(vid, shop, options = {})
params = options.fetch(:params, {})
r1 = hubspot_get_request("https://api.hubapi.com/contacts/v1/contact/vid/#{vid}/profile", shop)
JSON.parse(r1.body)
end
def hubspot_api_v1_get_contact_by_email(email, shop, options = {})
params = options.fetch(:params, {})
r1 = hubspot_get_request("https://api.hubapi.com/contacts/v1/contact/email/#{email}/profile", shop)
JSON.parse(r1.body)
end
# @private
def default_hubspot_property_group(shop)
{
:name => "#{shop.uid}customerdata",
:displayName => "#{shop.domain} Customer Data"
}
end
def hubspot_api_v1_update_contact_by_email(property, email, shop, options = {})
recursive = options.fetch(:recursive, nil)
group_name = options.fetch(:group_name, nil)
group_label = options.fetch(:group_label, nil)
retries ||=0
hubspot_post_request(
"https://api.hubapi.com/contacts/v1/contact/email/#{email}/profile",
shop,
body: { :properties => [ property ] }
)
rescue RuntimeError => err
if recursive && err.message=~/PROPERTY_DOESNT_EXIST/ && retries < 2
hubspot_api_v1_create_property(
property[:property], shop, recursive: true,
group_name: group_name, group_label: group_label
)
retries+=1
retry
end
raise
end
def hubspot_api_v1_create_property(label, shop, options = {})
retries ||= 0
name = options.fetch(:name, label.parameterize.underscore)
group_name = options.fetch(:group_name, default_hubspot_property_group(shop)[:name])
group_label = options.fetch(:group_label, default_hubspot_property_group(shop)[:displayName])
recursive = options.fetch(:recursive, nil)
r1 = hubspot_post_request(
'https://api.hubapi.com/properties/v1/contacts/properties',
shop,
body: {
:name => name,
:label => label,
:description => options.fetch(:description, nil),
:groupName => group_name,
:type => "string",
:fieldType => "text"
}
)
JSON.parse(r1.body)
rescue RuntimeError => err
if recursive && err.message =~ /property group.*does not exist/
retries+=1
hubspot_api_v1_create_group(group_name, group_label, shop)
retry if retries < 2
end
raise
end
def hubspot_api_v1_create_group(group_name, group_label, shop)
r1 = hubspot_post_request(
'https://api.hubapi.com/properties/v1/contacts/groups',
shop,
body: { :name => group_name, :dislpayName => group_label })
JSON.parse(r1.body)
end
def maybe_cache_http_requests(cassette, options = {})
options.slice!(:record)
if ENV['CACHE_HTTP_REQUESTS'] == '1'
require 'vcr'
VCR.configure do |config|
config.cassette_library_dir = 'vcr_cassettes'
config.hook_into :webmock
config.allow_http_connections_when_no_cassette = true
end
VCR.use_cassette(cassette, options) do
yield
end
else
yield
end
end
def log(str)
Rails.logger.debug "DB8899 #{str}"
end
# @private
def bigcommerce_get_request(url, shop, _options = {})
r1 = net_http_request(
url,
headers:
bigcommerce_headers.merge(bigcommerce_headers_for_shop(shop))
)
describe_bigcommerce_response(r1)
r1
end
# @private
def hubspot_get_request(url, shop, _options = {})
retries ||= 0
r1 = net_http_request(
url,
headers: hubspot_headers.merge(hubspot_headers_for_shop(shop))
)
describe_hubspot_response(r1)
r1
rescue RuntimeError => e
retries += 1
if e.message =~ /is expired\! expiresAt/ && retries < 2
renew_hubspot_access_token(shop)
retry
end
raise
end
def renew_hubspot_access_token(shop)
#`curl -d 'grant_type=refresh_token&client_id=a&client_secret=a&refresh_token=a'
# -X POST -v https://api.hubapi.com/oauth/v1/token`
log medium_indent + ">>POST https://api.hubapi.com/oauth/v1/token"
r1 = JSON.parse(
Net::HTTP.post_form(
URI('https://api.hubapi.com/oauth/v1/token'),
{ "grant_type" => "refresh_token",
"client_id" => ENV['HUBSPOT_CLIENT_ID'],
"client_secret" => ENV['HUBSPOT_CLIENT_SECRET'],
"refresh_token" => shop.hubspot_site.refresh_token }
).body
)
shop.hubspot_site.update_columns(
access_token: r1["access_token"],
expires_at: Time.now + r1["expires_in"].to_i
)
end
# @private
def hubspot_post_request(url, shop, options = {})
retries ||= 0
r1 = net_http_request(
url,
headers: hubspot_headers.merge(hubspot_headers_for_shop(shop)),
body: options[:body],
type: :post,
allowed_responses: [Net::HTTPOK, Net::HTTPNoContent]
)
describe_hubspot_response(r1)
r1
rescue RuntimeError => e
retries += 1
if e.message =~ /is expired\! expiresAt/ && retries < 2
renew_hubspot_access_token(shop)
retry
end
raise
end
# @private
def hubspot_put_request(url, shop, options = {})
r1 = net_http_request(
url,
shop,
headers: hubspot_headers.merge(hubspot_headers_for_shop(shop)),
body: options[:body],
type: :put
)
describe_hubspot_response(r1)
JSON.parse(r1)
end
# @private
def bigcommerce_headers
{
'accept': 'application/json',
'content-type': 'application/json'
}
end
# @private
def bigcommerce_headers_for_shop(shop)
{
'x-auth-client': ENV['BIGCOMMERCE_CLIENT_ID'],
'x-auth-token': shop.bigcommerce_token
}
end
# @private
def describe_bigcommerce_response(response)
msg = "#{http_logging_prefix_in} #{response.message} (#{response.class})"
if response.class == Net::HTTPConflict
msg = "#{http_logging_prefix_in} NOK (existed)"
elsif response.class == Net::HTTPNoContent
msg = "#{http_logging_prefix_in} OK"
end
log medium_indent + msg
msg
end
# @private
def medium_indent
' ' * 10
end
# @private
def http_logging_prefix_in
'<<'
end
# @private
def http_logging_prefix_out
'>>'
end
# @private
# irb(main):004:0> "What is your birthday?".parameterize.underscore
#=> "what_is_your_birthday"
def strip_spaces(str)
str.parameterize.underscore
end
# @private
def describe_hubspot_response(response)
msg = "#{http_logging_prefix_in} #{response.message} (#{response.class})"
if response.class == Net::HTTPConflict
msg = "#{http_logging_prefix_in} NOK (existed)"
elsif response.class == Net::HTTPNoContent
msg = "#{http_logging_prefix_in} OK"
end
log medium_indent + msg
msg
end
# @private
def hubspot_headers
{
:accept => 'application/json',
:'Content-Type' => 'application/json'
}
end
# @private
def hubspot_headers_for_shop(shop)
{ :Authorization => "Bearer #{shop.hubspot_site.access_token}" }
end
# @private
def net_http_request(url, options = {})
retries ||= 0
type = options.fetch(:type, :get)
allowed_responses = options.fetch(:allowed_responses, [Net::HTTPOK] )
body = options.fetch(:body, {})
headers = options.fetch(:headers, [])
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri) if type == :get
request = Net::HTTP::Post.new(uri) if type == :post
request = Net::HTTP::Put.new(uri) if type == :put
request.body = body.to_json if (type != :get && body.present?)
headers.each { |key, value| request[key.to_s.downcase] = value }
log medium_indent + http_logging_prefix_out + type.to_s.upcase + ':' + url
r1 = http.request(request)
raise "#{r1.inspect} #{r1&.body}" unless allowed_responses.include?(r1.class) #r1.is_a?(Net::HTTPOK)
r1
rescue Net::HTTPTooManyRequests
retries += 1
log medium_indent + '!!!!!!!! Net::HTTPTooManyRequests, will retry'
sleep_a_bit
retry if retries <= 3
raise
end
# @private
def sleep_a_bit
sleep rand(0..1.0)
end
# @private
def bigcommerce_api_v3_collection_result_valid?(result)
result.class == Net::HTTPOK && JSON.parse(result.body)['meta']['pagination']['count'].positive?
end
end
```
Tests
```ruby
# this is test/lonestar_bigcommerce_test.rb,
# the test file that tests the corresponding app/lib/ file.
# to run tests do bundle exec rake test
require 'test_helper'
require 'lonestar_bigcommerce'
class DummyClass
include LonestarBigcommerce
end
class LonestarBigcommerceTest < ActiveSupport::TestCase
test 'bigcommerce_api_v3_get_customers_by_shop_a' do
# when theres less than a pageful of results
# ends up making one get request, plus one to realize theres no more
# limit 250 freeman "count 16 total": 16, total_pages": 1
VCR.use_cassette("#{self.class}_#{__method__}") do
dummy = DummyClass.new
r1 = dummy.bigcommerce_api_v3_get_customers_by_shop(create(:shop, :rbxboxing), params: { :'name:like' => 'freeman' })
r2 = r1.to_a
assert_equal 16, r2.size
assert_equal 'Aviva', r2[0]['first_name']
end
end
test 'bigcommerce_api_v3_get_customers_by_shop_b' do
# when theres more than 1 page of results
# ends up making two get requests, plus one to realize theres no more
# limit 250 ree count 250 "total": 257, total_pages": 2
VCR.use_cassette("#{self.class}_#{__method__}") do
dummy = DummyClass.new
r1 = dummy.bigcommerce_api_v3_get_customers_by_shop(create(:shop, :rbxboxing), params: { :'name:like' => 'ree' })
assert_equal 257, r1.to_a.size
end
end
test 'bigcommerce_api_v3_get_customers_by_shop_c' do
# when theres zero results
VCR.use_cassette("#{self.class}_#{__method__}") do
dummy = DummyClass.new
r1 = dummy.bigcommerce_api_v3_get_customers_by_shop(create(:shop, :rbxboxing), params: { :'name:like' => 'Nonexistantname' })
assert_equal 0, r1.to_a.size
end
end
test 'hubspot_api_v1_get_contact_by_vid' do
VCR.use_cassette("#{self.class}_#{__method__}") do
dummy = DummyClass.new
r1 = dummy.hubspot_api_v1_get_contact_by_vid(32051, create(:shop, :rbxboxing) )
assert_equal 32051, r1["vid"]
assert_equal 125, r1["properties"].size
end
end
test 'hubspot_api_v1_get_contact_by_email' do
VCR.use_cassette("#{self.class}_#{__method__}") do
dummy = DummyClass.new
r1 = dummy.hubspot_api_v1_get_contact_by_email('ka@gmail.com', create(:shop, :rbxboxing) )
assert_equal 'kalish.nd@gmail.com', r1["properties"]["email"]["value"]
assert_equal 7164201, r1["vid"]
end
end
# when Events::OrderCreated::TOPIC
# Events::OrderCreated.new(event).process!
# when Events::OrderUpdated::TOPIC
# Events::OrderUpdated.new(event).process!
# when Events::CustomerCreated::TOPIC
# -> Events::CustomerCreated.new(event).process!
# when Events::CustomerUpdated::TOPIC
# Events::CustomerUpdated.new(event).process!
# when Events::CustomerFullSync::TOPIC
# Events::CustomerFullSync.new(event).process!
# when Events::CartAbandoned::TOPIC
# Events::CartAbandoned.new(event).process!
test 'custom fields handled during background processing scenario a' do
VCR.use_cassette("#{self.class}_#{__method__}") do
event = create(:event, :rbxboxing, :topic_store_customer_created)
Events::CustomerCreated.new(event).process!
end
end
def test_hubspot_api_v1_create_group
VCR.use_cassette("#{self.class}_#{__method__}") do
shop = create(:shop, :hsfbc)
r1 = DummyClass.new.hubspot_api_v1_create_group("example002", "Example Name", shop)
assert_equal ({"portalId"=>6300907, "name"=>"example002", "displayOrder"=>8}), r1
end
end
# fails when group already exists
def test_hubspot_api_v1_create_group_fails_001
VCR.use_cassette("#{self.class}_#{__method__}") do
shop = create(:shop, :hsfbc)
err = assert_raises do
r1 = DummyClass.new.hubspot_api_v1_create_group("example001", "Example Name", shop)
end
assert_match /Net::HTTPConflict 409/, err.message
end
end
def test_hubspot_api_v1_create_property
VCR.use_cassette("#{self.class}_#{__method__}") do
shop = create(:shop, :hsfbc)
r1 = DummyClass.new.hubspot_api_v1_create_property(
"example001",
shop,
group_name: 'example001')
assert_match '{"name"=>"example001", "label"=>"example001", "description"=>"", "groupName"=>"example001", ', r1.to_s
end
end
# fails when group does not exist
def test_hubspot_api_v1_create_property_fails_001
VCR.use_cassette("#{self.class}_#{__method__}") do
shop = create(:shop, :hsfbc)
err = assert_raises do
DummyClass.new.hubspot_api_v1_create_property(
"example001",
shop)
end
assert_match /property group 1h2smorqcustomerdata does not exist/, err.message
end
end
# update contact success
def test_hubspot_api_v1_update_contact
VCR.use_cassette("#{self.class}_#{__method__}") do
r1 = DummyClass.new.hubspot_api_v1_update_contact_by_email(
{ :property => "example003", :value => "example003value"},
'ch@gr.com',
create(:shop, :hsfbc)
)
assert_equal Net::HTTPNoContent, r1.class
end
end
# update contact fails when property not exist
def test_hubspot_api_v1_update_contact_fails_001
VCR.use_cassette("#{self.class}_#{__method__}") do
err = assert_raises do
DummyClass.new.hubspot_api_v1_update_contact_by_email(
{ :property => "example004", :value => "example004value"},
'ch@gr.com',
create(:shop, :hsfbc)
)
end
assert_match /error":"PROPERTY_DOESNT_EXIST/, err.message
end
end
# update contact success when recursive needed and supplied
def test_hubspot_api_v1_update_contact_recursive
VCR.use_cassette("#{self.class}_#{__method__}") do
r1 = DummyClass.new.hubspot_api_v1_update_contact_by_email(
{ :property => "example004", :value => "example004value"},
'ch@gr.com',
create(:shop, :hsfbc),
recursive: true,
group_name: 'example005',
group_label: 'example005 label'
)
assert r1.is_a?(Net::HTTPNoContent)
end
end
end
</code></pre>
|
[] |
[
{
"body": "<pre><code>def bigcommerce_api_v3_get_customers_by_shop(shop, options = {})\n</code></pre>\n\n<p>Since you are only extracting a couple values from <code>options</code> here, consider using keyword params instead. It makes it more obvious what specific keys are used by the method, without needing to dig into the method body.</p>\n\n<hr>\n\n<pre><code>raise if params['page'] || params['limit'] # prevent manual pagination attempt\n</code></pre>\n\n<p>You should raise a specific error here, or at least include a message. Currently, you'll just get a <code>RuntimeError</code> with no message, and would need go to that line in the source code to figure out what is the actual error</p>\n\n<hr>\n\n<pre><code>r1 = hubspot_get_request(\"https://api.hubapi.com/contacts/v1/contact/vid/#{vid}/profile\", shop)\n</code></pre>\n\n<p>It's kinda nice to have URLs like this as constants. Of course, you do have to interpolate a value in there, but it can be done using the <code>%</code> operator as well (see <a href=\"https://stackoverflow.com/questions/28556946/percent-operator-string-interpolation\">https://stackoverflow.com/questions/28556946/percent-operator-string-interpolation</a>):</p>\n\n<pre><code># Note I changed #{} here to %{}\nHUBSPOT_USER_PROFILE_PATH = \"https://api.hubapi.com/contacts/v1/contact/vid/%{vid}/profile\"\n# ...\nr1 = hubspot_get_request(\n HUBSPOT_USER_PROFILE_PATH % { vid: vid },\n shop\n)\n</code></pre>\n\n<hr>\n\n<pre><code>:name => \"#{shop.uid}customerdata\",\n</code></pre>\n\n<p>You should use the shorter syntax for symbol keys, <code>name: \"#{shop.uid}customerdata\",</code></p>\n\n<hr>\n\n<pre><code>recursive = options.fetch(:recursive, nil)\n</code></pre>\n\n<p>Using <code>fetch</code> here is pointless, just use <code>options[:recursive]</code> which will return <code>nil</code> if the key isn't found anyway. But still, it's better to use keyword params anyway.</p>\n\n<hr>\n\n<p>This is as far as I'm gonna get right now, this is quite a long program and I have to head to work. But, those issues I outlined above are applicable in many parts of the program. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T14:04:07.570",
"Id": "459317",
"Score": "0",
"body": "hey thanks for reviewing the code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T17:13:02.720",
"Id": "232392",
"ParentId": "231215",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:26:47.767",
"Id": "231215",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"http"
],
"Title": "Easily interacting with two external apis"
}
|
231215
|
<p>I started learning compilers development and as pet project decided to implement c compiler.
The first step is implementing simplest lexer.
Also, I decided to try new programming language and chose go. This is my first go program and I will be grateful for any advice. Thanks.</p>
<pre><code>package lexer
import (
"errors"
"fmt"
"unicode"
)
type tokenType int
const (
EOF tokenType = iota
Identifier
NumericConstant
IntType
ReturnKeyword
OpenRoundBracket
CloseRoundBracket
OpenCurlyBracket
CloseCurlyBracket
Semicolon
)
type token struct {
tokenType tokenType
value string
}
type parser struct {
code []rune
currentIndex int
}
func (p *parser) nextToken() token {
p.skipSpaces()
if p.isEOF() {
return token{tokenType: EOF}
}
var newToken token
r := p.currentRune()
if unicode.IsLetter(r) {
newToken = p.parseLetterStartToken()
} else if unicode.IsNumber(r) {
newToken = p.parseNumberStartToken()
} else if r == '(' {
newToken = token{tokenType: OpenRoundBracket, value:string(r)}
} else if r == ')' {
newToken = token{tokenType: CloseRoundBracket, value:string(r)}
} else if r == '{' {
newToken = token{tokenType: OpenCurlyBracket, value:string(r)}
} else if r == '}' {
newToken = token{tokenType: CloseCurlyBracket, value:string(r)}
} else if r == ';' {
newToken = token{tokenType: Semicolon, value:string(r)}
} else {
errorText := fmt.Sprintf("Unexpected character: %c", r)
panic(errors.New(errorText))
}
p.currentIndex += 1
return newToken
}
func (p *parser) skipSpaces() {
if p.isEOF() {
return
}
for unicode.IsSpace(p.currentRune()) {
p.currentIndex += 1
if p.isEOF() {
return
}
}
}
func (p *parser) parseLetterStartToken() token {
startIndex := p.currentIndex
for unicode.IsLetter(p.currentRune()) || unicode.IsNumber(p.currentRune()) {
p.nextRune()
}
endIndex := p.currentIndex
tokenValue := string(p.code[startIndex: endIndex])
p.currentIndex -= 1
return letterStartToken(tokenValue)
}
func letterStartToken(tokenValue string) token {
var tokenType tokenType
switch tokenValue {
case "int":
tokenType = IntType
case "return":
tokenType = ReturnKeyword
default:
tokenType = Identifier
}
return token{tokenType:tokenType, value:tokenValue}
}
func (p *parser) parseNumberStartToken() token {
startIndex := p.currentIndex
for unicode.IsNumber(p.currentRune()) {
p.nextRune()
}
endIndex := p.currentIndex
tokenValue := string(p.code[startIndex: endIndex])
p.currentIndex -= 1
return token{tokenType: NumericConstant, value:tokenValue}
}
func (p parser) isEOF() bool {
return p.currentIndex >= len(p.code)
}
func (p parser) currentRune() rune {
return p.code[p.currentIndex]
}
func (p *parser) nextRune() rune {
p.currentIndex += 1
return p.currentRune()
}
func Tokenize(code []rune) []token {
parser := parser{code:code, currentIndex:0}
tokens := []token{}
for newToken := parser.nextToken(); newToken.tokenType != EOF; {
tokens = append(tokens, newToken)
newToken = parser.nextToken()
}
return tokens
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is a good start, but it is not finished yet. You still need to do:</p>\n\n<ul>\n<li>character literals</li>\n<li>string literals</li>\n<li>floating-point literals</li>\n<li>hexadecimal int literals</li>\n<li>int literals containing underscores</li>\n</ul>\n\n<p>I suggest you pick a copy of the current C standard and read through chapter 6, which contains the definitions for all these lexemes. Along with the reading, start to write unit tests for each of the lexeme rules, especially the edge cases.</p>\n\n<p>Your current code is well-structured, and you will be able to write the full lexer keeping the structure the same. I've written a very similar lexer <a href=\"https://github.com/rillig/pkglint/blob/master/textproc/lexer.go\" rel=\"nofollow noreferrer\">in my pkglint project</a>, and the corresponding unit tests in <code>lexer_test.go</code> in the same directory. Reading this code will bring you up to speed with your own lexer. To see how I use the lexer, look for <code>NewLexer</code> in the code.</p>\n\n<p>One aspect where my lexer differs from yours is that my lexer only remembers the remaining input string, whereas your lexer remembers the complete input string plus the current index. I chose my data structure since it uses the least amount of memory possible. Taking a subslice is an efficient operation in Go, therefore I haven't been bitten my the extra memory access that <code>l.rest = l.rest[1:]</code> needs (it updates both the start and the length of <code>l.rest</code>. Your code is more efficient in that it only increments the index.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T06:24:05.083",
"Id": "450870",
"Score": "0",
"body": "Thank you for your answer!\nI will definitely look at your project code\nThe only reason that my lexer has little functionality is I am going through series of articles (https://norasandler.com/2017/11/29/Write-a-Compiler.html) and the first practice task is to implement only these lexemes.\nI am not sure about substrings and memory managment. As I understand mystring = mystring[10:] will keep original mystring in memory because substring has pointer to original value and GC won't clear it (https://stackoverflow.com/questions/16909917/substrings-and-the-go-garbage-collector).\nAm I right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T06:41:20.027",
"Id": "450873",
"Score": "0",
"body": "Yes, you're right about the GC. The reason that I did it this way is that when I step through the parking code, I can immediately see the remaining string. That's more comfortable than doing searching for the character by counting characters on the screen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T09:42:16.100",
"Id": "451035",
"Score": "0",
"body": "Got it. Thanks for your help"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T17:15:33.960",
"Id": "231219",
"ParentId": "231218",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231219",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T16:56:44.457",
"Id": "231218",
"Score": "4",
"Tags": [
"go",
"lexer"
],
"Title": "Simplest lexer for c in go"
}
|
231218
|
<p>This code takes a list of words that all (pairwise) share at least one letter, e.g.</p>
<pre><code>words = ["forget", "fret", "for", "tort", "forge", "fore", "frog", "fort", "forte", "ogre"]
</code></pre>
<p>and creates what I'm calling a "sparse crossword" puzzle that looks like this.</p>
<pre><code>-------FORT
----------O
------F-FOR
----FROGR-T
----F-R-E--
--OFORGET--
--G-R-E----
FORTE------
--E--------
</code></pre>
<p>I'd greatly appreciate any feedback on either the algorithm for inserting words into the puzzle (which results is a pretty "formulaic" grid) and the general structure/style of the Python code as well.</p>
<pre><code>import enum
import itertools
import math
import numpy as np
import random
@enum.unique
class Direction(enum.Enum):
ACROSS = enum.auto()
DOWN = enum.auto()
def __str__(self):
return("ACROSS" if self is Direction.ACROSS else "DOWN")
def get_deltas(self):
delta_r = int(self == Direction.DOWN)
delta_c = int(self == Direction.ACROSS)
return(delta_r, delta_c)
@staticmethod
def random():
return random.choice(list(Direction))
class GridWord:
def __init__(self, word: str, r: int, c: int, direction: Direction):
if not isinstance(word, str):
raise TypeError("word must be a string")
if not (isinstance(r, int) and isinstance(c, int) and r >= 0 and c >= 0):
raise ValueError("Row and column positions must be positive integers")
if not isinstance(direction, Direction):
raise TypeError("Direction must be an enum of type Direction")
self.word = word.upper()
self.r1 = r
self.c1 = c
self.direction = direction
self.delta_r, self.delta_c = self.direction.get_deltas()
self.__len = len(self.word)
self.r2 = self.r1 + (self.__len - 1)* self.delta_r
self.c2 = self.c1 + (self.__len - 1)* self.delta_c
def __str__(self):
return(f"{self.word}, ({self.r1}, {self.c1}) -- ({self.r2}, {self.c2}), {self.direction}")
def __len__(self):
return(self.__len)
def __contains__(self, item):
if isinstance(item, str):
# The left operand is a string
return(item in self.word)
elif isinstance(item, tuple) and len(item) == 2 and isinstance(item[0], int) and isinstance(item[1], int):
# The left operand is a tuple that contains two integers, i.e. a
# coordinate pair
return(self.r1 <= item[0] and item[0] <= self.r2 and
self.c1 <= item[1] and item[1] <= self.c2)
else:
raise TypeError("'in <GridWord>' requires string or coordinate pair as left operand")
def __getitem__(self, item):
try:
return(self.word[item])
except:
raise
def intersects(self, other):
if not isinstance(other, GridWord):
raise TypeError("Intersection is only defined for two GridWords")
if self.direction == other.direction:
raise ValueError("Intersection is only defined for GridWords placed in different directions")
for idx1, letter1 in enumerate(self.word):
for idx2, letter2 in enumerate(other.word):
rr1 = self.r1 + idx1*self.delta_r
cc1 = self.c1 + idx1*self.delta_c
rr2 = other.r1 + idx2*self.delta_c # because the direction is reversed
cc2 = other.c1 + idx2*self.delta_r
if letter1 == letter2 and rr1 == rr2 and cc1 == cc2:
return(True)
return(False)
def overlaps(self, other):
if not isinstance(other, GridWord):
raise TypeError("Overlap check is only defined for two GridWords")
if self.direction == other.direction:
return((self.r1, self.c1) in other or (other.r1, other.c1) in self)
for idx, letter in enumerate(self.word):
rr = self.r1 + idx*self.delta_r
cc = self.c1 + idx*self.delta_c
if (rr, cc) in other:
return(True)
return(False)
def adjacent_to(self, other):
if not isinstance(other, GridWord):
raise TypeError("Adjacency is only defined for two GridWords")
if self.direction != other.direction:
return(False)
for delta in [-1, 1]:
for idx in range(self.__len):
r = self.r1 + idx*self.delta_r + delta*self.delta_c
c = self.c1 + idx*self.delta_c + delta*self.delta_r
if (r, c) in other:
return(True)
# (-1) point directly to the left of (or above) a word placed across
# (or down)
#
# (1) point directly to the right of (or below) a word placed across
# (or down)
if delta == -1:
r = self.r1 + delta * self.delta_r
c = self.c1 + delta * self.delta_c
elif delta == 1:
r = self.r2 + delta * self.delta_r
c = self.c2 + delta * self.delta_c
if (r, c) in other:
return(True)
return(False)
class Grid:
def __init__(self, num_rows = 50, num_cols = 50):
self.num_rows = num_rows
self.num_cols = num_cols
self.grid = np.full([self.num_rows, self.num_cols], "")
self.grid_words = []
def __str__(self):
s = ""
for i in range(self.num_rows):
for j in range(self.num_cols):
s += self.grid[i][j] if self.grid[i][j] != "" else "-"
s += "\n"
return(s)
def __approximate_center(self):
center = (math.floor(self.num_rows / 2), math.floor(self.num_cols / 2))
return(center)
def __insert_word(self, grid_word):
if not isinstance(grid_word, GridWord):
raise TypeError("Only GridWords can be inserted into the Grid")
delta_r, delta_c = grid_word.direction.get_deltas()
for idx, letter in enumerate(grid_word.word):
self.grid[grid_word.r1 + idx*delta_r, grid_word.c1 + idx*delta_c] = letter
self.grid_words.append(grid_word)
def __word_fits(self, word: str, r: int, c: int, d: Direction):
# Make sure we aren't inserting the word outside the grid
if ((d == Direction.DOWN and r + len(word) >= self.num_rows) or
(d == Direction.ACROSS and c + len(word) >= self.num_cols)):
return(False)
grid_word = GridWord(word, r, c, d)
check = False
for gw in self.grid_words:
if grid_word.adjacent_to(gw):
# If the word is adjacent to any other words in the grid, we can
# exit right away because it doesn't fit
return(False)
if grid_word.overlaps(gw):
if d == gw.direction:
# If the word overlaps another word that is placed in the
# same direction, we can exit right away
return(False)
elif not grid_word.intersects(gw):
# If the word overlaps another word that is placed in the
# other direction but DOESN'T intersect it (i.e. the overlap
# doesn't happen on the same letter in each word), we can
# exit right away
return(False)
else:
check = True
else:
# If the word doesn't overlap the current word (already in the
# grid) that's being checked, we don't know yet whether or not
# we CAN or CANNOT place it on the grid
pass
return(check)
def __scan_and_insert_word(self, word):
if not isinstance(word, str):
raise TypeError("Only strings can be inserted into the puzzle by scanning")
if len(self.grid_words) == 0:
self.__insert_word(GridWord(word, *self.__approximate_center(), Direction.random()))
return(None)
for d, r, c in itertools.product(list(Direction), range(self.num_rows), range(self.num_cols)):
if self.__word_fits(word, r, c, d):
grid_word = GridWord(word, r, c, d)
self.__insert_word(grid_word)
break
def scan_and_insert_all_words(self, words):
for word in words:
self.__scan_and_insert_word(word)
def __randomly_insert_word(self, word):
if not isinstance(word, str):
raise TypeError("Only strings can be randomly inserted into the puzzle")
if len(self.grid_words) == 0:
self.__insert_word(GridWord(word, *self.__approximate_center(), Direction.random()))
return(None)
num_iterations = 0
while num_iterations <= 10000:
rand_r = random.randint(0, self.num_rows - 1)
rand_c = random.randint(0, self.num_cols - 1)
d = Direction.random()
if self.__word_fits(word, rand_r, rand_c, d):
grid_word = GridWord(word, rand_r, rand_c, d)
self.__insert_word(grid_word)
break
num_iterations += 1
def crop(self):
min_c = min([word.c1 for word in self.grid_words])
min_r = min([word.r1 for word in self.grid_words])
max_c = max([word.c2 for word in self.grid_words])
max_r = max([word.r2 for word in self.grid_words])
cropped_grid = Grid(max_r - min_r + 1, max_c - min_c + 1)
for grid_word in self.grid_words:
cropped_word = GridWord(grid_word.word, grid_word.r1 - min_r,
grid_word.c1 - min_c, grid_word.direction)
cropped_grid.__insert_word(cropped_word)
return(cropped_grid)
random.seed(1)
words = ["forget", "fret", "for", "tort", "forge", "fore", "frog", "fort", "forte", "ogre"]
g = Grid()
g.scan_and_insert_all_words(words)
print(g.crop())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T01:32:16.183",
"Id": "450845",
"Score": "1",
"body": "How are _FFORE_ or _FROGR_ words?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:31:02.293",
"Id": "450922",
"Score": "0",
"body": "@Reinderien That is ... a bug I thought I fixed, but obviously didn't (and didn't notice here). That's embarrassing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:37:24.763",
"Id": "450923",
"Score": "0",
"body": "It's okay it won't prevent you from having a meaningful review, with the caveat that CR feed back won't be expected to fix the bug if that's what you need help with. Such help comes from StackOverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:40:38.367",
"Id": "450924",
"Score": "0",
"body": "@Reinderien Thanks. No, that wasn't what I needed help with (since I didn't even notice it when I copied the grid into the question...) and I'm working on fixing it offline as we speak."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:41:42.797",
"Id": "450926",
"Score": "0",
"body": "If you manage to fix it before an answer is posted here, you're still free to edit the question."
}
] |
[
{
"body": "<h2>Validation</h2>\n\n<p>This:</p>\n\n<pre><code>words = [\"forget\", \"fret\", \"for\", \"tort\", \"forge\", \"fore\", \"frog\", \"fort\", \"forte\", \"ogre\"]\n</code></pre>\n\n<p>should probably receive some kind of validation to confirm that each word shares at least one letter. One simple way to do this is a <code>set</code>: iterate through each word, adding each letter of the word to the set. Then do a second iteration to ensure that the set intersects with each word.</p>\n\n<h2>Enum name</h2>\n\n<pre><code>def __str__(self):\n return(\"ACROSS\" if self is Direction.ACROSS else \"DOWN\")\n</code></pre>\n\n<p>is not necessary. You should be able to simply do:</p>\n\n<pre><code>def __str__(self):\n return self.name\n</code></pre>\n\n<h2>Implicit tuple</h2>\n\n<p>This:</p>\n\n<pre><code> return(delta_r, delta_c)\n</code></pre>\n\n<p>does not require parens, nor does this:</p>\n\n<pre><code> return(True)\n</code></pre>\n\n<h2>Dunders</h2>\n\n<pre><code> self.__len = len(self.word)\n</code></pre>\n\n<p>Don't name this variable with two underscores - that usually has a special meaning. (The same applies to <code>__word_fits</code>.) Even so, you don't need this variable at all - just use <code>len(self.word)</code> in your <code>__len__</code> method.</p>\n\n<h2>Combined comparison</h2>\n\n<pre><code>self.r1 <= item[0] and item[0] <= self.r2 and\nself.c1 <= item[1] and item[1] <= self.c2\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>self.r1 <= item[0] <= self.r2 and\nself.c1 <= item[1] <= self.c2\n</code></pre>\n\n<h2>Don't no-op <code>except</code></h2>\n\n<p>Delete this try block, since it does nothing:</p>\n\n<pre><code> try:\n return(self.word[item])\n except: \n raise\n</code></pre>\n\n<h2>Coordinate nomenclature</h2>\n\n<p><code>rr1</code> and <code>cc1</code> and their ilk are probably better expressed as <code>yy1</code> and <code>xx1</code>, etc.</p>\n\n<h2>Overlap detection</h2>\n\n<p>You have some long loops to detect spatial overlap. Instead, consider building up an index structure that is composed of nested lists. Indexing <code>[y][x]</code> into the list can get you an inner structure that contains all words at that location, and for each of them, the offset into the word. This will be fairly cheap memory-wise and will greatly improve your runtime. It will also make <code>__word_fits</code> much nicer.</p>\n\n<h2>Or semantics</h2>\n\n<pre><code> s += self.grid[i][j] if self.grid[i][j] != \"\" else \"-\"\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>s += self.grid[i][j] or '-'\n</code></pre>\n\n<h2>Grid.<strong>str</strong></h2>\n\n<p>Much ink has been spilled on the evils of successive immutable string concatenation. This is what <code>StringIO</code> is built for, so do that instead.</p>\n\n<p>Or, if you're feeling fancy, write a long, horrible <code>'\\n'.join(...)</code> comprehension.</p>\n\n<h2>Branch trimming</h2>\n\n<pre><code> if d == gw.direction:\n return(False)\n elif not grid_word.intersects(gw):\n return(False)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if d == gw.direction or not grid_word.intersects(gw):\n return False\n</code></pre>\n\n<p>And delete this branch entirely (you can keep the comment of course):</p>\n\n<pre><code> else:\n # If the word doesn't overlap the current word (already in the\n # grid) that's being checked, we don't know yet whether or not\n # we CAN or CANNOT place it on the grid\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T18:58:37.397",
"Id": "451200",
"Score": "0",
"body": "Thanks for all the comments. I'm still sorting through all of these. In response to the \"Don't no-op except\" comment, I put that block there to implement/pass through the appropriate IndexError when indexing into `self.word`. Does that make more sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T19:24:15.483",
"Id": "451203",
"Score": "0",
"body": "Not really. What you've written has no effect. The default is for exceptions to \"pass through\" everything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T20:04:07.743",
"Id": "451208",
"Score": "1",
"body": "Good point. If `self.word[item]` raises an exception it'll just get thrown in the program anyway. Makes sense, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T21:32:00.137",
"Id": "451403",
"Score": "0",
"body": "I understand your comment about my naming of `__len` (Thanks!) but I don't understand how that applies to the `__word_fits` method. My intention was for `__word_fits` to use name scrambling on all methods of `Grid` that aren't meant to be accessed directly from anywhere outside the class. An [encapsulated \"private method\"](https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private) so to speak (even though I know Python doesn't have those per se)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T21:35:39.190",
"Id": "451404",
"Score": "0",
"body": "Single-underscore methods are private-by-agreement, and there's no such thing as enforced-private. Linters will warn you against accessing single-underscore members from outside of the class. Double underscore indicates name mangling, which is something else - read https://docs.python.org/3/tutorial/classes.html#private-variables"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T21:37:20.583",
"Id": "451405",
"Score": "0",
"body": "Thanks. Single underscore naming is definitely what I meant to use."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T02:49:27.803",
"Id": "231294",
"ParentId": "231222",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231294",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:07:30.930",
"Id": "231222",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python 3 code to generate simple crossword puzzles from a list of words/anagrams"
}
|
231222
|
<p>Within <a href="https://nl.mathworks.com/help/images/ref/strel.html#bu7pnvk-1" rel="nofollow noreferrer">Matlab</a> there exist a function to create a structuringselement in the form of a line.<br>
<code>SE = strel('line',len,deg)</code> creates a linear structuring element that is symmetric with respect to the neighborhood center, with approximate length <code>len</code> and angle <code>deg</code>. For a couple of morphological operations I need to filter out horizontal-, vertical and other angles of lines. Within <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html#structuring-element" rel="nofollow noreferrer">Python's</a> <code>CV2</code> a similiar function does not exist. Therefore, I wanted to recreate this function in Python</p>
<p>My code:</p>
<pre><code>import math
import numpy as np
# bresenham function is the accepted answer of SO's post https://stackoverflow.com/questions/23930274/list-of-coordinates-between-irregular-points-in-python
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
x, y = x0, y0
sx = -1 if x0 > x1 else 1
sy = -1 if y0 > y1 else 1
if dx > dy:
err = dx / 2.0
while x != x1:
points.append((x, y))
err -= dy
if err < 0:
y += sy
err += dx
x += sx
else:
err = dy / 2.0
while y != y1:
points.append((x, y))
err -= dx
if err < 0:
x += sx
err += dy
y += sy
points.append((x, y))
return points
def strel_line(length, degrees):
if length >= 1:
theta = degrees * np.pi / 180
x = round((length - 1) / 2 * np.cos(theta))
y = -round((length - 1) / 2 * np.sin(theta))
points = bresenham(-x, -y, x, y)
points_x = [point[0] for point in points]
points_y = [point[1] for point in points]
n_rows = int(2 * max([abs(point_y) for point_y in points_y]) + 1)
n_columns = int(2 * max([abs(point_x) for point_x in points_x]) + 1)
strel = np.zeros((n_rows, n_columns))
rows = ([point_y + max([abs(point_y) for point_y in points_y]) for point_y in points_y])
columns = ([point_x + max([abs(point_x) for point_x in points_x]) for point_x in points_x])
idx = []
for x in zip(rows, columns):
idx.append(np.ravel_multi_index((int(x[0]), int(x[1])), (n_rows, n_columns)))
strel.reshape(-1)[idx] = 1
return strel
if __name__=='__main__':
strel = strel_line(15, 105)
print(strel)
print(strel.shape)
</code></pre>
<p>Output:</p>
<pre><code>[[1. 0. 0. 0. 0.]
[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 0. 0. 1.]]
</code></pre>
<p>Do you see any ways to write my function more efficiently?</p>
|
[] |
[
{
"body": "<h2>Type hints</h2>\n\n<pre><code>def bresenham(x0, y0, x1, y1):\n</code></pre>\n\n<p>should be, at a guess,</p>\n\n<pre><code>def bresenham(x0: float, y0: float, x1: float, y1: float) -> List[float]:\n</code></pre>\n\n<p>or maybe <code>int</code>, but you get the idea.</p>\n\n<h2>Type promotion</h2>\n\n<p>You don't need decimals here:</p>\n\n<pre><code>err = dx / 2.0\n</code></pre>\n\n<p><code>/2</code> will accomplish the same thing.</p>\n\n<h2>Termination</h2>\n\n<p>What happens if you call <code>bresenham(0, 0, 9.5, 9.5)</code>? I suspect that it will iterate infinitely and hang, due to</p>\n\n<pre><code> while x != x1:\n</code></pre>\n\n<p>One way to fix this, if your algorithm permits, is - rather than making an <code>sx</code> dependent on the comparison of <code>x0</code> and <code>x1</code>, simply swap <code>x0</code> and <code>x1</code> if they're in the wrong order. Then, rather than <code>!=</code>, use <code><</code>, and you don't have to calculate <code>sx</code>.</p>\n\n<h2>Use a generator</h2>\n\n<p>For some use cases this will dramatically decrease memory consumption. Instead of building up <code>points</code> in memory, just <code>yield</code> whenever you have a point. Allow the caller to decide whether they want to cast to a <code>list</code>, a <code>tuple</code>, or just iterate over the points.</p>\n\n<h2>Int casting</h2>\n\n<pre><code> n_rows = int(2 * max([abs(point_y) for point_y in points_y]) + 1)\n</code></pre>\n\n<p>is overambitious in application of the <code>int</code> cast. The multiplication and addition don't need to be done in floating-point math, so you can instead do</p>\n\n<pre><code> n_rows = 2 * int(max(abs(point_y) for point_y in points_y)) + 1\n</code></pre>\n\n<p>Also note that you shouldn't pass a <code>list</code> to <code>max</code> - just pass the generator directly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T01:28:27.733",
"Id": "231236",
"ParentId": "231225",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:36:22.070",
"Id": "231225",
"Score": "3",
"Tags": [
"python",
"opencv"
],
"Title": "Create a structuringselement in the form of a line with a certain degree and length"
}
|
231225
|
<p>I wrote a simple logger class for my project. Some key points:</p>
<ul>
<li>The interface is heavily inspired by Java's logging libraries (you can tell from the getters/setters that I'm a Java programmer). In particular I'm using printf style functions instead of std::ostream style, which I don't like very much.</li>
<li>verify is a macro similar to assert, but instead of aborting it throws std::logic_error and cannot be disabled with NDEBUG.</li>
<li>The heavy lifting is done by Handler, which I didn't include here because it's quite a lot of code and it's not finished.</li>
</ul>
<p>Without further ado, here's log.hpp</p>
<pre><code>#pragma once
#include "verify.hpp"
#include <cassert>
#include <ostream>
#include <utility>
namespace bran {
enum class log_severity : unsigned {
INHERIT,
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL
};
std::ostream& operator<<(std::ostream& out, log_severity severity);
template<class Handler>
class basic_logger;
template<class Handler>
void swap(basic_logger<Handler>& a, basic_logger<Handler>& b) noexcept;
template<class Handler>
class basic_logger {
public:
explicit basic_logger(const std::string& name, basic_logger<Handler>* parent, Handler* handler);
explicit basic_logger(const std::string& name, basic_logger<Handler>& parent);
explicit basic_logger(const std::string& name, Handler& handler);
basic_logger(basic_logger&& l) noexcept;
basic_logger(const basic_logger&) = delete;
~basic_logger() = default;
basic_logger& operator=(basic_logger l) noexcept;
[[nodiscard]] inline std::string get_name() const noexcept;
void set_threshold(log_severity threshold);
[[nodiscard]] inline log_severity get_threshold() const noexcept;
void set_handler(Handler* handler);
[[nodiscard]] inline Handler* get_handler() const noexcept;
void set_parent(basic_logger<Handler>* parent);
[[nodiscard]] inline basic_logger<Handler>* get_parent() const noexcept;
[[nodiscard]] inline bool is_trace() const noexcept;
[[nodiscard]] inline bool is_debug() const noexcept;
[[nodiscard]] inline bool is_info() const noexcept;
[[nodiscard]] inline bool is_warn() const noexcept;
[[nodiscard]] inline bool is_error() const noexcept;
template<class... T>
inline void trace(const std::string& message, T... args);
template<class... T>
inline void debug(const std::string& message, T... args);
template<class... T>
inline void info(const std::string& message, T... args);
template<class... T>
inline void warn(const std::string& message, T... args);
template<class... T>
inline void error(const std::string& message, T... args);
template<class... T>
inline void fatal(const std::string& message, T... args);
private:
std::string name;
log_severity threshold;
basic_logger<Handler>* parent;
Handler* handler;
template<class... T>
inline void log(log_severity severity, const std::string& message, T... args);
public:
friend void swap<Handler>(basic_logger<Handler>& a, basic_logger<Handler>& b) noexcept;
};
}
template<class Handler>
bran::basic_logger<Handler>::basic_logger(const std::string& name, basic_logger<Handler>* parent, Handler* handler)
: name{name}, parent{parent}, handler{handler} {
verify(!name.empty() && (parent != nullptr || handler != nullptr));
if (parent != nullptr) {
threshold = log_severity::INHERIT;
} else {
threshold = log_severity::TRACE;
}
}
template<class Handler>
bran::basic_logger<Handler>::basic_logger(const std::string& name, basic_logger<Handler>& parent)
: basic_logger{name, &parent, nullptr} {
}
template<class Handler>
bran::basic_logger<Handler>::basic_logger(const std::string& name, Handler& handler)
: basic_logger{name, nullptr, &handler} {
}
template<class Handler>
bran::basic_logger<Handler>::basic_logger(basic_logger&& l) noexcept {
swap(*this, l);
}
template<class Handler>
bran::basic_logger<Handler>& bran::basic_logger<Handler>::operator=(basic_logger l) noexcept {
swap(*this, l);
return *this;
}
template<class Handler>
std::string bran::basic_logger<Handler>::get_name() const noexcept {
return name;
}
template<class Handler>
void bran::basic_logger<Handler>::set_threshold(log_severity threshold) {
verify(threshold != log_severity::INHERIT || parent != nullptr);
this->threshold = threshold;
}
template<class Handler>
bran::log_severity bran::basic_logger<Handler>::get_threshold() const noexcept {
assert(threshold != log_severity::INHERIT || parent != nullptr);
return threshold == log_severity::INHERIT ? parent->get_threshold() : threshold;
}
template<class Handler>
void bran::basic_logger<Handler>::set_handler(Handler* handler) {
verify(handler != nullptr || parent != nullptr);
this->handler = handler;
}
template<class Handler>
Handler* bran::basic_logger<Handler>::get_handler() const noexcept {
assert(handler != nullptr || parent != nullptr);
return handler == nullptr ? parent->get_handler() : handler;
}
template<class Handler>
void bran::basic_logger<Handler>::set_parent(basic_logger<Handler>* parent) {
verify(parent != nullptr || (handler != nullptr && threshold != log_severity::INHERIT));
this->parent = parent;
}
template<class Handler>
bran::basic_logger<Handler>* bran::basic_logger<Handler>::get_parent() const noexcept {
return parent;
}
template<class Handler>
bool bran::basic_logger<Handler>::is_trace() const noexcept {
return get_threshold() <= log_severity::TRACE;
}
template<class Handler>
bool bran::basic_logger<Handler>::is_debug() const noexcept {
return get_threshold() <= log_severity::DEBUG;
}
template<class Handler>
bool bran::basic_logger<Handler>::is_info() const noexcept {
return get_threshold() <= log_severity::INFO;
}
template<class Handler>
bool bran::basic_logger<Handler>::is_warn() const noexcept {
return get_threshold() <= log_severity::WARN;
}
template<class Handler>
bool bran::basic_logger<Handler>::is_error() const noexcept {
return get_threshold() <= log_severity::ERROR;
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::trace(const std::string& message, T... args) {
log(log_severity::TRACE, message, args...);
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::debug(const std::string& message, T... args) {
log(log_severity::DEBUG, message, args...);
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::info(const std::string& message, T... args) {
log(log_severity::INFO, message, args...);
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::warn(const std::string& message, T... args) {
log(log_severity::WARN, message, args...);
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::error(const std::string& message, T... args) {
log(log_severity::ERROR, message, args...);
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::fatal(const std::string& message, T... args) {
log(log_severity::FATAL, message, args...);
}
template<class Handler>
template<class... T>
void bran::basic_logger<Handler>::log(log_severity severity, const std::string& message, T... args) {
if (get_threshold() > severity) {
return;
}
get_handler()->log(*this, severity, message, args...);
}
template<class Handler>
void bran::swap(basic_logger<Handler>& a, basic_logger<Handler>& b) noexcept {
using std::swap;
swap(a.name, b.name);
swap(a.threshold, b.threshold);
swap(a.parent, b.parent);
swap(a.handler, b.handler);
}
</code></pre>
<p>And the puny log.cpp</p>
<pre><code>#include "log.hpp"
std::ostream& bran::operator<<(std::ostream& out, bran::log_severity severity) {
static const std::string SEVERITY_NAMES[] = {"INHERIT", "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"};
static const size_t SEVERITY_COUNT = sizeof(SEVERITY_NAMES) / sizeof(SEVERITY_NAMES[0]);
auto index = static_cast<size_t>(severity);
assert(index < SEVERITY_COUNT);
return out << SEVERITY_NAMES[index];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:51:18.253",
"Id": "450885",
"Score": "0",
"body": "Did you know the existence of boost::log?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:47:43.680",
"Id": "450895",
"Score": "0",
"body": "@camp0 Yes. I don't like the interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:58:00.970",
"Id": "450929",
"Score": "1",
"body": "If you could show an example of how you intend to use this, it would be helpful to reviewers. As it is right now, you say everything is delegated to `Handler`, but the posted code never invokes `Handler` for any purpose. If you could supply those missing pieces, it would help a great deal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:27:03.897",
"Id": "450932",
"Score": "0",
"body": "Handler is used in the function basic_logger::log almost at the very end: get_handler()->log(*this, severity, message, args...); I'll post some example usage in a couple hours when I get home."
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Don't write getters and setters for every class</h2>\n\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. Instead, move setter functionality into constructors and think very carefully about whether a getter is needed at all. In this code, there are some invariants being enforced, but I'd still be skeptical about the need for all of these setters and getters. For example, the whole chaining of raw pointers to loggers is rather suspect. While checks are made to verify the pointer isn't <code>nullptr</code>, a handler or parent could go out of scope and the class would still be using a non-<code>nullptr</code> but invalid pointer.</p>\n\n<h2>Minimize the interface</h2>\n\n<p>Is there really a compelling need to have an <code>is_trace</code> and related? I'd recommend simplifying the interface by omitting all of those. The user can just as easily write <code>if(log.threshold <= log_severity::TRACE) {}</code>. </p>\n\n<h2>Use better data structures</h2>\n\n<p>The code currently contains code for <code>operator<<</code> that looks like this:</p>\n\n<pre><code>std::ostream& bran::operator<<(std::ostream& out, bran::log_severity severity) {\n static const std::string SEVERITY_NAMES[] = {\"INHERIT\", \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"FATAL\"};\n static const size_t SEVERITY_COUNT = sizeof(SEVERITY_NAMES) / sizeof(SEVERITY_NAMES[0]);\n\n auto index = static_cast<size_t>(severity);\n assert(index < SEVERITY_COUNT);\n\n return out << SEVERITY_NAMES[index];\n}\n</code></pre>\n\n<p>Since you're using the C++17 <code>[[nodiscard]]</code>, you could also use <code>std::string_view</code> and <code>std::array</code> to make this cleaner and more modern.</p>\n\n<pre><code>#include <array>\n#include <string_view>\nstd::ostream& bran::operator<<(std::ostream& out, bran::log_severity severity) {\n static constexpr std::array<std::string_view, 7> severity_names{\"INHERIT\", \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"FATAL\"};\n auto index = static_cast<size_t>(severity);\n assert(index < severity_names.size());\n return out << severity_names[index];\n}\n</code></pre>\n\n<p>Also, it's better to avoid ALL_CAPS names. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-not-CAPS\" rel=\"nofollow noreferrer\">ES.9</a></p>\n\n<h2>Rethink the existence of the class</h2>\n\n<p>As noted in the description of the code, all of the real work is being done by an unposted <code>Handler</code> function. Since the only useful things in the <code>basic_logger</code> class are the name and severity level, I'd suggest replacing the entire templated class with a concrete class that contains those two data items and whatever actual behavior is in <code>Handler</code>. The only required function in the <code>Handler</code> is apparently <code>log</code>. If you think you might need variations on the handler, simply make it a base class and make the <code>log</code> and destructor <code>virtual</code>.</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:13:16.723",
"Id": "450963",
"Score": "0",
"body": "Thank you for your review. I don't understand what you mean by no invariant being enforced. Functions set_parent, set_severity and set_handler all use the verify macro (which I described in the OP) to prohibit certain object states. You cannot set parent to null without having a non-null handler, handler to null without having non-null parent and others. I want to be able to change the logging system at run-time from configuration file, that's why the variables are mutable. I didn't post handler, because I have several unfinished implementations and they are all rather big already and use..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:18:47.883",
"Id": "450964",
"Score": "0",
"body": "additional classes. The whole system is well over 1000 lines of code and again, unfinished. It supports logging configuration from files in several formats, synchronous and asynchronous handler, logging to console, file and TCP stream, triggers that perform some action when message matching certain pattern is logged and more. I decided instead of reviewing the whole mess, I could just get a review of the interface. The other points I have nothing to say against so again, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:28:34.960",
"Id": "450970",
"Score": "0",
"body": "@Novotny You're right -- I had overlooked the purpose of the `verify` as being a way to enforce runtime invariance. I'll update my answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:41:00.680",
"Id": "231270",
"ParentId": "231235",
"Score": "3"
}
},
{
"body": "<p>I am not familiar with Java and I don't fully understand the purpose of Handler / parent - it would help us to better review the code if it was explained as pseudocode or via an interface.</p>\n\n<ul>\n<li><p>Considering the way <code>get_handler()</code> is implemented... do you really intend to change <code>parent</code>'s handler at runtime? Can't you just set the handler at class instantiation or something? Also, currently, changing <code>parent</code> at runtime is not thread-safe.</p></li>\n<li><p>I doubt that you want your logger to be a template. If you use it across all your codebase then either all of the code is a template (which is very troublesome currently for developers and the compiler...) or you end up with using a single version of the logger. Instead consider usage of an interface class <code>ILogHandler</code> so that you could run applications with different handlers without them needing to know anything about it. Sure, calling a virtual function is slower than a regular function but it pales in comparison to everything else the logger needs to do upon a function call. Though, you'd need to implement in the logger what to do with <code>T... args</code>, not in the Handler.</p></li>\n<li>Add <code>verbose_level</code>, not just <code>severity_level</code>. At times you'd want to see info_level log from a high level function but ignore warning/errors logs from low level functions.</li>\n<li>Also consider writing implementation of short functions when declaring them. It doesn't hinder view of the whole class declaration and you can see the implementation without the need to search for it. I might be spoiled with Visual Studio but it allows to hide implementation of functions in its text editor so in this case even long functions provide little to hindrance when their implementation is written inside class declaration.</li>\n<li>Since you work with C++17, consider using <code>std::string_view</code> instead of <code>const std::string&</code>.</li>\n<li><p>Use <code>std::forward<T>(args)...</code> when you forward data in template functions as otherwise you might end up with unnecessary data copying:</p>\n\n<pre><code>template<class Handler>\ntemplate<class... T>\nvoid bran::basic_logger<Handler>::debug(const std::string& message, T... args) {\n log(log_severity::DEBUG, message, std::forward<T>(args)...);\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T23:52:52.973",
"Id": "231322",
"ParentId": "231235",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T00:20:23.277",
"Id": "231235",
"Score": "6",
"Tags": [
"c++",
"logging"
],
"Title": "Logger class (C++)"
}
|
231235
|
<p>Update from <a href="https://codereview.stackexchange.com/q/230049/209774">Paper label system in Python</a></p>
<p>I have not updated the security on the app, need to have a proper look into it.</p>
<p>Have decided to use <code>docx</code> module, instead of using print-screen. </p>
<p>I have added few important <code>if</code> statements when handling <code>.docx</code> files in folders depending what the user has clicked etc..</p>
<p>My current issues are: </p>
<ul>
<li>Security of the application</li>
<li>Storing username paths inside code isn't a great idea, but it will do for now</li>
<li>Will be moving from <code>grid</code> to <code>pack</code> as I don't like the whole feeling of the app itself.</li>
<li>Handling the <code>options menu</code> if a user has signed the document, do not show the file that has been signed for that specific user.</li>
</ul>
<p>I will work on the above, but before I proceed any further. I'd like to hear some feedback on my updated code.</p>
<p><strong>Code below:</strong></p>
<pre><code>import tkinter as tk
from tkinter import messagebox, Frame, Label, Entry, Button, Toplevel, IntVar, Radiobutton, StringVar, OptionMenu
import tkinter.ttk as ttk
import os
import glob
from PIL import Image, ImageTk, ImageGrab
from pathlib import Path
import pyautogui
from time import gmtime, strftime
from docx import Document
import pandas as pd
from collections import Counter
def main():
root = tk.Tk()
# Gets the requested values of the height and widht.
windowWidth = root.winfo_reqwidth()
windowHeight = root.winfo_reqheight()
print("Width",windowWidth,"Height",windowHeight)
# Gets both half the screen width/height and window width/height
positionRight = int(root.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(root.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
root.geometry("+{}+{}".format(positionRight, positionDown))
app = Window1(root)
root.mainloop()
#Log in system
class Window1:
def __init__(self,master):
self.master = master
self.master.title("User Log In")
self.master.geometry('400x150')
self.frame = Frame(self.master)
self.frame.pack(fill="both", expand=True)
#Press enter key to log in
self.master.bind('<Return>',self.parse)
#Input for username & password
self.label_username = Label(self.frame, text="Username: ",font=("bold",16))
self.entry_username = Entry(self.frame, font = ("bold", 14))
self.label_password = Label(self.frame, text="Password: ",font=("bold",16))
self.entry_password = Entry(self.frame, show="*", font = ("bold", 14))
#layout for inputs
self.label_username.pack()
self.entry_username.pack()
self.label_password.pack()
self.entry_password.pack()
#Log in button
self.logbtn = Button(self.frame, text="Login", font = ("bold", 10), command=self._login_btn_clicked)
self.logbtn.pack()
#close and stop tkinter running in backround, also see line #67
def on_closing(self):
self.master.destroy()
def _login_btn_clicked(self):
# retriving username and password from above entries
username = self.entry_username.get()
password = self.entry_password.get()
found_username = False
#opening Window2
def Window2_open():
self.master.withdraw()
self.newWindow = Toplevel(self.master)
self.newWindow.protocol("WM_DELETE_WINDOW", self.on_closing)
self.app = Window2(self.newWindow, window1 = self)
#self.newWindow.state('zoomed')
#password file, will need to improve security
with open('//SERVER/shared_data/Technical/EdGzi/Sign off/passwords.csv', 'r') as passwords_file:
for line in passwords_file:
username_file, password_file = line.strip().split(',')
if username == username_file:
found_username = True
if password == password_file:
Window2_open() #open main window
else:
messagebox.showinfo("User message", "Invalid username or password specified please try again")
break
if not found_username:
messagebox.showinfo("User message", "Invalid username or password specified please try again")
#function to press enter on keyboard to log in
def parse(self,event):
self._login_btn_clicked()
#Main window
class Window2:
def __init__(self,master, window1):
#Seperated into tabs
notebook = ttk.Notebook(master)
notebook.pack(expand = 1, fill = "both")
#Frames
main = ttk.Frame(notebook)
manual = ttk.Frame(notebook)
pswd_change = ttk.Frame(notebook)
notebook.add(main, text='Main-Screen')#Main screen
notebook.add(manual, text='Manual')#Link to docx files
notebook.add(pswd_change, text = "Change Password")
self.window1 = window1 # returning functions from window1
#validating which user has signed
username = self.window1.entry_username.get()
self.User = Label(main, text = 'User: '+ username, font = ('15'))
self.User.grid(column = 5, row = 0)
self.info = ["Brand (Logo)", "Product Name:",
"Product Sub Description: ",
"Ingredients present in full (any allergens in bold with allergen warning if necessary)",
"May Contain Statement.",
"Cocoa Content (%).",
"Vegetable fat in addition to Cocoa butter",
"Instructions for Use.",
"Additional warning statements (pitt/stone, hyperactivity etc)",
"Nutritional Information Visible",
"Storage Conditions",
"Best Before & Batch Information",
"Net Weight & Correct Font Size.",
"Barcode - Inner",
"Address & contact details correct"
]
self.vars = []
for idx,i in enumerate(self.info):
self.var = IntVar(value=0)
self.vars.append(self.var)
self.lblOption = Label(main,text=i)
self.btnYes = Radiobutton(main, text="Yes", variable=self.var, value=2)
self.btnNo = Radiobutton(main, text="No", variable=self.var, value=1)
self.btnNa = Radiobutton(main, text="N/A", variable=self.var,value=0)
self.lblOption.grid(column=4,row=idx, sticky = 'w')
self.btnYes.grid(column=1,row=idx)
self.btnNo.grid(column=2,row=idx)
self.btnNa.grid(column=3,row=idx)
#paths to sign and signed
to_sign = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To Sign/'
signed = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/'
adjust = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Adjust/'
#Writing to docx file
def var_states():
document = Document()
section = document.sections[0]
document.add_paragraph(f'Date and Time: {strftime("%d-%m-%Y, %H:%M:%S", gmtime())}')
document.add_paragraph(f'Sign Off - Name: {username}')
document.add_picture(f'{self.p}')
#add table
table = document.add_table(1, 4)
#style table
table.style = 'Table Grid'
#populate header row
heading_cells = table.rows[0].cells
heading_cells[0].text = "Options"
heading_cells[1].text = self.btnYes.cget("text")
heading_cells[2].text = self.btnNo.cget("text")
heading_cells[3].text = self.btnNa.cget("text")
for idx, item in enumerate(self.vars):
cells = table.add_row().cells
cells[0].text = self.info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "*"
elif val == 1: # checks if no
cells[2].text = "*"
elif val == 0: # checks if N/A
cells[3].text = "*"
no_in_result = any([self.var.get() == 1 for self.var in self.vars])
doc_name = f"{adjust}{os.path.basename(self.p).strip('.jpg') + ' ' + username}.docx" if no_in_result else f"{signed}{os.path.basename(self.p).strip('.jpg') + ' ' + username}.docx"
fn = document.save(doc_name)
print(fn)
#Usernames to verify 2 word documents exist
ed = (signed+ os.path.basename(self.p).strip('.jpg') +' ed'+ '.docx')
neal = (signed + os.path.basename(self.p).strip('.jpg') +' neal'+ '.docx')
jurate = (signed + os.path.basename(self.p).strip('.jpg') +' jurate'+ '.docx')
karolina = (signed + os.path.basename(self.p).strip('.jpg') +' karolina'+ '.docx')
rita = (signed + os.path.basename(self.p).strip('.jpg') +' rita'+ '.docx')
if os.path.exists(neal) and os.path.exists(jurate) == True:
os.remove(to_sign + os.path.basename(self.p))
messagebox.showinfo("MSG[T]", "Saved!")
print("Both users signed the document")
elif os.path.exists(neal) and os.path.exists(karolina) == True:
os.remove(to_sign + os.path.basename(self.p))
messagebox.showinfo("MSG[T]", "Saved!")
print("Both users signed the document")
elif os.path.exists(jurate) and os.path.exists(karolina) == True:
os.remove(to_sign + os.path.basename(self.p))
messagebox.showinfo("MSG[T]", "Saved!")
print("Both users signed the document")
elif os.path.exists(rita) and os.path.exists(karolina) == True:
os.remove(to_sign + os.path.basename(self.p))
messagebox.showinfo("MSG[T]", "Saved!")
print("Both users signed the document")
elif os.path.exists(rita) and os.path.exists(neal) == True:
os.remove(to_sign + os.path.basename(self.p))
messagebox.showinfo("MSG[T]", "Saved!")
print("Both users signed the document")
elif os.path.exists(rita) and os.path.exists(jurate) == True:
os.remove(to_sign + os.path.basename(self.p))
messagebox.showinfo("MSG[T]", "Saved!")
print("Both users signed the document")
else:
print("One user has signed")
messagebox.showinfo("MSG[F]", "Document Saved!")
self.dataSend = Button(main, text = "Send", command = var_states) #send all relevant data from var_states
self.dataSend.grid(column = 1, row = 16, sticky = 'w')
###################################################################################################################################
##Load Image##
###################################################################################################################################
try:
# Create a Tkinter variable
self.tkvar = StringVar()
# Directory
self.directory = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To Sign/'
self.choices = os.listdir(self.directory)
#self.choices = glob.glob(os.path.join(self.directory, "*")) #all choices
self.tkvar.set('...To Sign Off...') # set the default option
###for later### ###for later###
# for subdir, dirs, files in os.walk(signed):
# for file in files:
# x = os.path.join(file).split()[-3:-1]
# y = ' '.join(x)
#
#
# if os.path.join(subdir, file).endswith(f'{username}.docx') is True: #if this file exists, do not show 'to-sign' file for current user signed in
# self.choices = glob.glob(os.path.join(self.directory, '{y}*.jpg'.format(prefix=y)))
# print("true")
###for later### ###for later###
# Images, placing the image onto canvas
def change_dropdown():
imgpath = self.tkvar.get()
img = Image.open(self.directory + imgpath)
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
#return path value of selected directory
self.p = None
def func(value):
global p
self.p = Path(self.directory + value)
print(self.p)
#reset function to continue signing other labels
def reset():
for intvar in self.vars:
intvar.set(0)
label2.configure(image='')
self.tkvar.set('...To Sign Off...') # set the default option
#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) #Dropdown menu of all sign off Sheets that need signing
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) # opens the directory and opens selected image
self.open_button.grid(row=502, column=0)
self.resetBtn = Button(main, text = "reset", command = reset)
self.resetBtn.grid(column = 1, row = 17, sticky = 'w')
except TypeError: #if no images found in folder, then show messagebox & disable send btn
self.dataSend['state'] = 'disabled'
messagebox.showinfo("Label Error", "No labels to sign, please quit the program!")
###################################################################################################################################
##Click and drag for measuring purposes##
###################################################################################################################################
# def drag(event):
# event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)
#
#
#
# self.card = Canvas(main, width=50, height=50, bg='blue')
# self.card.place(x=300, y=600,anchor=CENTER)
#
# self.card.bind("<B1-Motion>", drag)
###################################################################################################################################
##TAB 2 - MANUAL##
###################################################################################################################################
#opening a docx file for manual guide on how to print labels.
def manualopen():
# file_to_open = str(Path("//SERVER/shared_data/Technical/Food Safety & Quality Manual/21.LABL.02 - Labelling notes.docx"))
# subprocess.check_call(['open', file_to_open])
file_to_open = r"\\SERVER\shared_data\Technical\Food Safety & Quality Manual\Section 21 - Process Control\21.LABL.02 - Labelling notes.docx"
os.startfile(file_to_open)
self.manualBtn = Button(manual, text= "open doc", command = manualopen)
self.manualBtn.pack()
###################################################################################################################################
##TAB 3 - Password Change##
###################################################################################################################################
self.usernameReturn = Label(pswd_change, text = "Username: "+username).pack()
self.msgPass = Label(pswd_change, text = "New Password: ").pack()
self.password_change = Entry(pswd_change, show = "*")
self.password_change.pack()
def changepass():
password_replace = pd.read_csv("//SERVER/shared_data/Technical/EdGzi/Sign off/passwords.csv")
password_replace.loc[password_replace["username"]==username, "pa55w07541146ffdf4s65"] = self.password_change.get()
password_replace.to_csv("//SERVER/shared_data/Technical/EdGzi/Sign off/passwords.csv", index=False)
messagebox.showinfo("Password MSG", "Password Changed!")
self.btnChangePass = Button(pswd_change, text = "Change Password", command = changepass)
self.btnChangePass.pack()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<h2>Dimension output</h2>\n\n<p>This:</p>\n\n<pre><code># Gets the requested values of the height and widht.\nwindowWidth = root.winfo_reqwidth()\nwindowHeight = root.winfo_reqheight()\nprint(\"Width\",windowWidth,\"Height\",windowHeight)\n</code></pre>\n\n<p>firstly has a spelling mistake - widht = width. That aside, you can probably just simplify it to</p>\n\n<pre><code>window_width = root.winfo_reqwidth()\nwindow_height = root.winfo_reqheight()\nprint(f'Dimensions: {window_width}x{window_height}')\n</code></pre>\n\n<p>Also note the use of <code>lower_camel_case</code>.</p>\n\n<p>Similarly,</p>\n\n<pre><code>root.geometry(f\"+{position_right}+{position_down}\")\n</code></pre>\n\n<h2>Class names</h2>\n\n<p>Pick better names than <code>Window1</code>, <code>Window2</code>. Perhaps <code>MainWindow</code>, <code>LoginWindow</code>.</p>\n\n<h2>Password storage</h2>\n\n<p>Other than this being insecure - which you've already identified - there are other issues:</p>\n\n<pre><code> with open('//SERVER/shared_data/Technical/EdGzi/Sign off/passwords.csv', 'r') as passwords_file:\n for line in passwords_file:\n username_file, password_file = line.strip().split(',')\n\n if username == username_file:\n found_username = True\n if password == password_file:\n Window2_open() #open main window\n else:\n messagebox.showinfo(\"User message\", \"Invalid username or password specified please try again\")\n break\n</code></pre>\n\n<p>Don't hard-code that path. At the least, use <code>~</code> and resolve your home directory, and/or accept a string parameter in the constructor. Since you're manipulating multiple files, establish a supported directory structure, and parametrize the base path - in your case, <code>//SERVER/shared_data/Technical</code>.</p>\n\n<p>You set <code>found_username</code> to <code>True</code> even if the password is incorrect. That doesn't seem right. Beyond that: you shouldn't need to use a <code>found</code> flag at all - just <code>break</code> if you find the thing, and write a <code>for/else</code> to detect if you didn't break.</p>\n\n<p>In general, you should try harder to separate your presentation (i.e. <code>messagebox</code>) from your logic (i.e. password storage, retrieval and comparison). Entirely different classes, maybe different modules.</p>\n\n<h2>Single-parameter formatting</h2>\n\n<p>Don't do this:</p>\n\n<pre><code> document.add_picture(f'{self.p}')\n</code></pre>\n\n<p>instead,</p>\n\n<pre><code> document.add_picture(str(self.p))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T02:16:39.217",
"Id": "231292",
"ParentId": "231244",
"Score": "2"
}
},
{
"body": "<p>A few other things that weren't mentioned so far:</p>\n\n<p>In a few places, you do something like this:</p>\n\n<pre><code>f\"{adjust}{os.path.basename(self.p).strip('.jpg') + ' ' + username}\"\n</code></pre>\n\n<p>Why not simply:</p>\n\n<pre><code>f\"{adjust}{os.path.basename(self.p).strip('.jpg')} {username}\"\n</code></pre>\n\n<p>Speaking of which, your use of <code>str.strip</code> doesn't behave the way you think it does. Take a look:</p>\n\n<pre><code>>>> help(str.strip)\nHelp on method_descriptor:\n\nstrip(self, chars=None, /)\n Return a copy of the string with leading and trailing whitespace remove.\n\n If chars is given and not None, remove characters in chars instead.\n\n>>> \n</code></pre>\n\n<p>In your case, the optional <code>chars</code> parameter is not <code>None</code>, it's <code>\".jpg\"</code>. That means it will remove any of the characters specified in <code>chars</code>. Not only that, but since you're using <code>str.strip</code> instead of <code>str.rstrip</code>, you're potentially removing those characters not just from the back, but from the front as well.</p>\n\n<p>For example:</p>\n\n<pre><code>>>> \"john_help.jpg\".strip(\".jpg\")\n'ohn_hel'\n>>>\n</code></pre>\n\n<p>Definitely not the desired output in your case.\nUsing <code>str.rstrip</code> would strip only from the back of the string, but it still wouldn't give you the desired result:</p>\n\n<pre><code>>>> \"john_help.jpg\".rstrip(\".jpg\")\n'john_hel'\n>>>\n</code></pre>\n\n<p>If you're using Python 3.4+, you're better of using <code>pathlib</code> anyway instead of all that <code>os.path</code> stuff:</p>\n\n<pre><code>>>> from pathlib import Path\n>>> Path(\"root/dir/sub/file.jpg\").stem\n'file'\n>>> \n</code></pre>\n\n<p>I would also suggest using an <code>enum.Enum</code> to represent the possible values / options / states of your <code>tk.Radiobutton</code>s. It prevents you from \"stringify-ing\" the options or doing something like this:</p>\n\n<pre><code>val = item.get() #radiobutton value\nif val == 2: # checks if yes\n cells[1].text = \"*\"\nelif val == 1: # checks if no\n cells[2].text = \"*\"\nelif val == 0: # checks if N/A\n cells[3].text = \"*\"\n</code></pre>\n\n<p>Here's how I might set up a <code>tk.Radiobutton</code> using an enum:</p>\n\n<pre><code>import tkinter as tk\n\n\nclass Application(tk.Tk):\n\n from enum import Enum\n\n\n class RadioOption(Enum):\n Red = 0\n Green = 1\n Blue = 2\n\n def __init__(self, *args, **kwargs):\n\n tk.Tk.__init__(self, *args, **kwargs)\n self.title(\"Title\")\n self.geometry(\"100x100\")\n self.resizable(width=False, height=False)\n\n self.radio_variable = tk.Variable(None, Application.RadioOption.Red)\n\n def on_radio_variable_change(*args):\n print(self.radio_variable.get())\n self.radio_variable.trace(mode=\"w\", callback=on_radio_variable_change)\n\n self.radio_button_red = tk.Radiobutton(\n self,\n text=\"Red\",\n variable=self.radio_variable,\n value=Application.RadioOption.Red,\n )\n\n self.radio_button_green = tk.Radiobutton(\n self,\n text=\"Green\",\n variable=self.radio_variable,\n value=Application.RadioOption.Green,\n )\n\n self.radio_button_blue = tk.Radiobutton(\n self,\n text=\"Blue\",\n variable=self.radio_variable,\n value=Application.RadioOption.Blue,\n )\n\n self.radio_button_red.pack(anchor=tk.W)\n self.radio_button_green.pack(anchor=tk.W)\n self.radio_button_blue.pack(anchor=tk.W)\n\ndef main():\n\n application = Application()\n application.mainloop()\n\n return 0\n\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(main())\n</code></pre>\n\n<p>And one more tiny nit-pick, in a few different places you do something like this:</p>\n\n<pre><code>self.open_button.grid(row=502, column=0)\nself.resetBtn = Button(main, text = \"reset\", command = reset)\n</code></pre>\n\n<p>See how some of the keyword-arguments have additional whitespace, and others do not? Pick one style, but don't do both - personally I would remove the whitespace since that's PEP8 compliant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T15:16:43.800",
"Id": "231343",
"ParentId": "231244",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T06:33:55.593",
"Id": "231244",
"Score": "3",
"Tags": [
"python",
"tkinter"
],
"Title": "Paper label system in Python / Tkinter"
}
|
231244
|
<p>I'm trying to make a function that asks for a string input and then validates it. If the answer is not correct, the function asks them again for valid input with a while loop.</p>
<p>In order to validate the string input, I'm using a string array with all the possible answers to the question.</p>
<p>Because I'm using a string array I need to pass it into the function as a pointer.</p>
<p>The problem I'm running into is that to call the function properly currently I have to type this:</p>
<pre><code>std::string possibleAnswers[3] = { "0","1","2" };
//find the length of the possibleAnswers array
int length = sizeof(possibleAnswers) / sizeof(possibleAnswers[0]);
//create a pointer that points at the string array
std::string* pointerPossibleAnswers = possibleAnswers;
//call function to validate input
std::string response = checkInput(pointerPossibleAnswers, length);
</code></pre>
<p>You'll also notice that I used
<code>sizeof(possibleAnswers)/sizeof(possibleAnswers[0]</code> to find the length which I can't call within the function, because the pointer in the function points to an element in the array, not the entire array.
My function implementation is here:</p>
<pre><code>std::string checkInput(std::string* pointerPossibleAnswers, int length)
{
std::string input;
//input = toLowerCase(input);
//create a boolean to continue to ask for input
bool isAsking = true;
while (isAsking)
{
std::getline(std::cin, input);
//for loop checks against possibleAnswer array
for(int i = 0; i< length; i++)
{
// dereference possibleAnswers pointer to the
//ith position of the array
if (input == *pointerPossibleAnswers)
{
isAsking = false;
//stop checking if a possible response is found
//break from the loop on next iteration
i = length;
}
//make the pointer point to the next spot
pointerPossibleAnswers++;
}
if (isAsking == true)
{
std::cout << "Invalid response, please enter a valid response." << std::endl;
//reset the pointer to point at original memory
//location
for (int i = 0; i < length; i++)
{
pointerPossibleAnswers--;
}
}
}
return input;
}
</code></pre>
<p>I was just wondering if there is an easier way to call the function, which is one or two lines something like:</p>
<pre><code>std::string possibleAnswers[3] = { "0","1","2" };
std::string response = checkInput(pointerPossibleAnswers, length);
</code></pre>
<p>within two lines that's more efficient, because I have noticed that I'm copying and pasting a lot of code each time. I feel like there is a much more efficient way to do this with a class or a vector, given they have some built in methods for calling</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:20:05.120",
"Id": "450889",
"Score": "3",
"body": "What about using `std::vector` or `std::array` instead of a raw c-style array of `std::string`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:23:11.237",
"Id": "450890",
"Score": "0",
"body": "@πάντα ῥεῖ That's a good suggestion I'll try changing it to a vector so I can stuff more of it into a function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T06:09:40.990",
"Id": "451016",
"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)*."
}
] |
[
{
"body": "<ul>\n<li><p>Use <code>std::vector<std::string></code> instead C-style array for <code>possibleAnswers</code> and then pass a reference to the vector into the <code>checkInput</code> function.</p></li>\n<li><p>If you will use <code>std::vector</code> you can use just <a href=\"http://en.cppreference.com/w/cpp/algorithm/find\" rel=\"nofollow noreferrer\"><code>std::find</code></a> to check if the input appears in the <code>possibleAnswers</code>.</p></li>\n<li><p>Consider making <code>possibleAnswers</code> constant<sup>1</sup>. It is never change, is not it?</p></li>\n<li><p>The <code>sizeof</code> operator returns a value of type <a href=\"https://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a> but you use <code>int length</code> to hold it. You should use <code>std::size_t</code> instead of <code>int</code> for the loop counters <code>i</code> inside the <code>checkInput</code> fucntion as well. Note that <code>int</code> is not guaranted to be large enough to hold a size of any object type (an array of <code>std::string</code> in your case).</p></li>\n<li><p>It is a good habit to prefer pre-increment over post-increment all things being equal in C++ since the first usually is <a href=\"https://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c\">faster</a>.</p></li>\n<li><p>Do not comment your code too much. Anyone perfectly knows that <code>*</code> means <em>dereference</em>:</p>\n\n<blockquote>\n<pre><code>// dereference possibleAnswers pointer to the\n//ith position of the array\nif (input == *pointerPossibleAnswers)\n</code></pre>\n</blockquote>\n\n<p>Make it a rule: \"<em>Comments shouldn't say <strong>what</strong> happens in code, they should say <strong>why</strong> this is happens</em>\".</p></li>\n<li><p>You can easily restructure your code to get rid of the <code>isAsking</code> flag variable. All you have to do is explicitly return <code>input</code> when it equals to one of the possible answer.</p></li>\n</ul>\n\n<hr>\n\n<p><sub><sup>1</sup> As mentioned @πάντα ῥεῖ in the comments if you'll decide to use to make <code>possibleAnswers</code> constant you may want to use <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a>. But in this case you have to use templates to pass different sized arrays to the <code>possibleAnswers</code> function.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:42:58.300",
"Id": "450893",
"Score": "1",
"body": "_\"It is a good habit to prefer pre-increment over post-increment ...\"_ That's a long standing myth still told, while no longer really valid for modern optimizing compilers. I also still prefer pre-incerement though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:47:34.097",
"Id": "450894",
"Score": "0",
"body": "@πάνταῥεῖ, but it is still a good habit, especially if you are forced to use a dinosaur compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:50:04.457",
"Id": "450896",
"Score": "1",
"body": "Sure, I just wanted to mention that performance isn't an argument anymore for most modern compilers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:27:57.517",
"Id": "450906",
"Score": "0",
"body": "@eanmos Thanks for the suggestions, I apologise for my inexperience. I think I'll try using templates, given const vectors are a little redundant. I genuinely was not aware of std::size_t nor pre-increment. I'll cut down on the comments as well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:29:49.733",
"Id": "450907",
"Score": "0",
"body": "@eanmos one point of clarification, if I get rid of the boolean isAsking I'm just thing that the other option would be to have a while(true) loop which I've always been advised is bad practice, is there another option which would be a little better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:36:45.697",
"Id": "450908",
"Score": "0",
"body": "Also, I was just thinking about how would I use templates to go about implementing this code?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:30:02.647",
"Id": "231248",
"ParentId": "231247",
"Score": "4"
}
},
{
"body": "<h1>Include the necessary standard headers</h1>\n\n<p>To compile successfully, this code needs at least</p>\n\n<pre><code>#include <iostream>\n#include <string>\n</code></pre>\n\n<h1>Don't use signed types for size</h1>\n\n<p>Prefer <code>std::size_t length</code>.</p>\n\n<h1>Don't compare booleans to <code>true</code> or <code>false</code></h1>\n\n<p>A boolean that's not <code>false</code> must be <code>true</code>, so just write</p>\n\n<pre><code> if (isAsking)\n</code></pre>\n\n<h1>Consider using an infinite loop</h1>\n\n<p>Return from within the loop when we have a matching answer, instead of having to maintain the <code>isAsking</code> variable. That also enables us to reduce the scope of <code>input</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:48:17.160",
"Id": "450912",
"Score": "0",
"body": "Thanks for the suggestions I messed up with the booleans and signed types, just with the infinite loop, I was just wondering if there was a better way to do that other than while(true), because I've always been advised not to do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:50:35.683",
"Id": "450914",
"Score": "0",
"body": "I'd say that `while (true)` is exactly the right way to implement such a loop; I don't think the advice was particularly good. You do want to take care that the control flow is understandable, but I don't expect that to be a problem here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:41:27.917",
"Id": "231257",
"ParentId": "231247",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231248",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:17:00.420",
"Id": "231247",
"Score": "3",
"Tags": [
"c++",
"strings",
"parsing"
],
"Title": "Function to prompt and check user input"
}
|
231247
|
<p>I want to create a factory to return all Source instances that match given entry parameters- that is, I want to iterate through some Collection of objects and for each entry check boolean method.
I thought about enum, as I'm guaranteed to iterate through them all.
I came up with something like this:</p>
<p>simple interface</p>
<pre><code>public interface Source {
public boolean isPresent(SourceCalculationData data);
public Source2 getType();
}
</code></pre>
<p>my take on enum factory:</p>
<pre><code>public enum Source2 {
IB("IB", SourceIb.class),
CCWEW("BOT", SourceCcwew.class),
OBD("CUF", SourceCuf.class),
PB("PB", SourcePb.class),
COK("COK", SourceCok.class),
CCZEW("CCZ", SourceCczew.class),
CRM("CRM", SourceCrm.class),
APP("APP", SourceApp.class);
private static final Logger SENSITIVE_LOGGER = SensitiveLoggerFactory.getSensitiveLogger(Source2.class);
private String configChannel;
private Class<? extends Source> clazz;
private Source2(String configChannel, Class<? extends Source> clazz) {
this.configChannel = configChannel;
this.clazz = clazz;
}
public Class<? extends Source> getClazz() {
return clazz;
}
public String getConfigChannel() {
return configChannel;
}
public Source getSource() {
return getAction(clazz);
}
private Source getAction(Class<? extends Source> source2Class) {
try {
return source2Class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
SENSITIVE_LOGGER.warn("<< Exception occured during init of {}, returning unkown source.", source2Class);
return new SourceUnkown();
}
}
</code></pre>
<p>and use case:</p>
<pre><code> final SourceCalculationData data = new SourceCalculationData();
final EnumSet<Source2> presentSources = EnumSet.noneOf(Source2.class);
for (final Source2 source2ToCheck : Source2.values()) {
if (source2ToCheck.getSource().isPresent(data)) presentSources.add(source2ToCheck);
}
</code></pre>
<p>I'm pretty sure this is not the best code in the world. Any suggestions what will make it better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:47:09.873",
"Id": "450911",
"Score": "0",
"body": "Greetings & Salutations, to prevent this from being closed; I would take out the implementation of `SourceIb`, since we don't review stubs. Ideally you would also figure out your logging and error handling before submitting the code."
}
] |
[
{
"body": "<p>Your implementation is good, but I would suggest following points to improve:</p>\n\n<ol>\n<li>It is really hard to test/mock <code>source2ToCheck.getSource()</code>.</li>\n<li><code>Source2</code> contains a lot logic/functionality (it is source type and\nfactory) it has to be simplified. </li>\n<li><code>getSource()</code> creates new course\nobject it is confusing </li>\n<li><code>getSource(...)</code> calls <code>getAction(...)</code> that create a source object. It is wired. </li>\n<li>Be aware <code>source2Class.newInstance()</code> is deprecated since java 9\n<code>source2Class.getDeclaredConstructor().newInstance()</code></li>\n</ol>\n\n<p><strong><em>Suggestions:</em></strong></p>\n\n<ul>\n<li>I would propose to create dedicated interface/class for source factory</li>\n<li>Rename <code>Source2</code> to <code>SourceType</code>.</li>\n<li>Throw custom exception <code>CustomCantCreateSourceException</code> instead of <code>return new SourceUnkown()</code>. Because it is real exceptional situation.</li>\n<li>Remove public methods modifier from Source interface</li>\n<li>Minor enhancements you can find in following code</li>\n</ul>\n\n<p><em>Source Factory interface:</em></p>\n\n<pre><code>public interface SourceFactory {\n Source create(SourceType type);\n}\n</code></pre>\n\n<p><em>Factory implementation:</em></p>\n\n<pre><code>public class SourceFactoryImpl implements SourceFactory {\n @Override\n public Source create(SourceType type) {\n try {\n return type.getClazz().getDeclaredConstructor().newInstance();\n } catch (InstantiationException | IllegalAccessException\n | NoSuchMethodException | InvocationTargetException e) {\n SENSITIVE_LOGGER.warn(\"<< Exception occured during init of {}, returning unkown source.\", source2Class);\n throw new CustomCantCreateSourceException();\n }\n }\n}\n</code></pre>\n\n<p><em>Renamed Source2:</em></p>\n\n<pre><code>public enum SourceType {\n\n IB(\"IB\", SourceIb.class),\n CCWEW(\"BOT\", SourceCcwew.class),\n OBD(\"CUF\", SourceCuf.class),\n PB(\"PB\", SourcePb.class),\n COK(\"COK\", SourceCok.class),\n CCZEW(\"CCZ\", SourceCczew.class),\n CRM(\"CRM\", SourceCrm.class),\n APP(\"APP\", SourceApp.class);\n\n private static final Logger SENSITIVE_LOGGER = SensitiveLoggerFactory.getSensitiveLogger(SourceType.class);\n\n private String configChannel;\n\n private Class<? extends Source> clazz;\n\n private SourceType(String configChannel, Class<? extends Source> clazz) {\n this.configChannel = configChannel;\n this.clazz = clazz;\n }\n\n public Class<? extends Source> getClazz() {\n return clazz;\n }\n\n public String getConfigChannel() {\n return configChannel;\n }\n}\n</code></pre>\n\n<p><em>Usage:</em></p>\n\n<pre><code>public class SourceService {\n private final SourceFactory factory;\n\n public SourceService(SourceFactory factory) {\n this.factory = factory;\n }\n\n public EnumSet<SourceType> fillSources() {\n final SourceCalculationData data = new SourceCalculationData();\n\n final EnumSet<SourceType> presentSources = EnumSet.noneOf(SourceType.class);\n for (final SourceType source2ToCheck : SourceType.values()) {\n if (factory.create(source2ToCheck).isPresent(data)) {\n presentSources.add(source2ToCheck);\n }\n }\n return presentSources;\n }\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T05:49:18.160",
"Id": "231331",
"ParentId": "231249",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231331",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T09:47:54.127",
"Id": "231249",
"Score": "4",
"Tags": [
"java",
"enum",
"factory-method"
],
"Title": "Java enum-based factory to calculate entry parameters"
}
|
231249
|
<p>I'm mostly wondering if I can simplify the code. I've been told that it's
needlessly complicated.</p>
<p>HTML:</p>
<pre><code><div class="board">
<div id="tl" class="tldarkmode" (click)="fill(1)">{{ valtl }}</div>
<div id="t" class="tdarkmode" (click)="fill(2)">{{ valt }}</div>
<div id="tr" class="trdarkmode" (click)="fill(3)">{{ valtr }}</div>
<div id="cl" class="cldarkmode" (click)="fill(4)">{{ valcl }}</div>
<div id="c" class="cdarkmode" (click)="fill(5)">{{ valc }}</div>
<div id="cr" class="crdarkmode" (click)="fill(6)">{{ valcr }}</div>
<div id="bl" class="bldarkmode" (click)="fill(7)">{{ valbl }}</div>
<div id="b" class="bdarkmode" (click)="fill(8)">{{ valb }}</div>
<div id="br" class="brdarkmode" (click)="fill(9)">{{ valbr }}</div>
</div>
<div id="turnmsg">
{{ msg }}
</div>
<input
class="newgamebutton"
type="button"
value="New Game"
(click)="newgame()"
title="Start a new game"
/>
</code></pre>
<p>Typescript:</p>
<pre><code>export class GameComponent implements OnInit {
constructor() {}
ngOnInit() {}
public turn: number = 1;
public count: number = 0;
public msg: string = "";
public buttonvalue = "";
public winflag: number = -1;
public valtl: string = "";
public valt: string = "";
public valtr: string = "";
public valcl: string = "";
public valc: string = "";
public valcr: string = "";
public valbl: string = "";
public valb: string = "";
public valbr: string = "";
fill(cell: number) {
if (cell == 1) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valtl == "") {
this.valtl = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valtl == "") {
this.valtl = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 2) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valt == "") {
this.valt = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valt == "") {
this.valt = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 3) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valtr == "") {
this.valtr = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valtr == "") {
this.valtr = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 4) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valcl == "") {
this.valcl = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valcl == "") {
this.valcl = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 5) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valc == "") {
this.valc = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valc == "") {
this.valc = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 6) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valcr == "") {
this.valcr = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valcr == "") {
this.valcr = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 7) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valbl == "") {
this.valbl = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valbl == "") {
this.valbl = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 8) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valb == "") {
this.valb = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valb == "") {
this.valb = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
if (cell == 9) {
if (this.turn == 1) {
if (this.winflag == -1) {
if (this.valbr == "") {
this.valbr = "X";
this.turn = this.turn + 1;
this.msg = "Player O's turn";
}
}
} else {
if (this.winflag == -1) {
if (this.valbr == "") {
this.valbr = "O";
this.turn = this.turn - 1;
this.msg = "Player X's turn";
}
}
}
if (this.winflag == -1) {
this.count = this.count + 1;
}
this.checkwin();
}
}
checkwin() {
if (
(this.valtl == "X" && this.valt == "X" && this.valtr == "X") ||
(this.valcl == "X" && this.valc == "X" && this.valcr == "X") ||
(this.valbl == "X" && this.valb == "X" && this.valbr == "X") ||
(this.valtl == "X" && this.valcl == "X" && this.valbl == "X") ||
(this.valt == "X" && this.valc == "X" && this.valb == "X") ||
(this.valtr == "X" && this.valcr == "X" && this.valbr == "X") ||
(this.valtl == "X" && this.valc == "X" && this.valbr == "X") ||
(this.valtr == "X" && this.valc == "X" && this.valbl == "X")
) {
this.msg = "Player X wins";
this.winflag = 1;
} else if (this.count == 9) {
//alert("It's a draw"!);
this.msg = "It's a Draw";
this.winflag = 0;
} else if (
(this.valtl == "O" && this.valt == "O" && this.valtr == "O") ||
(this.valcl == "O" && this.valc == "O" && this.valcr == "O") ||
(this.valbl == "O" && this.valb == "O" && this.valbr == "O") ||
(this.valtl == "O" && this.valcl == "O" && this.valbl == "O") ||
(this.valt == "O" && this.valc == "O" && this.valb == "O") ||
(this.valtr == "O" && this.valcr == "O" && this.valbr == "O") ||
(this.valtl == "O" && this.valc == "O" && this.valbr == "O") ||
(this.valtr == "O" && this.valc == "O" && this.valbl == "O")
) {
this.msg = "Player O wins";
this.winflag = 2;
}
}
newgame() {
this.turn = 1;
this.msg = "";
this.count = 0;
this.valtl = "";
this.valt = "";
this.valtr = "";
this.valcl = "";
this.valc = "";
this.valcr = "";
this.valbl = "";
this.valb = "";
this.valbr = "";
this.winflag = -1;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T10:33:54.487",
"Id": "231252",
"Score": "2",
"Tags": [
"tic-tac-toe",
"typescript",
"angular-2+"
],
"Title": "Simple Tictactoe game in Typescript"
}
|
231252
|
<p>I have 271 million records, line by line in a text file that I need to add to MongoDB, and I'm using Python and Pymongo in order to do this.</p>
<p>I first split the single file containing the 271 million records into multiple files containing each 1 million lines, and have written the current code to add it to the database:</p>
<pre><code>import os
import threading
from pymongo import MongoClient
class UserDb:
def __init__(self):
self.client = MongoClient('localhost', 27017)
self.data = self.client.large_data.data
threadlist = []
def start_add(listname):
db = UserDb()
with open(listname, "r") as r:
for line in r:
if line is None:
return
a = dict()
a['no'] = line.strip()
db.data.insert_one(a)
print(listname, "Done!")
for x in os.listdir(os.getcwd()):
if x.startswith('li'):
t = threading.Thread(target=start_add, args=(x,))
t.start()
threadlist.append(t)
print("All threads started!")
for thread in threadlist:
thread.join()
</code></pre>
<p>This starts as many threads as there are files, and adds every line to the db as it goes through it. The bad thing is that after 3 hours it had only added 8.630.623.</p>
<p>What can I do to add the records faster?</p>
<p>There are 261 threads currently running.</p>
<p>Example of one row of data: 12345678 (8 digits)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:00:44.607",
"Id": "450916",
"Score": "0",
"body": "How many parallel threads are running? (not the total number of files) I mean how many files are being added to the database simultaneously?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:04:05.917",
"Id": "450918",
"Score": "1",
"body": "At somepoint, you spend more time managing threads than using them. I am interested in seeing what one row of data looks like. I gather it's a scalar?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:21:59.093",
"Id": "450920",
"Score": "1",
"body": "I have seen your edit. You should visit https://codereview.stackexchange.com/help/merging-accounts to get your accounts merged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:23:45.503",
"Id": "450921",
"Score": "1",
"body": "Btw on own questions you can always comment (at least if you are using the same account)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:40:52.893",
"Id": "450925",
"Score": "0",
"body": "Are you sure the performance bottleneck is in this code? Is it chewing up 100% of the CPU? If not, maybe the problem is on the mongo side or IOPS. Until you find and fix the bottleneck other optimizations won't make it go much faster."
}
] |
[
{
"body": "<p>First, you need to consider that adding 271 million records is going to be long, there's no changing that. You should also consider your processing power. You could have the best code in the world, if it runs on an average computer it's going to be average.</p>\n\n<p>Now, what can be done better?</p>\n\n<p>What you're doing is called bulk insertion. There are mechanisms with every database engine that enable doing this faster than one insert at a time. For example, you should consider using the <a href=\"https://docs.mongodb.com/manual/reference/method/Bulk.insert/\" rel=\"noreferrer\">Bulk</a> object to insert many lines at the same time. Basically, you want most of your processing to be done by the database engine, simply because it was written by experts on how to do things fast and without problems. Looking at the <code>Bulk</code> object maximum size, your bulk insert cannot be bigger than 16 megabytes. Considering you have 8 digits number, you can figure out what's the biggest bulk insert you can do!</p>\n\n<p>Running 261 threads probably hurts your performance. After all, the 261 threads probably don't run in parallel (because.. I doubt you have 261 threads available, but who knows). Do more research of multi-threading, maybe using a simple parallel library with way less threads would even be faster. I've got to admit I'm not an expert in threading myself, but I'm pretty confident running 261 threads will simply hurt your performance, these threads need to be managed!</p>\n\n<p>Now, there are a couple things that bother me with your situation :</p>\n\n<ul>\n<li>How many files do you have? If you have like... a million files with 271 lines each, you should consider pre-processing the whole thing to reduce the number of file access necessary. I'd even consider keeping only 1 file.</li>\n<li>If you have <span class=\"math-container\">\\$2.71*10^8\\$</span> 8 digit numbers and, I didn't have my morning coffee yet, there are <span class=\"math-container\">\\$9*10^7\\$</span> possible combinations of 8 digits, you would have a lot of duplicates. Are you sure there isn't a simpler way to insert your data than reading 271000000 8 digits numbers from files?</li>\n</ul>\n\n<p>Anyways, I think the main thing you need to consider is using bulk insertion, which brings me to my final tip : Read the documentation of whatever database engine you're using. They are big pieces of code and it's pretty sure you will find something interesting to help you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T14:39:18.923",
"Id": "451073",
"Score": "0",
"body": "If leading zero's are a thing, then it would be 10^8 possible combinations. If not and we don't have silly things like zero-right-fill (I've seen it on StackOverflow once), then it's still 10^8. That's still 1.71 * 10^8 duplicates in a best-case scenario, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T15:00:10.083",
"Id": "451078",
"Score": "0",
"body": "@Gloweye I assumed there were no leading zeros, which means we have numbers from 10000000 to 99999999, which gives 9*10^7 possibilities? That's... right, isn't it? Unless I'm missing something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T15:02:42.600",
"Id": "451079",
"Score": "0",
"body": "I was thinking 8 positions, each with a possibility of 0 to 9. That's 10^8. Now, simply not printing leading 0's does not make it a different number. Our difference seems to be that I would consider 1234 a valid number, regardless of being written like 1234 or 00001234. If it's NOT a valid number, then you're right. I think."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T14:12:48.160",
"Id": "231265",
"ParentId": "231258",
"Score": "5"
}
},
{
"body": "<p>In order to make the comment by <a href=\"https://codereview.stackexchange.com/users/40395/ieatbagels\">@IEatBagels</a> made in <a href=\"https://codereview.stackexchange.com/a/231265/98493\">their answer</a> more explicit, you can just do this:</p>\n\n<pre><code>def start_add(file_name):\n db = UserDb()\n with open(file_name) as file:\n db.data.insert_many(\n ({\"no\": line.strip()} for line in file if line),\n ordered=False)\n print(file_name, \"Done!\")\n</code></pre>\n\n<p>Using the <code>ordered=False</code> option might actually already do what you want, which is let the server parallelize it if possible (taken from the <a href=\"https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many\" rel=\"nofollow noreferrer\">documentation</a>):</p>\n\n<blockquote>\n <p><code>ordered</code> (optional): If <code>True</code> (the default) documents will be\n inserted on the server serially, in the order provided. If an error\n occurs all remaining inserts are aborted. If <code>False</code>, documents will\n be inserted on the server in arbitrary order, possibly in parallel,\n and all document inserts will be attempted.</p>\n</blockquote>\n\n<p>This means you can probably just have one file, or, if you insist on it running in parallel on the computer running the script, use at most #CPU threads (potentially times two if you CPU supports <a href=\"https://en.wikipedia.org/wiki/Hyper-threading\" rel=\"nofollow noreferrer\">hyper-threading</a>).</p>\n\n<p>Note that I also followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, by using <code>lower_case</code> and used the fact that <code>\"r\"</code> is the default mode for opening files with <code>open</code>.</p>\n\n<p>The argument I passed to the call is a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a>, which means that the file does not even need to fit into memory all at once (the file object returned by <code>open</code> is also a kind of generator). Unfortunately, <code>insert_many</code> itself <a href=\"https://stackoverflow.com/q/37293900/4042267\">does just put them into a list</a>, although <a href=\"https://api.mongodb.com/python/current/examples/bulk.html?highlight=bulk%20insert#bulk-insert\" rel=\"nofollow noreferrer\">another page in the documentation</a> lead me to believe this is not the case:</p>\n\n<blockquote>\n <p>PyMongo will automatically split the batch into smaller sub-batches\n based on the maximum message size accepted by MongoDB, supporting very\n large bulk insert operations</p>\n</blockquote>\n\n<p>As mentioned in the above link, you can do the chunking yourself, though (directly in Python, or via different files as you already did).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:11:44.660",
"Id": "231303",
"ParentId": "231258",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T11:56:25.533",
"Id": "231258",
"Score": "7",
"Tags": [
"python",
"performance",
"mongodb",
"pymongo"
],
"Title": "Insert 271 million records from text file to mongodb"
}
|
231258
|
<p>I am currently developing a windows service in C# which is supposed to run a data import every day at configurable times. For this purpose I have created a class "ExecutionTime" which contains the attributes "Hour" and "Minute" to specify a time when the data import should be executed. When the service is started, the configured times are parsed into one ExecutionTime object each and those objects are then added to a list "executionTimes". I also created a class "Scheduler" which is responsible for checking if the data import should be executed and executing it once one of the configured times is reached.</p>
<p>I have already created a possible solution but I am not sure if my solution is considered "good practice" or if there are any edge cases when my code will not work the way it should. Could I therefore please get some feedback on my idea? Is it good? Can it still be improved?</p>
<p>My idea is to run the following code inside a while-loop:</p>
<pre><code>DateTime now = DateTime.Now;
foreach (ExecutionTime executionTime in executionTimes)
{
if (now.Hour == executionTime.Hour && now.Minute == executionTime.Minute
&& (lastExecutionTime.Hour < executionTime.Hour || lastExecutionTime.Minute < executionTime.Minute || lastExecutionTime < DateTime.Today))
{
PerformImport();
lastExecutionTime = now;
}
}
Thread.Sleep(1000);
</code></pre>
<p>Please do not suggest using scheduled tasks as a solution because that is not up for discussion, I have to implement this in a windows service.</p>
<p>I have already asked this question on <a href="https://stackoverflow.com/questions/58541127/how-to-run-some-code-at-certain-times-every-day">StackOverflow</a> but someone recommended to ask it here instead.</p>
<p>Thanks a lot in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:59:37.020",
"Id": "450930",
"Score": "0",
"body": "Welcome to Code Review. How many `ExecutionTime` objects will be in `executionTimes`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:27:17.267",
"Id": "450933",
"Score": "0",
"body": "@Heslacher Thank you! Currently there will be four objects in it. There is a possibility that more will be added in the future but I doubt it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:56:26.620",
"Id": "450936",
"Score": "1",
"body": "Take a look at https://www.quartz-scheduler.net/ it can be adjusted to your needs. Running inside a service won't be a problem either. If you click on the right side on \"Documentation\" you will see a \"Getting Started\" as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T14:14:48.143",
"Id": "450939",
"Score": "0",
"body": "@Heslacher Thank you for the idea! However, I'd like to avoid including yet another whole library into my project just to run my code at a few given times per day. I know that it is usually not a good idea to re-invent the wheel but this problem seemed simple enough to me that I can do it myself in a few lines of code. Could I please get some feedback regarding the code that I provided?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:22:38.347",
"Id": "451054",
"Score": "0",
"body": "It can start as a very simple task and evolve just so little that it can get messy to deal with while extending it. I definitely agree that you should use a well tested and a stable/reliable library if you can. Apart from **Quartz.Net** you can also take a look at https://www.hangfire.io."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:55:12.400",
"Id": "231260",
"Score": "1",
"Tags": [
"c#",
".net",
"datetime"
],
"Title": "Running some code every day at certain times"
}
|
231260
|
<p>I want to make testable network calls using Swift.</p>
<p>For example, I want to download the latest from AWS if and only if it's version is newer than the downloaded file.</p>
<p>In order to do this I've created a function:</p>
<pre><code>func requestDownloadLinkForAWS() {
DispatchQueue.global(qos: .background).async { [weak self] in
guard let self = self else {return}
// Hard coded download for testing - where will this compatibility file be hosted??
do {
let decoder = JSONDecoder()
if let dataResponse = content.data?[0]
{
if (dataResponse.appMinimumVersion >= appVersionString) && (dataResponse.appTargetVersion >= appVersionString) {
if let version = self.stagingBundle.getVersion()
{
if (version < dataResponse.version) {
self.downloadLatestFileAWS(dataResponse.bucketName, dataResponse.folderName, dataResponse.version)
}
}
}
}
}
} catch let error as NSError {
print ("\(error) 2 error")
}
}
}
</code></pre>
<p>Now my self.downloadLatestFileAWS is an async function that I can easily test. </p>
<p>My problem is to test the function above. There is no output here, but I need to test this function. What refactoring could I do to make this testable?</p>
|
[] |
[
{
"body": "<p>You can refactor this method (and <code>downloadLatestFileAWS</code>, too), to take an optional completion handler parameter:</p>\n\n<pre><code>func requestDownloadLinkForAWS(completion: @escaping ((Result<URL, Error>) -> Void)? = nil) {\n ...\n\n do {\n ...\n downloadLatestFileAWS(dataResponse.bucketName, dataResponse.folderName, dataResponse.version, completion: completion)\n } catch let error {\n completion?(.failure(error))\n }\n}\n\nfunc downloadLatestFileAWS(_ bucket: String, _ folder: String, _ version, completion: @escaping ((Result<URL, Error>) -> Void)? = nil) {\n ...\n completion?(.success(url)) // the file URL of the saved file\n}\n</code></pre>\n\n<p>Then you can test it:</p>\n\n<pre><code>func testDownload() {\n var result: String?\n\n let expectation = self.expectation(description: \"download\")\n requestDownloadLinkForAWS { result in\n if case .failure(_) = result {\n XCTFail(\"Download failed\")\n }\n expectation.fulfill()\n }\n wait(for: [expectation], timeout: 10)\n}\n</code></pre>\n\n<p>By the way, by adding a completion handler to the download method, it also offers you the opportunity to have the caller specify what UI updates should take place when the download is done. For example, you generally don’t want to bury those UI updates within <code>downloadLatestFileAWS</code>. Also, rather than just printing the error to the Xcode console, the caller can now specify what it wants to do when an error occurs.</p>\n\n<p>That having been said, you might not want to actually perform network requests in unit tests. You might, instead <a href=\"https://www.swiftbysundell.com/articles/mocking-in-swift/\" rel=\"nofollow noreferrer\">mock the network service</a>, or use <code>URLProtocol</code> to <a href=\"https://vojtastavik.com/2019/09/12/mocking-network-calls-using-urlprotocol/\" rel=\"nofollow noreferrer\">mock it behind the scenes</a>.</p>\n\n<p>But either way, you can make your methods testable by providing them with completion handler closures.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T23:24:17.650",
"Id": "231572",
"ParentId": "231261",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:50:08.700",
"Id": "231261",
"Score": "2",
"Tags": [
"swift"
],
"Title": "Testable network calls Swift"
}
|
231261
|
<p>I'm trying to improve my algorithm to make it faster. Also might help to have a few sets of eyes for any bugs or gaps in logic I didn't catch. One thing to note: because of the nature of the algorithm, there will be periods at the beginning and end of the data that are dead zones, where a peak/valley will not be detected.</p>
<p>The jist of the algorithm is to step through overlapping windows of the data, do some linear regression and pick out points by standard deviation. Because of the overlapping feature we can decide how many "angles" a point needs to be detected as a peak for it to be valid. Then we go and only take the highest peak from a group of consecutive peaks.</p>
<p>I have highly stationary data; what I may or may not want to detect as a peak varies, and I wanted the most robust algorithm so I can use something like Bayesian optimization to set the best parameters.</p>
<p>This is more or less how I'd like my algorithm to function for my specific use case; I'm not really looking for feedback on that, more on whether my code translates these goals correctly and if it's the most computationally efficient way to do things.</p>
<pre><code>def get_peak_valley(arr, threshold, window_size, overlap, req_angles):
# validate params
window_size = int(round(window_size))
req_angles = int(round(req_angles))
window_step = int(round(window_size * (1 - overlap)))
if window_step == 0:
window_step = 1
if req_angles == 0:
req_angles = 1
# get all points that classify as a peak/valley
ind = 0
peak_inds, valley_inds = [], []
while ind + window_size <= len(arr):
flattened = detrend(arr[ind:ind + window_size])
std, avg = np.std(flattened), np.mean(flattened)
lower_b = avg - std * threshold
upper_b = avg + std * threshold
for idx, val in enumerate(flattened):
if val < lower_b:
valley_inds.append(idx + ind)
elif val > upper_b:
peak_inds.append(idx + ind)
ind += window_step
# discard points that have counts below the threshold
peak_counts = Counter(peak_inds)
pk_inds = [c for c in peak_counts.keys() if peak_counts[c] >= req_angles]
valley_counts = Counter(valley_inds)
vly_inds = [c for c in valley_counts.keys() if valley_counts[c] >= req_angles]
# initialize iterator to find to best peak/valley for consecutive detections
if len(pk_inds) == 0 or len(vly_inds) == 0:
return pk_inds, vly_inds
if pk_inds[0] < vly_inds[0]:
curr_event = 'peak'
best_val = arr[pk_inds[0]]
else:
curr_event = 'valley'
best_val = arr[vly_inds[0]]
#iterate through points and only carry forward the index that has the highest or lowest value from the current group
best_ind, new_vly_inds, new_pk_inds = 0, [], []
event_inds = sorted(pk_inds + vly_inds)
for x in event_inds:
if x in pk_inds:
is_peak = True
else:
is_peak = False
if is_peak and curr_event == 'valley':
new_vly_inds.append(best_ind)
curr_event = 'peak'
best_val = arr[x]
best_ind = x
continue
if not is_peak and curr_event == 'peak':
new_pk_inds.append(best_ind)
curr_event = 'valley'
best_val = arr[x]
best_ind = x
continue
if is_peak and curr_event == 'peak' and arr[x] > best_val:
best_val = arr[x]
best_ind = x
elif not is_peak and curr_event == 'valley' and arr[x] < best_val:
best_val = arr[x]
best_ind = x
if curr_event == 'valley':
new_vly_inds.append(best_ind)
if curr_event == 'peak':
new_pk_inds.append(best_ind)
return new_pk_inds, new_vly_inds
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:20:26.520",
"Id": "450958",
"Score": "2",
"body": "Can you also add definition of `close_prices` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T11:41:46.363",
"Id": "451769",
"Score": "0",
"body": "Greetings! And Welcome! This question might get closed because there is not enough context. Can you help us by (1) providing imports (2) providing a sample input and output"
}
] |
[
{
"body": "<h2>Validation</h2>\n\n<pre><code># validate params\nwindow_size = int(round(window_size))\nreq_angles = int(round(req_angles))\nwindow_step = int(round(window_size * (1 - overlap)))\n</code></pre>\n\n<p>This does... some validation, but not a lot. It will validate that the arguments are numeric, but nothing else. If you cared about validation, you should probably also check ranges, especially that the window size and step are non-negative, etc.</p>\n\n<h2>Numpy vectorized conditionals</h2>\n\n<p>This:</p>\n\n<pre><code> for idx, val in enumerate(flattened):\n if val < lower_b:\n valley_inds.append(idx + ind)\n elif val > upper_b:\n peak_inds.append(idx + ind)\n</code></pre>\n\n<p>should not use a loop. Read about vectorized conditionals here:\n<a href=\"https://stackoverflow.com/questions/45768262/numpy-equivalent-of-if-else-without-loop#45768290\">https://stackoverflow.com/questions/45768262/numpy-equivalent-of-if-else-without-loop#45768290</a></p>\n\n<h2>Stricter events</h2>\n\n<pre><code> curr_event = 'peak'\n</code></pre>\n\n<p>shouldn't use a string. Use <code>enum.Enum</code> instead and include event values for <code>PEAK</code> and <code>VALLEY</code>.</p>\n\n<h2>Direct booleans</h2>\n\n<pre><code> if x in pk_inds:\n is_peak = True\n else:\n is_peak = False\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>is_peak = x in pk_inds\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T01:42:49.943",
"Id": "231291",
"ParentId": "231262",
"Score": "4"
}
},
{
"body": "<p>An extended and more comprehensive refactoring would require having more context to your current function: <em>calling context</em>, <em>how do the function's parameters are composed and related</em>, <em>what is <code>close_prices</code></em> ... </p>\n\n<p>But even with restricted context the posted function <code>get_peak_valley</code> has enough space (gaps) for restructuring and optimizations:</p>\n\n<p><strong><em>Rounding</strong> numeric arguments and ensuring limits:</em></p>\n\n<ul>\n<li><p><code>round</code> function. Python's <a href=\"https://docs.python.org/3/library/functions.html#round\" rel=\"nofollow noreferrer\"><code>round</code></a> function already returns rounded number as integer if precision is omitted, no need to cast to <code>int</code> (like <code>int(round(window_size))</code> ...). Negative numbers will be rounded to <code>0</code>.</p></li>\n<li><p>ensuring lower limit with </p>\n\n<pre><code>if window_step == 0:\n window_step = 1\nif req_angles == 0:\n req_angles = 1\n</code></pre>\n\n<p>can be replaced with convenient <code>max</code> function call, like <code>req_angles = max(round(req_angles), 1)</code></p></li>\n</ul>\n\n<p><strong><em>Primary</strong> \"peak\" and \"value\" indices:</em></p>\n\n<ul>\n<li><code>peak_inds, valley_inds = [], []</code>. Instead of declaring and accumulating separate lists which then will be feed to <code>Counter</code> - we can define and accumulate them as <em>counters</em> at once <code>peak_counts, valley_counts = Counter(), Counter()</code></li>\n</ul>\n\n<p><strong><em>Substitute Algorithm</em></strong> (<a href=\"https://refactoring.com/catalog/substituteAlgorithm.html\" rel=\"nofollow noreferrer\">Substitute Algorithm</a>) for \"stepping through overlapping windows\":</p>\n\n<ul>\n<li><p>the initial looping scheme:</p>\n\n<pre><code>ind = 0\nwhile ind + window_size <= len(arr):\n flattened = detrend(arr[ind:ind + window_size])\n ...\n ind += window_step\n</code></pre>\n\n<p>has more flexible equivalent:</p>\n\n<pre><code>arr_size = len(arr) # getting list size at once\nfor i in range(0, arr_size, window_step):\n flattened = detrend(arr[ind:ind + window_size])\n ...\n</code></pre></li>\n</ul>\n\n<p><a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\"><code>range</code></a> function has a convenient <code>step</code> option.</p>\n\n<p><em>New conception for <strong><code>Event</code></strong> and <strong><code>EventState</code></strong>:</em><br>\nThe proposed OOP approach is not primarily for performance, but for obtaining well-organized, structured and flexible code.<br>\nInstead of going to a mess of conditionals and switching between 2 exclusive events, we'll present an <em>event</em> as a <a href=\"https://docs.python.org/3/library/enum.html#intenum\" rel=\"nofollow noreferrer\">IntEnum</a> enumeration class with 2 values <code>0</code> and <code>1</code>. That will allow us to easily switch/swap to opposite event using bitwise XOR operator (<em>Bitwise XOR sets the bits in the result to 1 if either, but not both, of the corresponding bits in the two operands is 1</em>)</p>\n\n<pre><code>class Event(IntEnum):\n PEAK = 0\n VALLEY = 1\n</code></pre>\n\n<p>The class <code>EventState</code> represents the current event state with related <em>best</em> index, <em>best</em> price and the lists of <em>best</em> indices for each event type implemented conveniently as <code>self._event_indices = {Event.PEAK: [], Event.VALLEY: []}</code>. See the full definition in below code section.</p>\n\n<p><em>Trasersing through combined <code>event_inds</code> (last <code>for</code> loop):</em></p>\n\n<p>The first condition for setting <code>is_peak</code> flag should be simplified to the following <code>in_peak = x in pk_inds</code>. But, going further, we'll place a temp set <code>peak_ids_set = set(pk_inds)</code> before starting loop, for faster containment check on each loop iteration.<br>Then, changing the flag to <code>is_peak = x in peak_ids_set</code>.<br>\nAll seems good, but the flag is better with name <code>in_peak</code> (current item is contained <strong>in</strong> peak indices).<br>\nThat would support in solving next concern which is multiple conditions like <code>curr_event == 'valley'</code> and <code>curr_event == 'peak'</code>.<br> \nThe beneficial way is to apply <em>Extract variable</em> technique and extract those conditions at once as:</p>\n\n<pre><code>in_peak = x in peak_ids_set\nis_peak = event_state.event == Event.PEAK\nis_valley = event_state.event == Event.VALLEY\n</code></pre>\n\n<p>Two conditionals that have <code>continue</code> action are now collapsed into one due to flexible <code>EventState</code> behavior which allows to switch to next event (<code>event_state.switch</code> method), set best rate (index, price) with <code>event_state.set_best_rate</code> method and add best index to encapsulated internal lists for the needed event type (<code>event_state.add_best_index</code>).</p>\n\n<p>The final resulting <em>best</em> indices are covered and returned by <code>event_state.event_inices</code> property.</p>\n\n<hr>\n\n<p>The <strong>final</strong> version:</p>\n\n<pre><code>from collections import Counter\nfrom scipy.signal import detrend\nimport numpy as np\nfrom enum import IntEnum\n\n\nclass Event(IntEnum):\n PEAK = 0\n VALLEY = 1\n\n\nclass EventState:\n def __init__(self, event, close_prices, best_price, best_idx=0):\n self.event = event\n self._close_prices = close_prices\n self.best_price = best_price\n self.best_idx = best_idx\n self._event_indices = {Event.PEAK: [], Event.VALLEY: []}\n\n @property\n def event_inices(self):\n return tuple(self._event_indices.values())\n\n def switch(self):\n \"\"\"Switch event state (name)\"\"\"\n self.event ^= 1\n\n def set_best_rate(self, best_idx):\n self.best_price = self._close_prices[best_idx]\n self.best_idx = best_idx\n\n def add_best_index(self):\n self._event_indices[self.event].append(self.best_idx)\n\n\ndef get_peak_valley(arr, threshold, window_size, overlap, req_angles):\n # validate params\n window_size = round(window_size)\n req_angles = max(round(req_angles), 1)\n window_step = max(round(window_size * (1 - overlap)), 1)\n\n # get all points that classify as a peak/valley\n peak_counts, valley_counts = Counter(), Counter()\n arr_size = len(arr)\n\n for i in range(0, arr_size, window_step):\n flattened = detrend(arr[i:i + window_size])\n std, avg = np.std(flattened), np.mean(flattened)\n lower_b = avg - std * threshold\n upper_b = avg + std * threshold\n\n for idx, val in enumerate(flattened):\n if val < lower_b:\n valley_counts[idx + i] += 1\n elif val > upper_b:\n peak_counts[idx + i] += 1\n\n # discard points that have counts below the threshold\n pk_inds = [i for i, c in peak_counts.items() if c >= req_angles]\n vly_inds = [i for i, c in valley_counts.items() if c >= req_angles]\n\n # initialize iterator to find to best peak/valley for consecutive detections\n if len(pk_inds) == 0 or len(vly_inds) == 0:\n return pk_inds, vly_inds\n\n if pk_inds[0] < vly_inds[0]:\n curr_event, best_price = Event.PEAK, close_prices[pk_inds[0]]\n else:\n curr_event, best_price = Event.VALLEY, close_prices[vly_inds[0]]\n\n event_state = EventState(curr_event, close_prices=close_prices, best_price=best_price)\n event_inds = sorted(pk_inds + vly_inds)\n peak_ids_set = set(pk_inds)\n\n # iterate through points and only carry forward the index\n # that has the highest or lowest value from the current group\n for x in event_inds:\n in_peak = x in peak_ids_set\n is_peak = event_state.event == Event.PEAK\n is_valley = event_state.event == Event.VALLEY\n\n if (in_peak and is_valley) or (not in_peak and is_peak):\n event_state.add_best_index()\n event_state.switch()\n event_state.set_best_rate(best_idx=x)\n continue\n\n if (in_peak and is_peak and close_prices[x] > event_state.best_price) or \\\n (not in_peak and is_valley and close_prices[x] < event_state.best_price):\n event_state.set_best_rate(x)\n\n event_state.add_best_index()\n\n return event_state.event_inices\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:13:58.840",
"Id": "451091",
"Score": "0",
"body": "Look pretty good so far. I'll have to do some more testing though. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:37:36.270",
"Id": "451095",
"Score": "0",
"body": "@learningthemachine, please also consider the last edit (consolidate condition, the last `if` condition at the end `if (...) or (...): event_state.set_best_rate(x)`)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T14:36:44.157",
"Id": "231310",
"ParentId": "231262",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231310",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T13:53:27.920",
"Id": "231262",
"Score": "4",
"Tags": [
"python",
"performance",
"signal-processing"
],
"Title": "Peak and valley finding algorithm"
}
|
231262
|
<p>I made my custom heap, that allow to change and delete elements.</p>
<p>Please review it and tell me about any found bugs: <a href="https://bitbucket.org/nshatokhin/priorityqueue/src/master/" rel="nofollow noreferrer">https://bitbucket.org/nshatokhin/priorityqueue/src/master/</a></p>
<p>Is this implementation optimal? Is any better implementations exist?</p>
<pre class="lang-cpp prettyprint-override"><code> #pragma once
#include <cassert>
#include <cstdint>
#include <memory>
template<typename ObjectType, typename IdxType = uint32_t>
class PriorityQueue
{
public:
PriorityQueue(IdxType maxElements, ObjectType minusInfiniy, ObjectType plusInfinity) :
m_heapSize(0), m_maxSize(maxElements), m_minusInfinity(minusInfiniy), m_plusInfinity(plusInfinity)
{
assert(maxElements > 0);
m_objects = new ObjectType[m_maxSize];
m_externalIndices = new IdxType[maxElements];
m_internalIndices = new IdxType[maxElements];
for (IdxType i = 0; i < maxElements; i++)
{
m_externalIndices[i] = i;
m_internalIndices[i] = i;
}
}
~PriorityQueue()
{
delete[] m_objects;
delete[] m_externalIndices;
delete[] m_internalIndices;
}
IdxType heapSize() const
{
return m_heapSize;
}
ObjectType * objects()
{
return m_objects;
}
IdxType * indices()
{
return m_externalIndices;
}
IdxType * buildHeap(ObjectType * array, IdxType elementsCount)
{
assert(elementsCount <= m_maxSize);
std::memcpy(m_objects, array, sizeof(ObjectType)*elementsCount);
m_heapSize = elementsCount;
for (IdxType i = 0; i <= m_heapSize / 2; i++)
{
siftDown(m_heapSize / 2 - i);
}
return m_externalIndices;
}
ObjectType min()
{
if (m_heapSize == 0)
return m_plusInfinity;
return m_objects[0];
}
ObjectType extractMin()
{
if (m_heapSize == 0)
return m_plusInfinity;
ObjectType min = m_objects[0];
if (m_heapSize - 1 != 0)
{
exchangeObjects(0, m_heapSize - 1);
}
m_heapSize--;
siftDown(0);
return min;
}
IdxType insert(const ObjectType &obj)
{
assert(m_heapSize < m_maxSize);
m_heapSize++;
IdxType index = m_externalIndices[m_heapSize - 1];
m_objects[m_heapSize - 1] = obj;
siftUp(m_heapSize - 1);
return index;
}
void update(IdxType i, const ObjectType &obj)
{
assert(i < m_maxSize && m_internalIndices[i] < m_heapSize);
ObjectType &old = m_objects[m_internalIndices[i]];
if (old < obj)
{
old = obj;
siftDown(0);
}
else if (old > obj)
{
old = obj;
siftUp(m_internalIndices[i]);
}
}
void remove(IdxType i)
{
update(i, m_minusInfinity);
extractMin();
}
protected:
void exchangeObjects(IdxType obj1, IdxType obj2)
{
ObjectType tempObj = m_objects[obj1];
m_objects[obj1] = m_objects[obj2];
m_objects[obj2] = tempObj;
IdxType tempIdx = m_internalIndices[m_externalIndices[obj1]];
m_internalIndices[m_externalIndices[obj1]] = m_internalIndices[m_externalIndices[obj2]];
m_internalIndices[m_externalIndices[obj2]] = tempIdx;
tempIdx = m_externalIndices[obj1];
m_externalIndices[obj1] = m_externalIndices[obj2];
m_externalIndices[obj2] = tempIdx;
}
void siftDown(IdxType i)
{
IdxType left, right, j;
while (2 * i + 1 < m_heapSize)
{
left = 2 * i + 1;
right = 2 * i + 2;
j = left;
if (right < m_heapSize && m_objects[right] < m_objects[left])
{
j = right;
}
if (m_objects[i] <= m_objects[j])
{
break;
}
exchangeObjects(i, j);
i = j;
}
}
void siftUp(IdxType i)
{
IdxType parent = (i - 1) / 2;
while (i > 0 && m_objects[i] < m_objects[parent])
{
exchangeObjects(i, parent);
i = parent;
parent = (i - 1) / 2;
}
}
protected:
uint32_t m_heapSize, m_maxSize;
ObjectType * m_objects;
IdxType * m_externalIndices, * m_internalIndices;
ObjectType m_minusInfinity, m_plusInfinity;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:10:25.697",
"Id": "450956",
"Score": "0",
"body": "Could you summarise why you might use this in place of `std::priority_queue`? Is it the provision of element removal that's important?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:55:23.127",
"Id": "450961",
"Score": "0",
"body": "priority_queue can't update and delete elements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:20:17.497",
"Id": "450965",
"Score": "0",
"body": "D* lite needs object update and removal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T09:44:17.920",
"Id": "451036",
"Score": "0",
"body": "From binary heap to fibonacci heap is a (relatively) small step. Just an idea,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T10:26:50.840",
"Id": "451041",
"Score": "0",
"body": "@JoopEggen wow, I didn't know about it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T10:56:31.360",
"Id": "451043",
"Score": "1",
"body": "The principle being instead of splitting in half, spltting size fib(n) into fib(n-2) and fib(n-1) and vice versa. Idea is better memory utilisation. Tricky too."
}
] |
[
{
"body": "<p>Missing <code><cstring></code> header (needed for <code>std::memcpy()</code>). Conversely, we've included <code><memory></code> but declined to take advantage of what it provides.</p>\n\n<p>You have misspelt <code>std::uint32_t</code> (the template's default <code>IdxType</code>).</p>\n\n<p>Using bare <code>new[]</code> instead of a vector gives a serious bug when a <code>PriorityQueue</code> is copied (use after free, and double delete). It's simpler and safer to use a <code>std::vector</code> to manage the arrays for us.</p>\n\n<p>Giving external write access to the innards (<code>objects()</code>, <code>indices()</code>) allows outside code to break the object's invariants.</p>\n\n<p>The <code>buildHeap()</code> member applies <code>std::memcpy()</code> without checking whether that's safe for <code>ObjectType</code> objects - we should be using <code>std::move()</code> (from <code><algorithm></code>) instead:</p>\n\n<pre><code>std::move(array, array+elementsCount, m_objects);\n</code></pre>\n\n<p>It's surprising that this method takes a pointer to array of mutable objects; we could consider an overload for const objects - that would use <code>std::copy_n()</code> rather than <code>std::move()</code>:</p>\n\n<pre><code> IdxType * buildHeap(ObjectType const* array, IdxType elementsCount)\n {\n assert(elementsCount <= m_maxSize);\n\n std::copy_n(array, elementsCount, m_objects);\n</code></pre>\n\n<p>Also in this method, don't use <code>assert()</code> for checking that needs to occur in production builds - that's a macro compiles to nothing when <code>NDEBUG</code> is defined. We wouldn't need that test if we were using a vector for storage.</p>\n\n<p>Why are we writing our own heap algorithm instead of using <code>std::make_heap()</code> and related functions?</p>\n\n<p>Object counts are best represented as <code>std::size_t</code>, not <code>std::uint32_t</code>. <code>m_heapSize</code> and <code>m_maxSize</code> ought to be of type <code>IdxType</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:52:48.457",
"Id": "450959",
"Score": "0",
"body": "Oh, I forgot copy constructor :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:53:12.480",
"Id": "450960",
"Score": "0",
"body": "> we should be using std::move() instead\n\nHow to use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:57:58.593",
"Id": "450976",
"Score": "0",
"body": "`std::move(array, array+elementsCount, m_objects);`. (Albeit, the `ObjectType * array` perhaps should be `ObjectType const * array`, and we'd use `std::copy_n()` in that case - I'll mention something about that)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:05:13.243",
"Id": "450980",
"Score": "0",
"body": "Will std::move destroy original vector? I want to make copy of it, because many instances can use it for initialization\n\nApplied most of your comments: https://bitbucket.org/nshatokhin/priorityqueue/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:05:21.397",
"Id": "450981",
"Score": "0",
"body": "The raw pointers don't work well with copy construction or copy assignment; if you provide your own, then you'd also want to provide move constructor and move assignment. It's much simpler and safer to follow the Rule of Zero and delegate all that work to `std::vector`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:20:05.003",
"Id": "450983",
"Score": "0",
"body": "I've edited to show example. I hope that's clearer for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T19:36:02.833",
"Id": "450990",
"Score": "0",
"body": "I'd use `std::unique_ptr<T[]>` instead of `std::vector<T>` in this case. I don't think that this class needs a copy ctor or operator, and it doesn't utilize the `resize()` method of the vector, also the size is stored elsewhere. Though, it is not too significant."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:23:45.603",
"Id": "231269",
"ParentId": "231266",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231269",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T14:30:45.377",
"Id": "231266",
"Score": "0",
"Tags": [
"c++",
"heap"
],
"Title": "My implementation of binary heap"
}
|
231266
|
<p>This is my first program so no doubt I've made mistakes. The code works and meets all requirements as far as I can see.</p>
<p>(Further info: program to calculate Body Mass Index (BMI) allowing user to enter weight in stones and pounds or kilograms
It allows user to enter height in feet and inches or centimeters.</p>
<p>It then calculates BMI and displays the result.</p>
<p>I'm hoping to get a critical review of the code to identify any potential problems with it. I am open to any criticism and any suggestions on how I can improve the code and improve the overall quality.</p>
<pre><code>import java.util.Scanner;
import java.util.InputMismatchException;
public class BmiCalculatorWorking
{
static double totalIn;
static double kgs;
static double totalPound;
static double pounds;
static int stone;
static int feet;
static int inches;
static double cms;
static double totalCm;
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
boolean continueLoop = true;
do
{
try
{
System.out.println("Welcome to the BMI Calculator!\nYou"+
" may calculate your BMI in 1 of 2 ways:\n\n1. by"+
" entering Weight in stone and pounds and Height"+
" in feet and inches (Imperial) \nor\n2. by"+
" entering Weight in Kilograms and Height"+
" in Meters (Metric)");
while (true)
{
System.out.print("\nEnter 1 for Imperial OR Enter 2 for"+
" Metric: ");
int userInput;
userInput = input.nextInt();
if (userInput == 1)
{
bmiCalcImperial();
break;
}
else if (userInput == 2)
{
bmiCalcMetric();
break;
}
else
{
System.out.println("Invalid Input, please"+
" enter either 1 or 2");
continue;
}
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter"+
" numbers only. Please try again.\n" );
}
}while ( continueLoop );
}
public static void bmiCalcImperial()
{
Scanner input = new Scanner( System.in );
boolean continueLoop = true;
//ENTER WEIGHT IN STONE AND/OR POUNDS within range AND CONVERT TO KGS
do{
System.out.print("\nPlease enter your weight in Stone: ");
try{
stone = input.nextInt();
while (stone < 3 || stone > 30)
{
System.out.print("Please enter a valid weight (between 3 and"+
" 30 stone):");
stone = input.nextInt();
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter"+
" (St)numbers only. Please try again.\n" );
}
}while ( continueLoop );
continueLoop = true;
do{
System.out.print("Please enter your weight in Pounds: ");
try {
pounds = input.nextDouble();
while (pounds < 0 || pounds > 400)
{
System.out.print("Please enter a valid weight"+
" (between 0 and 400 pounds):");
pounds = input.nextDouble();
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter"+
" (Ibs)numbers only. Please try again.\n" );
}
}while ( continueLoop );
totalPound = stone*14 + pounds;
kgs = totalPound*0.45359237;
System.out.printf("Your weight in Kilograms is: %.3f", kgs);
System.out.print(" Kgs\n");
continueLoop = true;
//ENTER HEIGHT IN FEET AND/OR INCHES within range AND CONVERT TO CMS
do{
try{
System.out.print("\nPlease enter your Height in Feet: ");
feet = input.nextInt();
while (feet < 3 || feet > 7)
{
System.out.print("Please enter a valid Height (between"+
" 3 and 7 Feet):");
feet = input.nextInt();
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter (FEET)"+
"numbers only. Please try again.\n" );
}
}while ( continueLoop );
continueLoop = true;
do{
try{
System.out.print("Please enter your Height in Inches: ");
inches = input.nextInt();
while (inches < 0 || inches > 84)
{
System.out.print("Please enter a valid Height (between"+
" 0 and 84 inches):");
inches = input.nextInt();
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter"+
" (Inches)numbers only. Please try again.\n" );
}
}while ( continueLoop );
//converts feet and Inches to total Inches and then converts to centimetres
totalIn = feet*12 + inches;
totalCm = totalIn*2.54;
System.out.printf("Your height in Centimeters is: %.0f", totalCm);
System.out.print(" cms\n");
//Calculate BMI by converting from Imperial user input to metric
//and then using the metric formula
double ImperialToMetricBmi;
double InchesToMtrHeight;
InchesToMtrHeight = totalIn*2.54/100;
ImperialToMetricBmi = (kgs/(InchesToMtrHeight*InchesToMtrHeight));
System.out.printf("\nYour (converted to use Metric"+
" formula) BMI is: %.3f\n" ,ImperialToMetricBmi);
//Display BMI description based on Imperial user input
//calcualted with metric formula
if(ImperialToMetricBmi < 18.5)
{
System.out.println("You are underweight and are at risk of "+
"developing problems such as nutritional deficiency and "+
"osteoporosis.\nIt is recommended you seek professional"+
" medical advice.");
}
else
if (ImperialToMetricBmi >= 18.5 && ImperialToMetricBmi <= 24.9)
{
System.out.println("You are a healthy, normal weight");
}
else
if (ImperialToMetricBmi >= 25 && ImperialToMetricBmi <= 29.9)
{
System.out.println("You are overweight and are at"+""
+ " moderate risk of developing"+"\n"
+ " heart disease, high blood pressure,"+
" stroke, diabetes.\n It is recommended "+
"you lose weight through exercise and"+
" a healthy diet.");
}
else
if (ImperialToMetricBmi > 30 )
{
System.out.println("You are obese and are at"+
" High risk of developing heart"+
" disease, high blood pressure,"+
" stroke, diabetes. It is recommended"+
" you seek professional"+
" medical advice. ");
}
}
public static void bmiCalcMetric()
{
Scanner input = new Scanner(System.in);
boolean continueLoop = true;
//ENTER WEIGHT IN KGS AND CONVERT TO STONE AND POUNDS
double mtr;
double bmi;
do{
try{
System.out.print("\nPlease enter your weight in Kilograms: ");
kgs = input.nextDouble();
while (kgs < 20 || kgs > 180)
{
System.out.print("Please enter a valid weight "+
"(between 20 and 180kgs):");
kgs = input.nextDouble();
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter (KGS)"+
"numbers only. Please try again.\n" );
}
}while (continueLoop);
//note: Converts kgs to ibs **But not St AND Ibs !!**
pounds = kgs*2.204622;
System.out.printf("Your weight in pounds is: %.0f" ,pounds);
System.out.print(" Ibs\n");
continueLoop = true;
do{
try{
System.out.print("\nPlease enter your Height in Centimeters: ");
cms = input.nextInt(); //should this be .nextDouble?
while (cms < 91 || cms > 213)
{
System.out.print("Please enter a valid Height (between"+
" 91 and 213cms):");
cms = input.nextDouble();
}
continueLoop = false;
}
catch ( InputMismatchException inputMismatchException)
{
System.err.printf( "\nException: %s\n", inputMismatchException );
input.nextLine();
System.out.println("Input invalid! You must enter (cms)"+
"numbers only. Please try again.\n" );
}
}while (continueLoop);
totalIn = cms/2.54;
System.out.printf("\nYour height in inches is: %.0f" ,totalIn);
System.out.print( "\" \n");
//Calculate BMI
mtr = cms/100;
bmi = (kgs/(mtr*mtr));
//Display BMI
System.out.printf("\nYour BMI is: %.3f\n" ,bmi);
//Display BMI description
if(bmi < 18.5)
{
System.out.println("\nYou are underweight");
}
else
if (bmi >= 18.5 && bmi <= 24.999)
{
System.out.println("\nYou are a healthy, normal weight");
}
else
if (bmi >= 25 && bmi <= 29.999)
{
System.out.println("\nYou are overweight");
}
else
if (bmi > 30 )
{
System.out.println("\nYou are obese");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T17:23:17.320",
"Id": "450968",
"Score": "6",
"body": "Hi Julie, please include more context in your post. Also, maybe you've had some problem with indenting your code when posting it here? Try to fix it if that's not how you see code in your IDE. Otherwise surely a review element would be code indentation :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:44:10.993",
"Id": "450984",
"Score": "1",
"body": "I'm assuming BMI means Body Mass Index, but I could be wrong. That is probably what @IEatBagels is referring to. Please describe it in a little more detail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T21:27:29.837",
"Id": "450994",
"Score": "2",
"body": "@IEatBagels Post edited to include full context of what the program does.\nThanks for mentioning Indentation, I thought it was correct(ish) but is it indented too much?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T21:29:38.317",
"Id": "450995",
"Score": "1",
"body": "@pacmaninbw Yes, Body Mass Index, I've edited my post to include all details of what the program does. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:11:42.080",
"Id": "451119",
"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)*."
}
] |
[
{
"body": "<p><code>BmiCalculatorWorking</code> This name is confusing. All code should eventually be 'working'.</p>\n\n<p>Don't use static for all variables. I can only guess you did this to avoid the warning about calling non-static variables from a static method.</p>\n\n<p>Instead, you can instantiate a BmiCalculatorWorking, and call the methods on the object.</p>\n\n<p>You should never use <code>while(true)</code>, instead put the condition inside the while loop.</p>\n\n<p>If you've learned how to create methods, you should start practicing making them. It'll make your code much easier to read & much easier to refactor. For example, printing out the welcome message could be a method.</p>\n\n<p>This can be shortened to: <code>int userInput = input.nextInt();</code></p>\n\n<pre><code>int userInput;\nuserInput = input.nextInt();\n</code></pre>\n\n<p><code>bmiCalcImperial</code> is a really bad name for a method. It's not descriptive. This method is also doing waaaaay too much. Methods should only do 1 thing. This becomes easy when you name your methods descriptively. For example, this method would have a really long & awkward name.</p>\n\n<p><code>continueLoop</code> is a bad name. Try to give descriptive names. Naming it continueLoop because it's used in a while statement is silly.</p>\n\n<p>Just want to further emphasis that breaking this down into methods would substantially increase readability. Even for yourself. For example when trying to figure out your own errors or add functionality.</p>\n\n<p>Indentation also plays a huge part in readability. An IDE will help you with this but I understand some college/university courses start off disallowing an IDE and I will assume that's the case here.</p>\n\n<p>You shouldn't shorten variables names. <code>bmi</code> is okay, but I can't think of what <code>cms</code>, <code>mtr</code> stand for. Even if it's obvious, the computer doesn't care about how long your variable names are and you aren't saving much time by shortening them. It's not a big deal here but something to keep in mind for future programs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T23:15:34.290",
"Id": "450998",
"Score": "3",
"body": "*Just want to further emphasis that breaking this down into methods would substantially increase readability.* Yes, that's an important critique of this code. Writing one big blob of code like this is an anti-pattern (but also common for beginners)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:57:58.640",
"Id": "451116",
"Score": "0",
"body": "@dustytrash All advice taken into account\nI've spent many hours researching your comments and have made a lot of changes\n-I'll change the name\n-I think I've instantiated to call methods\n-I don't know any other way but {while(true)} Can't figure out how to put inside loop. Can you give an example?\n-I now have 9 methods instead of 3. bmiCalcImperial now split into 3 methods\n-What would be a better name than {continueLoop}?\n-I've changed var names to be clear"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:58:43.083",
"Id": "451117",
"Score": "0",
"body": "I'm still confused about static/non-static methods but my revised code works (apart from the int = double*2.2 problem which I am working on now).\nWill I enter my revised code above or should I create a new post as it's very different? Thank you all."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T22:14:17.070",
"Id": "231283",
"ParentId": "231271",
"Score": "4"
}
},
{
"body": "<p><strong>Dependency Management</strong></p>\n\n<p>The Scanner is a dependency in each of the 3 methods and may be difficult to unit test around. </p>\n\n<p><strong>Magic Numbers</strong></p>\n\n<p>Explicit numbers used should be wrapped in a constant to better explain its purpose. 0.45359237 is an example of this. It is difficult to understand what some of these numbers are used for unless you are deep in the implementation details.</p>\n\n<p><strong>Object-Oriented Composition Opportunity</strong></p>\n\n<p>We aren't really using object-oriented tools provided by Java. There is only one class used in a very procedural way.</p>\n\n<p>I created a design to help practice object-oriented composition. Instead of one main class calling two methods within your single calculator class, my design creates three new classes. One base class called BMICalculation. Then two more specific subclasses that inherit from that base class called ImperialBMICalculation and MetricBMICalculation. In the constructor for the two subclasses, you will put the user prompt to get the height and weight information for the calculation of each type. Also during construction, you can calculate the BMI for the object and use it to populate a results string on each object. BMICalculation will have methods that will be overridden by the subclasses such as displaying the result of a particular calculation. This gives you the option to create many instances of BMI calculation objects or be able to attach the object to something like a person object.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Great start! I like the exception handling and attention to detail. I hope this feedback helps and I will leave my live code review below.</p>\n\n<p>Live code review: <a href=\"https://youtu.be/RMJWdH2dQXU\" rel=\"nofollow noreferrer\">https://youtu.be/RMJWdH2dQXU</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:43:46.600",
"Id": "231433",
"ParentId": "231271",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231283",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:51:23.590",
"Id": "231271",
"Score": "2",
"Tags": [
"java",
"beginner",
"validation",
"error-handling"
],
"Title": "Beginning BMI calculator in Java"
}
|
231271
|
<p>Let me preface this with a few things before I get into my question: </p>
<ul>
<li>I am making the leap from <code>VBA/VB6</code> to .NET, (boy is it a big one), so I am noob to .NET best practices and so on.</li>
<li>I am re-writing en existing excel add-in (written in <code>VBA</code>) that has a library of subs and functions which are used to execute queries and return their results back to excel. I am modifying these functions to optionally return arrays, which means that I need to materialize a query's results in a .NET <code>DataReader</code>, then into a 2-D array with as little overhead as possible. </li>
<li>And yes, I am fully aware that there are several tried and tested ORM's out there that have various methods for mapping data to strongly typed objects (or even dynamics), but there are over 50 functions in this add-in (soon to be more), and the end goal is to return a 2-d array. It is not feasible to write 50 or more classes (or to use anonymous classes) to map the data into a generic list, only to then convert said list into an array. </li>
</ul>
<p>Saying all of that, I am looking for improvements/suggestions for some methods that I have written to map a query in to a dynamic array. Async execution is on my radar, but I just don't yet have the knowledge on how I could leverage that to populate the array; however, if any one else does, I am all ears. </p>
<p><strong>Class:</strong> ADOWrapper
As per @JesseC.Slicer's request I have included my <code>ADOWrapper</code> class </p>
<pre><code>public class ADOWrapper
{
private System.Data.Common.DbProviderFactory dbProvider;
private int commandTimeOut;
private bool deriveParameters;
//constructor
public ADOWrapper(string providerName, int commandTimeOut = 0, bool deriveParameters = false)
{
this.dbProvider = DbProviderFactories.GetFactory(providerName);
this.commandTimeOut = commandTimeOut;
this.deriveParameters = deriveParameters;
}
//Method
public IEnumerable<object[]> ExecuteQuery (
System.Data.CommandType commandType,
string commandText, string connectionString,
params KeyValuePair<String, Object>[] parameterValues
)
{
using (IDbConnection connection = this.dbProvider.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
IDbCommand command = connection.CreateCommand();
command.CommandText = commandText;
command.CommandType = commandType;
command.CommandTimeout = this.commandTimeOut;
if (!((parameterValues == null) || (parameterValues.Length == 0)))
command = GetParameterizedCommand(command, parameterValues);
using (IDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
var indices = Enumerable.Range(0, reader.FieldCount).ToArray();
foreach (IDataRecord record in reader as System.Collections.IEnumerable)
yield return indices.Select(i => record[i]).ToArray();
}
}
}
private IDbCommand GetParameterizedCommand(System.Data.IDbCommand command, params KeyValuePair<String, Object>[] parameterValues)
{
//can only derive parameters if it is a stored proc
if (this.deriveParameters && command.CommandType == System.Data.CommandType.StoredProcedure)
{
DerivedParameters parameterMapper = new DerivedParameters();
command = parameterMapper.AssignParameters(this.dbProvider, command, parameterValues);
}
else if (!this.deriveParameters)
{
AssummedParameters parameterMapper = new AssummedParameters();
command = parameterMapper.AssignParameters(command, parameterValues);
}
else
{
throw new System.ArgumentException("Parameter cannot be of type 'Text' if deriveParameters is set to true", "commandType");
}
return command;
}
}
internal class DerivedParameters
{
public IDbCommand AssignParameters(DbProviderFactory dbProvider, IDbCommand command, params KeyValuePair<String, Object>[] parameterValues)
{
DbCommandBuilder commandBuilder = dbProvider.CreateCommandBuilder();
//uses reflection to get method
MethodInfo method = commandBuilder.GetType().GetMethod("DeriveParameters", BindingFlags.Public | BindingFlags.Static);
method.Invoke(null, new object[] { command });
if (command.Parameters.Count == 0)
return command;
IDbDataParameter defaultParam = (IDbDataParameter)command.Parameters[0];
/*
skip first value in collection if there exists a defualt
return value
*/
int i = (defaultParam.ParameterName == "@RETURN_VALUE") ? 1 : 0;
foreach (KeyValuePair<String, Object> paramKVP in parameterValues)
{
IDbDataParameter param = (IDbDataParameter)command.Parameters[i];
if (paramKVP.Key != param.ParameterName)
throw new System.ArgumentException("The specified parameter does not have a"
+ "corresponding match in the database",
paramKVP.Key);
param = SetCommonProperties(param, paramKVP.Value.ToString());
param.Value = paramKVP.Value ?? System.DBNull.Value;
i++;
}
return command;
}
private IDbDataParameter SetCommonProperties(IDbDataParameter parameter, string parameterValue)
{
switch (parameter.DbType)
{
case DbType.Single:
if (Single.TryParse(parameterValue, out Single singleValue))
{
parameter.Precision = NumericDataAttributes.CalculatePrecision(singleValue);
parameter.Scale = NumericDataAttributes.CalculateNumericScale(singleValue);
}
break;
case DbType.Double:
if (double.TryParse(parameterValue, out double doubleValue))
{
parameter.Precision = NumericDataAttributes.CalculatePrecision(doubleValue);
parameter.Scale = NumericDataAttributes.CalculateNumericScale(doubleValue);
}
break;
case DbType.Decimal:
if (decimal.TryParse(parameterValue, out decimal decimalValue))
{
parameter.Precision = NumericDataAttributes.CalculatePrecision(decimalValue);
parameter.Scale = NumericDataAttributes.CalculateNumericScale(decimalValue);
}
break;
case DbType.String:
parameter.Size = parameterValue.Length;
break;
};
return parameter;
}
}
internal class AssummedParameters
{
public IDbCommand AssignParameters(IDbCommand command, params KeyValuePair<String, Object>[] parameterValues)
{
foreach (KeyValuePair<String, Object> paramKVP in parameterValues)
{
IDbDataParameter param = command.CreateParameter();
param.ParameterName = paramKVP.Key;
param = SetCommonProperties(param, paramKVP.Value.ToString());
param.Value = paramKVP.Value ?? System.DBNull.Value;
param.Direction = ParameterDirection.Input;
command.Parameters.Add(param);
}
return command;
}
private IDbDataParameter SetCommonProperties(IDbDataParameter parameter, string parameterValue)
{
if (byte.TryParse(parameterValue, out byte byteValue))
parameter.DbType = DbType.Byte;
else if (sbyte.TryParse(parameterValue, out sbyte sbyteValue))
parameter.DbType = DbType.SByte;
else if (Int16.TryParse(parameterValue, out Int16 smallintValue))
parameter.DbType = DbType.Int16;
else if (Int32.TryParse(parameterValue, out Int32 intValue))
parameter.DbType = DbType.Int32;
else if (Int64.TryParse(parameterValue, out Int64 bigintValue))
parameter.DbType = DbType.Int64;
else if (Single.TryParse(parameterValue, out Single singleValue))
{
parameter.DbType = DbType.Single;
parameter.Precision = NumericDataAttributes.CalculatePrecision(singleValue);
parameter.Scale = NumericDataAttributes.CalculateNumericScale(singleValue);
}
else if (double.TryParse(parameterValue, out double doubleValue))
{
parameter.DbType = DbType.Double;
parameter.Precision = NumericDataAttributes.CalculatePrecision(doubleValue);
parameter.Scale = NumericDataAttributes.CalculateNumericScale(doubleValue);
}
else if (decimal.TryParse(parameterValue, out decimal decimalValue))
{
parameter.DbType = DbType.Decimal;
parameter.Precision = NumericDataAttributes.CalculatePrecision(decimalValue);
parameter.Scale = NumericDataAttributes.CalculateNumericScale(decimalValue);
}
else if (DateTime.TryParse(parameterValue, out DateTime dateValue))
parameter.DbType = DbType.DateTime;
else if (bool.TryParse(parameterValue, out bool boolValue))
parameter.DbType = DbType.Boolean;
else if (parameter.DbType == DbType.String)
parameter.Size = parameterValue.Length;
return parameter;
}
}
internal class NumericDataAttributes
{
//2 overload methods (makes for a total of 3 per each of CalculatePrecision and CalculateNumericScale)
public static byte CalculatePrecision(Single valueIn)
{
return (byte)valueIn.ToString(CultureInfo.InvariantCulture).Replace(".", "").Length;
}
public static byte CalculateNumericScale(Single valueIn)
{
return (byte)valueIn.ToString(CultureInfo.InvariantCulture).Split('.')[1].Length;
}
public static byte CalculatePrecision(double valueIn)
{
return (byte)valueIn.ToString(CultureInfo.InvariantCulture).Replace(".", "").Length;
}
public static byte CalculateNumericScale(double valueIn)
{
return (byte)valueIn.ToString(CultureInfo.InvariantCulture).Split('.')[1].Length;
}
public static byte CalculatePrecision(decimal valueIn)
{
return (byte)valueIn.ToString(CultureInfo.InvariantCulture).Replace(".", "").Length;
}
public static byte CalculateNumericScale(decimal valueIn)
{
return (byte)valueIn.ToString(CultureInfo.InvariantCulture).Split('.')[1].Length;
}
}
</code></pre>
<p>}</p>
<p><strong>Usage:</strong> </p>
<pre><code>static void Main(string[] args)
{
string connString = "Persist Security Info=False;User ID=***;Password=***;Initial Catalog=***;Server=*****";
ADOWrapper SQLDataAdapter = new ADOWrapper("System.Data.SqlClient", 0, false);
var queryResult = SQLDataAdapter.ExecuteQuery(CommandType.Text, "Select * From TABLE_NAME",
connString).ToArray();
object[,] twoDArray = new object[queryResult.Length, queryResult.Max(x => x.Length)];
Get2dArrayFromJagged(queryResult, twoDArray);
Print2DArray(twoDArray);
Console.ReadLine();
}
public static void Get2dArrayFromJagged(object[][] jaggedArray, object[,] returnArray)
{
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
returnArray[i, j] = jaggedArray[i][j];
}
}
}
public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write("|" + matrix[i, j] + "|" + "\t");
}
Console.WriteLine();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T21:57:57.967",
"Id": "450996",
"Score": "1",
"body": "`IDbCommand` inherits from `IDisposable` and should also be wrapped in a `using` construct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T22:40:19.573",
"Id": "450997",
"Score": "0",
"body": "@JesseC.Slicer indeed. I probably could go without setting the connection behavior as well , b/c ‘IDataReader’ also inherits from ‘IDisposible’"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T11:40:27.013",
"Id": "451048",
"Score": "0",
"body": "@JesseC.Slicer Actually, I take that back. Wrapping `IDbCommand` in a using construct yields the \"cannot assign to to 'command' because it is a 'using variable'\" error, b/c I have `command = GetParameterizedCommand(command, parameterValues);` . As a work around, I suppose that I could use `try/catch` for `IDbCommand` and call `Dispose()` explicitly at the bottom of the `try` block and in the `catch` block. But the idea of having to do that makes me think that I should restructure the method so that I could utilize the `using` statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T14:47:33.143",
"Id": "451075",
"Score": "0",
"body": "Cam you add the code for `GetParameterizedCommand`? I feel there's some deeper issues now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:46:04.953",
"Id": "451099",
"Score": "0",
"body": "@JesseC.Slicer I'll do you one better and post the whole class, because it's relevant. I haven't implemented all the methods and overloads that I plan to yet because I am still very much in the development stage. Saying that, the whole using `KeyValuePair<string,object>` within a `param` array will be relpaced by a generic `dictionary<string, object>` w/o using `param`."
}
] |
[
{
"body": "<p>The current</p>\n\n<pre><code>foreach (IDataRecord record in reader as System.Collections.IEnumerable)...\n</code></pre>\n\n<p>seem complicated for no particular reason and is making assumptions about implementation concerns.</p>\n\n<p>With all that effort to make the function abstract I would suggest keep the reader traversal simple. </p>\n\n<pre><code>//...\n\nusing (IDataReader reader = command.ExecuteReader()) {\n var indices = Enumerable.Range(0, reader.FieldCount).ToArray();\n while (reader.Read()) {\n yield return indices.Select(i => reader[i]).ToArray();\n }\n}\n\n//...\n</code></pre>\n\n<p>Parameter values check condition can be simplified using a null conditional to</p>\n\n<pre><code>//...\n\nif (parameterValues?.Length > 0)\n //...\n\n//...\n</code></pre>\n\n<p>If <code>parameterValues</code> is null the condition will default to <code>false</code></p>\n\n<p><code>command</code> should be wrapped in a <code>using</code> statement but cannot because of how it is passed and reassign in the supporting methods. </p>\n\n<p>Since all those method only modify the variable, they should be refactored to reflect that</p>\n\n<pre><code>private void SetCommandParameters(IDbCommand command, params KeyValuePair<String, Object>[] parameterValues) {\n //can only derive parameters if it is a stored proc\n if (this.deriveParameters && command.CommandType == System.Data.CommandType.StoredProcedure) {\n\n DerivedParameters parameterMapper = new DerivedParameters();\n parameterMapper.AssignParameters(this.dbProvider, command, parameterValues);\n\n } else if (!this.deriveParameters) {\n\n AssummedParameters parameterMapper = new AssummedParameters();\n parameterMapper.AssignParameters(command, parameterValues);\n\n } else {\n throw new System.ArgumentException(\"Parameter cannot be of type 'Text' if deriveParameters is set to true\", \"commandType\");\n }\n}\n</code></pre>\n\n<p>Note the name change.</p>\n\n<p>The <code>ExecuteQuery</code> becomes</p>\n\n<pre><code>public IEnumerable<object[]> ExecuteQuery(CommandType commandType, string commandText, string connectionString, params KeyValuePair<String, Object>[] parameterValues) {\n using (IDbConnection connection = this.dbProvider.CreateConnection()) {\n connection.ConnectionString = connectionString;\n connection.Open();\n using (IDbCommand command = connection.CreateCommand()) {\n command.CommandText = commandText;\n command.CommandType = commandType;\n command.CommandTimeout = this.commandTimeOut;\n\n if (parameterValues?.Length > 0)\n SetCommandParameters(command, parameterValues);\n\n using (IDataReader reader = command.ExecuteReader()) {\n var indices = Enumerable.Range(0, reader.FieldCount).ToArray();\n while (reader.Read()) {\n yield return indices.Select(i => reader[i]).ToArray();\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>While I applaud the effort to make the code abstract, it still tightly couples itself to implementation concerns.</p>\n\n<p>Based on a review of the current implementation's dependency on <code>DbProviderFactory</code>, the following abstraction and default implementation was derived.</p>\n\n<pre><code>public interface IDbProviderFactory {\n IDbConnection CreateConnection(string connectionString);\n DbCommandBuilder CreateCommandBuilder();\n}\n\npublic class DefaultDbProviderFactory : IDbProviderFactory {\n private readonly DbProviderFactory dbProvider;\n\n public DefaultDbProviderFactory(string providerName) {\n dbProvider = DbProviderFactories.GetFactory(providerName);\n }\n\n public DbCommandBuilder CreateCommandBuilder() => dbProvider.CreateCommandBuilder();\n\n public IDbConnection CreateConnection(string connectionString) {\n var connection = dbProvider.CreateConnection();\n connection.ConnectionString = connectionString;\n return connection;\n }\n}\n</code></pre>\n\n<p>Along with an aggregation of the run-time dependencies into a POCO.</p>\n\n<pre><code>public class ADOWrapperOptions {\n public string ConnectionString { get; set; }\n public int CommandTimeOut { get; set; } = 0;\n public bool DeriveParameters { get; set; } = false;\n}\n</code></pre>\n\n<p>With the parameter helpers also refactored accordingly </p>\n\n<p>DerivedParameters</p>\n\n<pre><code>internal class DerivedParameters {\n public void AssignParameters(IDbProviderFactory dbProvider, IDbCommand command, KeyValuePair<String, Object>[] parameterValues) {\n\n DbCommandBuilder commandBuilder = dbProvider.CreateCommandBuilder();\n //uses reflection to get method\n MethodInfo method = commandBuilder.GetType().GetMethod(\"DeriveParameters\", BindingFlags.Public | BindingFlags.Static);\n method.Invoke(null, new object[] { command });\n\n if (command.Parameters.Count == 0)\n return;\n\n IDbDataParameter defaultParam = (IDbDataParameter)command.Parameters[0];\n\n /* \n skip first value in collection if there exists a defualt \n return value \n */\n int i = (defaultParam.ParameterName == \"@RETURN_VALUE\") ? 1 : 0;\n\n foreach (KeyValuePair<String, Object> paramKVP in parameterValues) {\n\n IDbDataParameter param = (IDbDataParameter)command.Parameters[i];\n\n if (paramKVP.Key != param.ParameterName)\n throw new System.ArgumentException(\"The specified parameter does not have a\"\n + \"corresponding match in the database\",\n paramKVP.Key);\n\n SetCommonProperties(param, paramKVP.Value.ToString());\n param.Value = paramKVP.Value ?? System.DBNull.Value;\n i++;\n }\n }\n\n //... omitted for brevity\n}\n</code></pre>\n\n<p>AssummedParameters </p>\n\n<pre><code>internal class AssummedParameters {\n public void AssignParameters(IDbCommand command, KeyValuePair<String, Object>[] parameterValues) {\n\n foreach (KeyValuePair<String, Object> paramKVP in parameterValues) {\n IDbDataParameter param = command.CreateParameter();\n param.ParameterName = paramKVP.Key;\n param.Value = paramKVP.Value ?? System.DBNull.Value;\n param.Direction = ParameterDirection.Input;\n\n SetCommonProperties(param, paramKVP.Value.ToString());\n\n command.Parameters.Add(param);\n }\n }\n\n //...omitted for brevity\n}\n</code></pre>\n\n<p>There is potential to create some form of strategy abstraction in a future refactor</p>\n\n<p>After refactoring, the wrapper becomes </p>\n\n<pre><code>public class ADOWrapper {\n private readonly IDbProviderFactory dbProvider;\n private readonly int commandTimeOut;\n private readonly bool deriveParameters;\n private readonly string connectionString;\n\n //constructor\n public ADOWrapper(IDbProviderFactory dbProvider, ADOWrapperOptions options) {\n this.dbProvider = dbProvider;\n commandTimeOut = options.CommandTimeOut;\n deriveParameters = options.DeriveParameters;\n connectionString = options.ConnectionString;\n }\n\n //Method\n public IEnumerable<object[]> ExecuteQuery(CommandType commandType, string commandText, params KeyValuePair<String, Object>[] parameterValues) {\n using (IDbConnection connection = dbProvider.CreateConnection(connectionString)) {\n connection.Open();\n using (IDbCommand command = connection.CreateCommand()) {\n command.CommandText = commandText;\n command.CommandType = commandType;\n command.CommandTimeout = commandTimeOut;\n\n if (parameterValues?.Length > 0)\n SetCommandParameters(command, parameterValues);\n\n using (IDataReader reader = command.ExecuteReader()) {\n var indices = Enumerable.Range(0, reader.FieldCount).ToArray();\n while (reader.Read()) {\n yield return indices.Select(i => reader[i]).ToArray();\n }\n }\n }\n }\n }\n\n private void SetCommandParameters(IDbCommand command, params KeyValuePair<String, Object>[] parameterValues) {\n //can only derive parameters if it is a stored proc\n if (this.deriveParameters && command.CommandType == System.Data.CommandType.StoredProcedure) {\n DerivedParameters parameterMapper = new DerivedParameters();\n parameterMapper.AssignParameters(this.dbProvider, command, parameterValues);\n } else if (!this.deriveParameters) {\n AssummedParameters parameterMapper = new AssummedParameters();\n parameterMapper.AssignParameters(command, parameterValues);\n } else {\n throw new System.ArgumentException(\"Parameter cannot be of type 'Text' if deriveParameters is set to true\", \"commandType\");\n }\n }\n}\n</code></pre>\n\n<p>The example usage now look like the following</p>\n\n<pre><code>string connString = \"Persist Security Info=False;User ID=***;Password=***;Initial Catalog=***;Server=*****\";\n\nIDbProviderFactory provider = new DefaultDbProviderFactory(\"System.Data.SqlClient\");\n\nADOWrapperOptions options = new ADOWrapperOptions() {\n ConnectionString = connString\n};\n\nADOWrapper SQLDataAdapter = new ADOWrapper(provider, options);\n\nvar queryResult = SQLDataAdapter.ExecuteQuery(CommandType.Text, \"Select * From TABLE_NAME\").ToArray();\n\nobject[,] twoDArray = new object[queryResult.Length, queryResult.Max(x => x.Length)];\n\nGet2dArrayFromJagged(queryResult, twoDArray);\n\n//...\n</code></pre>\n\n<p>And having the abstracted dependency allows the wrapper the flexibility to be tested in isolation.</p>\n\n<p>Simple example</p>\n\n<pre><code>[TestClass]\npublic class ADOWrapperTests {\n [TestMethod]\n public void ExecuteQuery_Should_Return_One_Row_Two_Columns() {\n //Arrange - Using Moq\n var reader = new Mock<IDataReader>();\n reader.Setup(_ => _.FieldCount).Returns(2);\n reader.Setup(_ => _[0]).Returns(\"Hello World\");\n reader.Setup(_ => _[1]).Returns(\"I am working\");\n reader.SetupSequence(_ => _.Read())\n .Returns(true)\n .Returns(false);\n\n var provider = Mock.Of<IDbProviderFactory>(dbpf =>\n dbpf.CreateConnection(It.IsAny<string>()) == Mock.Of<IDbConnection>(c =>\n c.CreateCommand() == Mock.Of<IDbCommand>(cmd =>\n cmd.ExecuteReader() == reader.Object\n )\n )\n );\n\n ADOWrapperOptions options = new ADOWrapperOptions() {\n ConnectionString = \"Fake connectino string\"\n };\n\n ADOWrapper SQLDataAdapter = new ADOWrapper(provider, options);\n\n //Act\n var queryResult = SQLDataAdapter.ExecuteQuery(CommandType.Text, \"Select * From TABLE_NAME\").ToArray();\n object[,] twoDArray = new object[queryResult.Length, queryResult.Max(x => x.Length)];\n Get2dArrayFromJagged(queryResult, twoDArray);\n\n //Assert - FluentAssertions\n twoDArray.Should().HaveCount(2); \n }\n\n public static void Get2dArrayFromJagged(object[][] jaggedArray, object[,] returnArray) {\n\n for (int i = 0; i < jaggedArray.Length; i++) {\n for (int j = 0; j < jaggedArray[i].Length; j++) {\n returnArray[i, j] = jaggedArray[i][j];\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:56:31.827",
"Id": "451287",
"Score": "0",
"body": "This is the kind of answer that I was looking for and I really appreciate the time and effort that you put into this. Creating the correct level of abstraction is what I was really struggling with, especially being a newbie to .NET. One final question: Is there any way to materialize the result of a query into a 2-D Object Array that is faster than the current method I am using?? By that I mean, can I skip the conversion of a jagged array to a 2-D array and instead return the 2-D array directly from `Execute Query`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T21:31:28.887",
"Id": "451303",
"Score": "0",
"body": "You used function is efficient enough. You can convert that to an extension method method and use it as a helper"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T23:35:33.493",
"Id": "231358",
"ParentId": "231278",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231358",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T19:32:19.817",
"Id": "231278",
"Score": "2",
"Tags": [
"c#",
"beginner",
"database",
"ado.net"
],
"Title": "DataReader to To IEnumerable<object[]> To 2 Dimensional Array"
}
|
231278
|
<p>I'm learning AJAX JSON. I'm just testing how to pull the data. The idea is, when hovering over the number, it pulls the data and show the content for name and email. Number 1 is to show name and number 2 is to show email.</p>
<p>The api is working, but I'm not quite sure how to refactor or make the code less redundant. Right now I just duplicate the code from one to another. I tried to add callback function, but I feel I'm doing it wrong.</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>const button = document.querySelector(".testName");
const buttonTest = document.querySelector(".testLastName");
const wrapper = document.querySelector(".wrapper");
const randomPerson = document.querySelector("random-person");
button.addEventListener("mouseover", function () {
getData("https://randomuser.me/api/");
console.log("first name");
})
buttonTest.addEventListener("mouseover", function () {
getDataTest("https://randomuser.me/api/");
console.log("last name");
})
function getData(url) {
const request = new XMLHttpRequest();
request.open("GET", url, true);
//console.log(request);
request.onload = function () {
if (this.status === 200) {
const data = JSON.parse(this.responseText);
console.log(data);
let display = "";
data.results.forEach(function (person) {
display += `
<div class="person">
<img class="random-image-js" src=${person.picture.large}></img>
<div class="person-category">
<p>Name: <br> ${person.name.first}</p>
</div>
</div>`
});
//randomPerson.innerHTML = display;
wrapper.innerHTML = display;
}
else {
console.log(this.statusText);
}
}
request.onerror = function () {
console.log("There was a mistake");
}
request.send();
}
function getDataTest(url) {
const request = new XMLHttpRequest();
request.open("GET", url, true);
//console.log(request);
request.onload = function () {
if (this.status === 200) {
const data = JSON.parse(this.responseText);
console.log(data);
let display = "";
data.results.forEach(function (person) {
display += `
<div class="person">
<img class="random-image-js" src=${person.picture.large}></img>
<div class="person-category">
<p>Email: <br> ${person.email}</p>
</div>
</div>`
});
wrapper.innerHTML = display;
}
else {
console.log(this.statusText);
}
}
request.onerror = function () {
console.log("There was a mistake");
}
request.send();
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
padding: 0;
margin: 0;
font-family: sans-serif;
}
.random-wrapper {
border: 1px solid green;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.random-wrapper .random-image-generator {
width: auto;
border-radius: 0;
}
.random-image-js {
width: 150px;
border-radius: 50%;
}
.random-button {
border: 1px solid green;
padding: 10px 30px;
background-color: #7305e4;
color: #ffffff;
cursor: pointer;
}
.random-title-generator {
border: 1px solid green;
width: 100%;
text-align: center;
padding: 10px 0;
margin: 0;
background-color: #839367;
color: #ffffff;
}
.random-button:hover {
background-color: #5d1579;
}
.random-button:focus {
outline: none;
}
.wrapper {
border: 1px solid green;
width: 100%;
margin-top: 50px;
}
.person {
width: 1000px;
border: 1px solid green;
margin: auto;
text-align: center;
}
.person-category {
display: flex;
justify-content: center;
}
.person-category p {
display: flex;
flex-direction: column;
margin: 15px;
}
.test {
display: flex;
}
.test p {
padding: 20px;
border: 1px solid green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="random-wrapper">
<div class="wrapper"></div>
<div class="test">
<p class="testName">1</p>
<p class="testLastName">2</p>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T09:27:44.207",
"Id": "451034",
"Score": "0",
"body": "\"I tried to add callback function, but I feel I'm doing it wrong.\" - anyways it's better than duplicating the code. Go ahead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T13:28:15.493",
"Id": "451060",
"Score": "0",
"body": "@BohdanStupak Yes, I already add callback function, but still not quite sure how to call each of the data. Right now it's just duplicating"
}
] |
[
{
"body": "<ul>\n<li>Find the differences and extract them into separate functions that you can pass as a parameter to the common processing function</li>\n<li>Use modern syntax: async/await, fetch, for-of, destructuring assignment</li>\n</ul>\n\n<pre><code>const wrapper = document.querySelector('.wrapper');\nconst fieldDefinitions = {\n '.test': {\n Name: person => person.name.first,\n },\n '.testLastName': {\n Email: person => person.email,\n }\n};\nfor (const [selector, fields] of Object.entries(fieldDefinitions)) {\n document.querySelector(selector).onmouseover = () => addPerson(fields);\n}\n\nasync function addPerson(fields) {\n try {\n const {results} = await (await fetch('https://randomuser.me/api/')).json();\n const htmlChunks = results.map(person => `\n <div class=\"person\">\n <img class=\"random-image-js\" src=\"${person.picture.large}\">\n <div class=\"person-category\">${\n Object.entries(fields)\n .map(([name, fn]) => `<p>${name}:<br>${fn(person)}</p>`)\n .join('')\n }</div>\n </div>\n `);\n wrapper.insertAdjacentHTML('beforeend', htmlChunks.join(''));\n } catch (e) {\n console.debug(e);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T13:38:02.993",
"Id": "231306",
"ParentId": "231280",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T20:27:02.433",
"Id": "231280",
"Score": "1",
"Tags": [
"javascript",
"json",
"api",
"event-handling",
"ajax"
],
"Title": "Display name and email fetched using JSON API when hovering"
}
|
231280
|
<p>I'm writing a sudoku col/row validator, what is does is:</p>
<ol>
<li>Reads user input on how many Sudoku instances to validate.</li>
<li>Reads the sudoku matrix grid 9x9 (for me, in my specific case 9x9) into a 2d array. Each line read/row should contain something like: <code>8 2 1 3 6 4 9 7 5</code>.</li>
<li>Validates each row and column by flipping a 9 bit bitset to test whether all columns and rows contains nums from 1-9.</li>
</ol>
<p>Please note that the only purpose of this program is to validate sudoku columns/rows as specified and not to completely validate it. i.e also checking each sudoku block.</p>
<p>How can I improve my code? I believe there's lots to it, naming conventions, fundamental approach...etc..etc.</p>
<pre><code>#include <iostream>
#include <sstream>
#include <bitset>
namespace Constants
{
constexpr int ROW_COL_SIZE = 9;
const std::string STR_YES = "YES";
const std::string STR_NO = "NO";
}
template<unsigned int N>
class Sudoku
{
private:
int m_matrix[N][N] {{0}};
public:
void ReadRows();
std::string strIsValid() const;
};
template<unsigned int N>void Sudoku<N>::ReadRows()
{
for(unsigned int row{0}; row<N; row++)
{
static std::string line;
std::getline(std::cin, line);
std::istringstream issline(line);
int readnum {0};
for(unsigned int i{0}; i<N; i++)
{
issline >> readnum;
m_matrix[row][i] = readnum;
}
}
}
template<unsigned int N>std::string Sudoku<N>::strIsValid() const
{
//9bit default ctor all zeroes, 000000000
std::bitset<N> bitRow[N];
std::bitset<N> bitCol[N];
for(int i{0}; i<N; i++)
{
for(int j{0}; j<N; j++)
{
bitRow[i].flip(m_matrix[i][j]-1); //verify nums 1-9 row, bitset index is 0 not 1.
bitCol[i].flip(m_matrix[j][i]-1); //verify nums 1-9 col
}
if(!bitRow[i].all() && !bitCol[i].all())
{
return Constants::STR_NO;
}
}
return Constants::STR_YES;
}
int main(int, char**)
{
int instances {0};
std::cin >> instances;
std::cin.clear();
std::cin.ignore();
for(int i{0}; i<instances; i++)
{
std::cout << "Instance " << i+1 << std::endl;
Sudoku<Constants::ROW_COL_SIZE> sudokuInstance;
sudokuInstance.ReadRows();
std::cout << sudokuInstance.strIsValid() << std::endl << std::endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><sub><em>It is not a complete answer. Just some of my thoughts about this code.</em></sub></p>\n\n<h2>C++</h2>\n\n<ul>\n<li><p><strong>Do not compare integers of different signedness</strong>. Loop counters <code>i</code> and <code>j</code> in function <code>strIsValid</code> are declared as <code>int</code>, but they are compared with <code>N</code> which is <code>unsigned int</code>. It could lead to some problems. Make the counters <code>unsigned</code>.</p></li>\n<li><p><strong>Use strict compilation flags</strong>. The compiler would tell you about your signed/unsigned issue if you pass it <code>-Wall</code> key.</p>\n\n<p>You should always achieve that the compiler will not display any diagnostic messages with the most strict compilation keys (<code>-Wall</code>, <code>-Wextra</code>, <code>-pedantic</code>, etc).</p>\n\n<p><sub>But you probably would <a href=\"https://quuxplusone.github.io/blog/2018/12/06/dont-use-weverything/\" rel=\"nofollow noreferrer\">not want</a> to use Clang's <code>-Weverything</code>.</sub></p></li>\n<li><p><strong>What happened with your <code>main</code>?</strong> Your <code>main</code> function looks very unnatural:</p>\n\n<blockquote>\n<pre><code>int main(int, char**)\n</code></pre>\n</blockquote>\n\n<p>If you do not need <code>argc</code> and <code>argv</code>, write just</p>\n\n<pre><code>int main()\n</code></pre></li>\n<li><p><strong>About <code>std::endl</code></strong>. You should avoid globally using <code>std::endl</code>. It is not the same as just <code>\\n</code>. There is a <a href=\"https://stackoverflow.com/a/14395960/8086115\">good answer</a> on SO about this topic.</p>\n\n<p>And why are you printing <code>std::endl</code> twice?</p>\n\n<blockquote>\n<pre><code>std::cout << sudokuInstance.strIsValid() << std::endl << std::endl;\n</code></pre>\n</blockquote></li>\n<li><p><strong>You do not have to explicitly return from <code>main</code></strong>. You <a href=\"https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c\">don't have</a> to explicitly <code>return 0;</code> at the end of main.</p></li>\n</ul>\n\n<h2>Programming</h2>\n\n<ul>\n<li><p><strong>Minimize the scope of local variables</strong>. You should always minimize the scope of local variables. In your case, for example, scope of the <code>readnum</code> variable can be reduced. Some <a href=\"https://refactoring.com/catalog/reduceScopeOfVariable.html\" rel=\"nofollow noreferrer\">reading</a> about this topic.</p></li>\n<li><p><strong>The predicative function should return boolean</strong>. Your <code>strIsValid</code> is a <em>predicative function</em>. It means that this function checks something and returns either true or false. But you return <em>string</em> <code>\"YES\"</code> (true) or <code>\"NO\"</code> (false). You should return <code>bool</code> instead.</p></li>\n<li><p><strong>What the <code>strIsValid</code> function does?</strong> The name of this function doesn't answer the question.</p></li>\n</ul>\n\n<h2>Architecture</h2>\n\n<ul>\n<li><p><strong>Validate user's input</strong>. At this time you do not validate user's input in <code>ReadRows</code>. What if I'll input a number which is greater than 9? Or less than 0? If I'll input too many numbers?..</p>\n\n<p>In this case, you store invalid data into <code>m_matrix</code>. Then this invalid data will be used as arguments of <code>std::bitset</code>'s <code>flip()</code> which will cause <code>std::out_of_range</code>.</p></li>\n<li><p><strong>Split row and cols validating and reading user's input</strong>. The <code>Sudoku</code> class should know nothing about reading user's input. The only thing that it should do is validate Sudoku columns and rows! This is called the Single Responsibility Principle (<a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T10:09:40.060",
"Id": "451040",
"Score": "2",
"body": "Some of your thoughts about the code makes a valid code review, don't worry about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:08:22.937",
"Id": "451110",
"Score": "1",
"body": "I totally agree regarding \"You should return `bool` instead\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:54:20.583",
"Id": "451114",
"Score": "1",
"body": "tyvm, applied all I've learned,"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T10:00:52.410",
"Id": "231301",
"ParentId": "231286",
"Score": "7"
}
},
{
"body": "<p>First, I just want to remark that this is excellent use of <code>std::bitset<></code>!\nFurther, I'm just adding to eanmos's comments.</p>\n\n<h1>Don't define constants that are named after their value</h1>\n\n<p>Apart from the fact that, as already mentioned, <code>strIsValid()</code> should return a <code>bool</code>, you define the constants <code>Constants::STR_YES</code> and <code>Constants::STR_NO</code>. These constants are longer to type than literal <code>\"YES\"</code> and <code>\"NO\"</code>. Also, consider that you would ever change the value of <code>STR_YES</code>. The code was written with the assumption that the constant would be the literal <code>\"YES\"</code>, as that is what its name clearly says, but now you are breaking that assumption. So in <code>main()</code>, just I would just write:</p>\n\n<pre><code>std::cout << sudokuInstance.strIsValid() ? \"YES\\n\" : \"NO\\n\";\n</code></pre>\n\n<p>If the goal is to make it easy to translate the program, then you should use a so-called internationalization library to do this, such as <a href=\"https://en.wikipedia.org/wiki/Gettext\" rel=\"nofollow noreferrer\">gettext</a>. Writing constants like this doesn't scale for programs with a large amount of text.</p>\n\n<h1>Consider returning a meaningful value from <code>main()</code></h1>\n\n<p>Your program prints whether each Sudoku instance is valid to standard output, but the exit code is always 0. It is custom to have the exit code be non-zero if an error happened. While technically your program still runs perfectly fine if you feed it an invalid Sudoku, you might consider returning 1 if it has encountered any non-valid Sudoku. This is similar to what some command line tools do, like <code>cmp</code> or <code>grep -q</code>.\nThis way, you can call your program from a shell script, and have the shell script react to the result of your program in an easy way, making it easy to integrate it into larger projects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T19:54:36.190",
"Id": "451115",
"Score": "0",
"body": "Makes a lot of sense, tyvm"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T18:53:17.957",
"Id": "231314",
"ParentId": "231286",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231301",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T22:58:42.700",
"Id": "231286",
"Score": "6",
"Tags": [
"c++",
"sudoku"
],
"Title": "Validating sudoku columns and rows"
}
|
231286
|
<p>I am following the Odin Project and building the <a href="https://www.theodinproject.com/courses/javascript/lessons/library" rel="nofollow noreferrer">Library project</a>.</p>
<p>It is very simple, just render a list of Books and we can add and delete books from the list.</p>
<p>However, I feel the code can be improved hugely, as it is getting too messy and I am not sure if I am using the class in the right way.</p>
<p>This is the JavaScript:</p>
<pre><code>const BOOKS_URL = 'https://raw.githubusercontent.com/benoitvallon/100-best-books/master/';
const form = document.querySelector('#library-form');
const newBookBtn = document.querySelector('#new-book');
const library = [];
class Book {
constructor({
author,
title,
pages,
imageLink,
read = false,
}) {
this.readSatusBtn = null;
this.author = author;
this.title = title;
this.pages = pages;
this.imageLink = imageLink;
this.read = !!read;
}
render(index) {
const bookContainer = document.createElement('div');
bookContainer.id = index;
Object.keys(this).forEach((key) => {
const data = document.createElement('div');
data.innerText = this[key];
bookContainer.appendChild(data);
});
const deleteBtn = document.createElement('button');
deleteBtn.innerText = 'Delete';
deleteBtn.class = 'delete-book';
bookContainer.appendChild(deleteBtn);
return bookContainer;
}
}
let deleteBook;
function render() {
const libraryContainer = document.querySelector('#library');
const libContainer = document.createElement('div');
libContainer.id = 'library';
library.forEach((book, index) => {
const bookElement = book.render(index);
libContainer.appendChild(bookElement);
});
document.body.replaceChild(libContainer, libraryContainer);
libContainer.addEventListener('click', deleteBook);
}
deleteBook = (event) => {
if (event.target.class === 'delete-book') {
const index = event.target.parentElement.id;
library.splice(index, 1);
render();
}
};
function addBookToLibrary(book) {
library.push(new Book(book));
render();
}
function cleanFields() {
document.querySelectorAll('input[type=text]').forEach((input) => {
input.value = '';
});
}
function bringUpForm() {
cleanFields();
form.classList.add('active');
}
function processBook(event) {
event.preventDefault();
const book = {};
const fd = new FormData(form);
Array.from(fd).forEach(([key, value]) => {
book[key] = value;
});
addBookToLibrary(book);
form.classList.remove('active');
}
form.addEventListener('submit', processBook);
newBookBtn.addEventListener('click', bringUpForm);
fetch(`${BOOKS_URL}/books.json`)
.then(response => response.json())
.then((data) => {
data.slice(0, 4).forEach((book) => {
book.imageLink = `${BOOKS_URL}/static/${book.imageLink}`;
addBookToLibrary(book);
});
});
</code></pre>
<p>The <code>index.html</code>:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="css/index.css">
<title>Library</title>
</head>
<body>
<h1>Library</h1>
<div id="library"></div>
<button id="new-book">New Book</button>
<form id="library-form">
<div>
<label for="author">Author</label>
<input id="author" name="author" type="text" />
</div>
<div>
<label for="title">Title</label>
<input id="title" name="title" type="text" />
</div>
<div>
<label for="imageLink">Image url</label>
<input id="imageLink" name="imageLink" type="text" />
</div>
<div>
<label for="pages">pages</label>
<input id="pages" name="pages" type="text" />
</div>
<div>
<label for="read">Read</label>
<input id="read" name="read" type="checkbox">
</div>
<input type="submit" value="submit" />
</form>
<script src="js/index.js"></script>
</body>
</html>
</code></pre>
<p>And the <code>css/index.css</code>:</p>
<pre><code>#library-form {
display: none;
}
#library-form.active {
display: block;
}
</code></pre>
<p>Thanks for any suggestions on how to improve this!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T02:21:40.253",
"Id": "231293",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Very simple library system with JavaScript"
}
|
231293
|
<p>I would like some one to review my code and let me know the feedback.<a href="https://i.stack.imgur.com/RRiYU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RRiYU.png" alt="enter image description here"></a></p>
<p>Each Kafka Message is like as follows</p>
<p>[{guid=id.Value1, timestamp=1386394980000, booleanValue=null, longValue=null, floatValue=null, stringValue=value1, source=X, metadata=null}]</p>
<p>This is what I implemented:</p>
<p>ExcelReader</p>
<pre><code>import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelReader{
public static List<KafkaMessage> readExcel(final InputStream inputStream) throws ParseException{
List<KafkaMessage> messages = new ArrayList<>();
XSSFWorkbook workbook;
try{
workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
messages = readRows(sheet, messages);
return messages;
}catch(IOException e){
e.printStackTrace();
}
return messages;
}
private static List<KafkaMessage> readRows(XSSFSheet sheet, List<KafkaMessage> rows) throws ParseException{
for(int i = 3; i <= sheet.getLastRowNum() - 1; i++) {
Row row = sheet.getRow(i);
for(int j = 6; j <= row.getLastCellNum(); j++) {
if(j == 6) {
KafkaMessage kafkaMessage = new KafkaMessage();
String str1 = row.getCell(5).getStringCellValue();
kafkaMessage.setTimestamp(convertToTimeStamp(str1));
String str2 = row.getCell(j).getStringCellValue();
kafkaMessage.setStringValue(str2);
kafkaMessage.setSource(sources().get(j));
kafkaMessage.setGuid(conditionParametersIds().get(j));
rows.add(kafkaMessage);
}
if(j == 7) {
KafkaMessage kafkaMessage = new KafkaMessage();
String str1 = row.getCell(5).getStringCellValue();
kafkaMessage.setTimestamp(convertToTimeStamp(str1));
double str3 = row.getCell(j).getNumericCellValue();
kafkaMessage.setLongValue((long) str3);
kafkaMessage.setSource(sources().get(j));
kafkaMessage.setGuid(conditionParametersIds().get(j));
rows.add(kafkaMessage);
}
if(j == 8) {
KafkaMessage kafkaMessage = new KafkaMessage();
String str1 = row.getCell(5).getStringCellValue();
kafkaMessage.setTimestamp(convertToTimeStamp(str1));
boolean str4 = row.getCell(j).getBooleanCellValue();
kafkaMessage.setBooleanValue(str4);
kafkaMessage.setSource(sources().get(j));
kafkaMessage.setGuid(conditionParametersIds().get(j));
rows.add(kafkaMessage);
}
if(j == 9) {
KafkaMessage kafkaMessage = new KafkaMessage();
String str1 = row.getCell(5).getStringCellValue();
kafkaMessage.setTimestamp(convertToTimeStamp(str1));
double str5 = row.getCell(j).getNumericCellValue();
kafkaMessage.setFloatValue((float) str5);
kafkaMessage.setSource(sources().get(j));
kafkaMessage.setGuid(conditionParametersIds().get(j));
rows.add(kafkaMessage);
}
}
}
return rows;
}
private static Long convertToTimeStamp(String dateTime) throws ParseException{
return DateUtil.provideDateFormat().parse(dateTime).getTime();
}
private static Map<Integer, String> conditionParametersIds(){
Map<Integer, String> map = new HashMap<>();
MapHelper.repeatPut(map, new Integer[]{6, 7, 8, 9}, new String[]{"id.Value1", "id.Value2", "id.Value3", "id.Value4"});
return map;
}
private static Map<Integer, String> sources(){
Map<Integer, String> map = new HashMap<>();
MapHelper.repeatPut(map, new Integer[]{6, 7}, "X");
MapHelper.repeatPut(map, new Integer[]{8, 9}, "Y");
return map;
}
public enum MapHelper{
; // Utility class for working with maps
public static <K, V> void repeatPut(Map<? super K, ? super V> map, K[] keys, V value){
for(K key : keys) {
map.put(key, value);
}
}
public static <K, V> void repeatPut(Map<? super K, ? super V> map, K[] keys, V[] values){
for(int index = 0; index < Math.min(keys.length, values.length); index++) {
map.put(keys[index], values[index]);
}
}
}
}
</code></pre>
<p>SendKafkaMessage</p>
<pre><code>import org.json.JSONArray;
import org.json.JSONObject;
import java.util.List;
public class SendKafkaMessage{
public void sendToProducer(List<KafkaMessage> messages){
Producer producer = new Producer();
messages.forEach(msg -> producer.start(getMessage(msg)));
}
public String getMessage(KafkaMessage message){
JSONObject obj= new JSONObject(message);
JSONArray jsonArray = new JSONArray();
return jsonArray.put(obj).toString();
}
}
</code></pre>
<p>KafkaProducer</p>
<pre><code>import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
public class Producer {
private Properties properties = new Properties();
String topicName = "topicname";
public void start(String value){
String bootstrapServer = "url";
String keySerializer = StringSerializer.class.getName();
String valueSerializer = StringSerializer.class.getName();
String producerId = "simpleProducer";
int retries = 2;
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializer);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer);
properties.put(ProducerConfig.CLIENT_ID_CONFIG, producerId);
properties.put(ProducerConfig.RETRIES_CONFIG, retries);
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topicName, "1",value);
kafkaProducer.send(producerRecord);
kafkaProducer.close();
}
}
</code></pre>
<p>Test Class</p>
<pre><code>import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
public class ExcelToJsonTest {
public static void main(String[] args) throws FileNotFoundException, JsonProcessingException, ParseException{
FileInputStream fis = new FileInputStream("FilePath");
if(fis == null)
System.out.println("fis null");
SendKafkaMessage sendKafkaMessage = new SendKafkaMessage();
sendKafkaMessage.sendToProducer(ExcelReader.readExcel(fis));
}
}
<span class="math-container">````</span>
</code></pre>
|
[] |
[
{
"body": "<p>I noticed in the code of your <code>ExcelReader</code> class the following methods that return two maps:</p>\n\n<blockquote>\n<pre><code>private static Map<Integer, String> conditionParametersIds(){\n Map<Integer, String> map = new HashMap<>();\n MapHelper.repeatPut(map, new Integer[]{6, 7, 8, 9}, new String[]{\"id.Value1\", \"id.Value2\", \"id.Value3\", \"id.Value4\"});\n return map;\n}\nprivate static Map<Integer, String> sources(){\n Map<Integer, String> map = new HashMap<>();\n MapHelper.repeatPut(map, new Integer[]{6, 7}, \"X\");\n MapHelper.repeatPut(map, new Integer[]{8, 9}, \"Y\");\n return map;\n}\n</code></pre>\n</blockquote>\n\n<p>You are repeating calls to these two methods to retrieve values from maps, a possible improvement to avoid this issue is to define two static final maps in your class initialized by the same methods returning <em>unmodifiable</em> maps like the code below:</p>\n\n<pre><code>private static Map<Integer, String> conditionParametersIds(){\n Map<Integer, String> map = new HashMap<>();\n MapHelper.repeatPut(map, new Integer[]{6, 7, 8, 9}, new String[]{\"id.Value1\", \"id.Value2\", \"id.Value3\", \"id.Value4\"});\n return Collections.unmodifiableMap(map);\n}\n\nprivate static Map<Integer, String> sources(){\n Map<Integer, String> map = new HashMap<>();\n MapHelper.repeatPut(map, new Integer[]{6, 7}, \"X\");\n MapHelper.repeatPut(map, new Integer[]{8, 9}, \"Y\");\n return Collections.unmodifiableMap(map);\n}\n\nprivate static final Map<Integer, String> SOURCES = sources();\nprivate static final Map<Integer, String> CONDITION_PARAMETER_IDS = conditionParametersIds();\n</code></pre>\n\n<p>I noticed you have a loop in the method <code>readRows</code> of <code>ExcelReader</code> class performing action on values in the range 6 ...9 and ignoring others out of this range:</p>\n\n<blockquote>\n<pre><code>for(int j = 6; j <= row.getLastCellNum(); j++) {\n if(j == 6) {\n //omitted\n }\n if(j == 7) {\n //omitted\n } //etc..\n}\n</code></pre>\n</blockquote>\n\n<p>You can rewrite the loop calculating the minimal value between 9 and <code>row.getLastCellNum()</code>, using a switch inside the loop for values between 6 and 9 and peculiar actions like my code below:</p>\n\n<pre><code>int min = Math.min(row.getLastCellNum(), 9);\n\nfor(int j = 6; j <= min; j++) {\n KafkaMessage kafkaMessage = new KafkaMessage();\n\n //initialize the common fields to all j values\n String str = row.getCell(5).getStringCellValue();\n kafkaMessage.setTimestamp(convertToTimeStamp(str));\n kafkaMessage.setSource(SOURCES.get(j));\n kafkaMessage.setGuid(CONDITION_PARAMETER_IDS.get(j));\n\n switch(j) {\n case 6:\n str = row.getCell(j).getStringCellValue();\n kafkaMessage.setStringValue(str);\n break;\n case 7:\n double d = row.getCell(j).getNumericCellValue();\n kafkaMessage.setLongValue((long) d);\n break;\n case 8:\n boolean b = row.getCell(j).getBooleanCellValue();\n kafkaMessage.setBooleanValue(b);\n break;\n case 9:\n d = row.getCell(j).getNumericCellValue();\n kafkaMessage.setFloatValue((float) d);\n break;\n }\n\n rows.add(kafkaMessage);\n}\n</code></pre>\n\n<p>I have seen that your <code>readExcel</code> method throws a <code>ParseException</code> but not <code>IOException</code> because you choose to catch the exception, for me the user of this method should be informed about the fact something was wrong with the file and so the exception should be thrown also.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T19:12:29.407",
"Id": "231388",
"ParentId": "231295",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T02:56:23.587",
"Id": "231295",
"Score": "2",
"Tags": [
"java",
"json",
"spring",
"apache-kafka"
],
"Title": "Send excel data to Kafka"
}
|
231295
|
<p>I am trying to solve this question</p>
<blockquote>
<p>Given a non-empty string s and a dictionary wordDict containing a list
of non-empty words, add spaces in s to construct a sentence where each
word is a valid dictionary word. Return all such possible sentences.</p>
<p>Note:</p>
<p>The same word in the dictionary may be reused multiple times in the
segmentation. You may assume the dictionary does not contain duplicate
words.</p>
</blockquote>
<p><a href="https://leetcode.com/problems/word-break-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/word-break-ii/</a></p>
<p>My working code that times out:</p>
<pre><code>class Solution:
def wordBreak(self, s, word_set) :
cache = {}
word_set = set(word_set)
def dfs(i):
if i in cache:
return cache[i]
words = []
res = ""
if s[i:] in word_set:
words.append(s[i:])
for k in range(i, len(s)):
res += s[k]
next_words = dfs(k+1)
if res in word_set:
for w in next_words:
new = res + " "+w
words.append(new)
cache[i] = words
return words
return dfs(0)
</code></pre>
<p>How do I optimize this in terms of time and space complexity?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T09:55:32.223",
"Id": "451037",
"Score": "0",
"body": "How long is the string that times out ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T09:56:56.300",
"Id": "451038",
"Score": "1",
"body": "Also, please note that the leetcode idea of putting every function into a class named \"Solution\" is very bad practice. It really should be a function, not a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T10:01:07.607",
"Id": "451039",
"Score": "0",
"body": "You may consider to *accept* some answers if there helped."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T10:28:03.480",
"Id": "451042",
"Score": "0",
"body": "@MartinR done :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T09:49:42.207",
"Id": "231300",
"Score": "0",
"Tags": [
"python",
"time-limit-exceeded"
],
"Title": "Leetcode Word break 2"
}
|
231300
|
<p>We have a list.
divide the list element into two groups such that when the product of the numbers of two groups is taken and their GCD is calculated, it came out to be 1. Answer the number of ways in which the list element can be divided into two groups following the property.</p>
<p><strong>Note:</strong> The value of a group is the product of the numbers in that group. The output can be very large, so you need to take the modulo 10^9 + 7 of the answer and print it.</p>
<p>sample Input :</p>
<pre>
2
3
2 3 5
4
2 4 6 8
</pre>
<p><strong>Constraints</strong></p>
<p>1<= T <=5</p>
<p>1<= N <=10^5</p>
<p>1<= list_element <=10^6</p>
<p><strong>Input Format</strong></p>
<pre><code>The first line consists of the number of test cases, T.
The first line of each test case consists of the number of element, N.
The second line of each test case consists of the N space-separated integers of the list.
</code></pre>
<p>My code is working fine but it is consuming too much time. Please help.</p>
<p>Below is my code.</p>
<pre><code>public static List<long> GroupList = new List<long>();
static long G_Counter = 0;
static void Main(string[] args)
{
int TestCases = int.Parse(Console.ReadLine());
List<List<long>> groupMember = new List<List<long>>();
for (int i = 0; i < TestCases; i++)
{
string People = Console.ReadLine();
groupMember.Add(Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt64(arrTemp)).ToList());
}
CreateGroup(groupMember);
}
static void CreateGroup(List<List<long>> Group)
{
int count=Group.Count();
List<long> GroupCount = new List<long>();
for (int k = 0; k < count; k++)
{
int lenght = Group[k].Count();
G_Counter = 0;
heapPermutation(Group[k].ToArray(), lenght, lenght);
GroupList.Add(G_Counter);
}
int GC = GroupList.Count();
for (int i = 0; i < GC; i++)
{
Console.WriteLine(GroupList[i]);
}
Console.ReadLine();
}
static bool printArr(long[] a, int n)
{
var k = 2;
bool val = false;
var res = Enumerable.Range(0, (a.ToList().Count - 1) / k + 1)
.Select(i => a.ToList().GetRange(i * k, Math.Min(k, a.ToList().Count - i * k)))
.ToList();
for (int i = 0; i != res.Count(); i++)
{
var result1 = res[i].Aggregate((c, b) => b * c);
for (int j = i + 1; j != res.Count(); j++)
{
var result2 = res[j].Aggregate((c, b) => b * c);
long gcd_val= gcd(result1, result2);
if (gcd_val == 1)
{
val = true;
break;
}
else {
break;
}
}
}
return val;
}
static void heapPermutation(long[] a, int size, int n)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
{
var result= printArr(a, n);
if (result == true)
{
G_Counter++;
}
}
for (int i = 0; i < size; i++)
{
heapPermutation(a, size - 1, n);
// if size is odd, swap first and last
// element
if (size % 2 == 1)
{
long temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}
// If size is even, swap ith and last
// element
else
{
long temp = a[i];
a[i] = a[size - 1];
a[size - 1] = temp;
}
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T11:37:47.550",
"Id": "451047",
"Score": "1",
"body": "Is this from a programming challenge/contest? Can you provide a link to the problem description? That might help to understand the task. – Some *examples* would also be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T11:45:25.563",
"Id": "451049",
"Score": "0",
"body": "Is this understanding correct? Given \\$ N\\$ numbers \\$ a_1, \\ldots, a_N\\$ we have to determine the number of ways to split these numbers into two groups \\$ b_1, \\ldots, b_k\\$ and \\$ c_1, \\ldots, c_l\\$ such that \\$ \\gcd(b_1 \\cdots b_k, c_1 \\cdots c_l) = 1\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T11:53:46.277",
"Id": "451050",
"Score": "0",
"body": "e.g. there are 3 numbers as {2,3,5}\n1. Group 1: {2, 3}; Product = 6\n\nGroup 2: {5}\n\n\n\ngcd(6, 5) = 1\nThe problem is to find the number of ways of dividing the dummies into groups such that the gcd of their product is 1. For the given set of dummies, there are 6 ways of dividing them into two groups following the property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T11:53:54.550",
"Id": "451051",
"Score": "0",
"body": "@DC_Sharp: Please add all relevant information to the question itself, not to the comments. – Known restrictions (how large can \\$N\\$ and the numbers \\$a_i\\$ be) would also be good to know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:01:30.497",
"Id": "451053",
"Score": "0",
"body": "hi @MartinR, I have edited my question. Please have a look on it. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:23:11.420",
"Id": "451055",
"Score": "1",
"body": "Well, this is a task where the “brute force attack” simply does not work. For \\$ N = 10^5 \\$ there are \\$2^N \\approx 10^{30103}\\$ partitions, that is far more than the number of atoms in the universe. – You'll need some math to understand and simplify the problem. [This](https://stackoverflow.com/q/57514180/1187415) might give you some inspiration."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T11:18:48.687",
"Id": "231302",
"Score": "0",
"Tags": [
"c#",
"linq"
],
"Title": "GCD Groups with list"
}
|
231302
|
<p>I looking around and not finding anything, I developed a simple function for estimating the area of a possibly cropped circle inside a frame. It uses a very basic MC implementation.</p>
<p>It is pretty fast but I think it could be made simpler. Any thoughts are appreciated.</p>
<pre><code>import numpy as np
from scipy.spatial import distance
def circFrac(cx, cy, rad, x0, x1, y0, y1, N_tot=100000):
"""
Use Monte Carlo to estimate the fraction of the area of a circle centered
in (cx, cy) with a radius of 'rad', that is located within the frame given
by the limits 'x0, x1, y0, y1'.
"""
# Generate a square containing the circle.
xmin, xmax = cx - rad, cx + rad
ymin, ymax = cy - rad, cy + rad
# Generate 'N_tot' uniform random points inside that square.
xr = np.random.uniform(xmin, xmax, N_tot)
yr = np.random.uniform(ymin, ymax, N_tot)
# Obtain the distances of those points to the center of the circle.
dist = distance.cdist([(cx, cy)], np.array([xr, yr]).T)[0]
# Find the points within the circle.
msk_in_circ = dist < rad
# Find the points that are within the frame, from the points that are
# within the circle.
msk_xy = (xr[msk_in_circ] > x0) & (xr[msk_in_circ] < x1) &\
(yr[msk_in_circ] > y0) & (yr[msk_in_circ] < y1)
# The area is the points within circle and frame over the points within
# circle.
return msk_xy.sum() / msk_in_circ.sum()
# Define the (x, y) limits of the frame
x0, x1 = 0., 1.
y0, y1 = 0., 1.
for _ in range(10):
# Random center coordinates within the frame
cx = np.random.uniform(x0, x1)
cy = np.random.uniform(y0, y1)
# Random radius
rad = np.random.uniform(.05, .5)
print("({:.2f}, {:.2f}), {:.2f}".format(cx, cy, rad))
frac = circFrac(cx, cy, rad, x0, x1, y0, y1)
print("Fraction of circle inside frame: {:.2f}".format(frac))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T13:35:38.730",
"Id": "451061",
"Score": "1",
"body": "Why use a Monty Carlo estimate when you can compute the required area directly using the formula for the area of circular sectors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T13:45:54.040",
"Id": "451063",
"Score": "0",
"body": "Because I found this general approach to be simpler that a geometrical approach. I'm open to it if you think it would be better and/or simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T14:37:55.753",
"Id": "451072",
"Score": "2",
"body": "There's a more efficient way of uniformly sampling over a circle (rather than the sample from a bounding square and discard approach that you describe) described here: https://stackoverflow.com/a/50746409/1845650 ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:09:31.670",
"Id": "451090",
"Score": "4",
"body": "@Gabriel Code Review is not a code writing service. Yes, I can write a direct formula-based calculation, and I believe it would be faster, simpler, and more accurate, but it goes beyond the scope of a simple \"code review\". (If you write one yourself, and post it here, we can review it and perhaps clean it up to make it better.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:45:04.943",
"Id": "451097",
"Score": "0",
"body": "@AJNeufeld yes I know. I don't think you could make it \"faster, simpler, and more accurate\", but if it indeed was simpler then it wouldn't be more than a few lines of code, which is why I suggested you tried. Thanks anyway!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:45:29.820",
"Id": "451098",
"Score": "0",
"body": "@RussHyde that looks like an improvement. I'll give it a try, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:13:48.040",
"Id": "455901",
"Score": "3",
"body": "@CloseVoters, even if OP wrote **in a comment** they'd like to see another implementation of the code, the post itself is 100% in the scope of CodeReview. Please try to get some context before using your VTC..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T12:53:26.733",
"Id": "231304",
"Score": "4",
"Tags": [
"python",
"random",
"statistics",
"numerical-methods"
],
"Title": "Estimate area of cropped circle with Monte Carlo"
}
|
231304
|
<p>Coming from this question <a href="https://stackoverflow.com/questions/58131614/how-to-convert-json-string-into-complex-clos-object-using-cl-json-library">https://stackoverflow.com/questions/58131614/how-to-convert-json-string-into-complex-clos-object-using-cl-json-library</a> I've finally come up with the following solution.</p>
<p>I use cl-json custom handle functionality </p>
<ul>
<li><strong>json::*object-key-handler*</strong> to always know the last key (parent slot name) we run through while parsing JSON. </li>
<li><p><strong>json::*beginning-of-object-handler*</strong> to push on stack a cons with :</p>
<ol>
<li>the last key read (which represent the slot name in the parent object)</li>
<li>the type of the parent object we parse, which is either the type of the root object (for first level referenced object) or which is found on the top of the same stack (general case).
<ul>
<li>special case for the root object where last key read is nil. (we then push nil on the stack).</li>
</ul></li>
</ol></li>
<li><p><strong>json::*end-of-object-handler*</strong> to set the json::*prototype* of the class that should be instantiated. I do this by using the stack.</p>
<ul>
<li>if the stack top is nil we need to instantiate the root object</li>
<li>else we need to instantiate a class from the type of the slot-definition from the 2 data on the stack (the parent slot class having the specific slot definition name).</li>
</ul></li>
</ul>
<p>I then have <strong>defgeneric make-instance-from-json</strong> ,so I can still overload that generic Json2CLOS engine depending on the root object to instantiate, without changing the call syntax.</p>
<p>As I'm just beginning with lisp, what are your thoughts on that code (design/implementation) ?
...and yes, I've just noticed while typing the code here that it's not compatible yet with json arrays [] :-/</p>
<pre class="lang-lisp prettyprint-override"><code>;; dependencies
;;(ql:quickload :cl-change-case)
;;(ql:quickload :closer-mop)
;;(ql:quickload :cl-json)
(require :cl-change-case)
(require :closer-mop)
(require :cl-json)
(defpackage :json2clos
(:use :common-lisp)
(:export #:make-instance-from-json))
(in-package :json2clos)
(defvar *stack-of-object-ref*) ;; holds elements as cons (class-name . slot-symbol)
(defvar *last-json-key-read*)
(defvar *name-of-current-class-being-decoded*)
(defun get-slot-definition (class-symbol json-key)
"returns a slot-definition from the slot of class-symbol which is infered from using json-key / method symbol"
(find
(cl-change-case:param-case json-key)
(closer-mop:class-direct-slots
(find-class class-symbol))
:test (lambda(a b) (string-equal a (symbol-name (closer-mop:slot-definition-name b))))))
(defun start-wrap-for-class (root-class-symbol &optional (fn json::*beginning-of-object-handler*))
(lambda ()
(let ((class-symbol-of-reference-holder nil)
(method-symbol-of-reference-holder *last-json-key-read*)) ;; default case : we are on root object, don't do anything else.
(when method-symbol-of-reference-holder
(let ((previous-class-symbol (caar *stack-of-object-ref*))
(previous-json-key-for-slot (cdar *stack-of-object-ref*)))
(if previous-class-symbol
;; if we are not in first class object : get the current class by using previous class and slot-definition-type.
(setf class-symbol-of-reference-holder
(closer-mop:slot-definition-type
(get-slot-definition previous-class-symbol previous-json-key-for-slot)))
;; else we are a first class object : use class-symbol.
(setf class-symbol-of-reference-holder root-class-symbol))))
;; now that the three cases are resolved let's push the cons on the stack.
(setf *stack-of-object-ref* (cons (cons class-symbol-of-reference-holder method-symbol-of-reference-holder) *stack-of-object-ref*))) ;; stack push
(funcall fn)))
(defun end-wrap-for-class (root-class-symbol &optional (fn json::*end-of-object-handler*))
"Utility code to unwrap JSON using cl-json::prototype and create instances of defined CLOS objects (https://stackoverflow.com/a/55018976/6509567)"
(let ((top-level-prototype (make-instance 'json::prototype :lisp-class root-class-symbol :lisp-package (find-symbol (package-name (symbol-package root-class-symbol))))))
(lambda ()
;; dynamically re-bind *prototype* right around calling fn
(let ((json::*prototype* top-level-prototype) ;;root case
(current-class-symbol (caar *stack-of-object-ref*))
(current-json-key-for-slot (cdar *stack-of-object-ref*))
(json:*json-symbols-package* (symbol-package root-class-symbol)))
(when current-json-key-for-slot
;; regular case
(let ((the-method (get-slot-definition current-class-symbol current-json-key-for-slot)))
(setf json::*prototype* (make-instance 'json::prototype
:lisp-class (closer-mop:slot-definition-type the-method)
:lisp-package (find-symbol (package-name (symbol-package (closer-mop:slot-definition-type the-method))))))
(format t "json::*prototype*= ~a (the-parent-slot-name= ~a) class-name= ~a package-name= ~a~%" json::*prototype* the-method (closer-mop:slot-definition-type the-method) (package-name (symbol-package (closer-mop:slot-definition-type the-method))))
(setf json:*json-symbols-package* (symbol-package (closer-mop:slot-definition-type the-method)))))
;; reset the same *last-json-key-read* as wrap-for-key does, in case we are in an array.
(setf *last-json-key-read* current-json-key-for-slot) ;; redo as if we had read this key again (array scenario)
(setf *stack-of-object-ref* (cdr *stack-of-object-ref*)) ; stack pop
(funcall fn)))))
(defun wrap-for-key (&optional (fn json::*object-key-handler*))
(lambda (the-key)
(setf *last-json-key-read* the-key)
(funcall fn the-key)))
(defun decode-json-to-clos (output-class-symbol json-input-string)
"JSON string to CLOS instance method.
This could be called make-instance-from-json."
(let ((json:*json-symbols-package* (symbol-package output-class-symbol)))
(json:with-decoder-simple-clos-semantics
(let* ((*stack-of-object-ref* (list))
(*last-json-key-read* nil)
(*name-of-current-class-being-decoded* nil)
(json::*beginning-of-object-handler* (start-wrap-for-class output-class-symbol))
(json::*end-of-object-handler* (end-wrap-for-class output-class-symbol))
(json::*object-key-handler* (wrap-for-key )))
(json:decode-json-from-string json-input-string)))))
(defgeneric make-instance-from-json (class-symbol json-input)
(:documentation "make an instance of class-symbol from the json-input data"))
;( the-class json-input)
(defmacro define-method-make-instance-from-json ((target-class-symbol &optional json-input-class-symbol) &key with)
"Used to create methods make-instance-from-json specialized on a type of object.
Structure of WITH must be ((the-class json-input) body)
- where the-class and json-input are designators of the defmethod parameters to refer to in the body context.
- where body is a list of sexp that forms the body of the defmethod."
(let ((the-class (first (first with)))
(json-input (second (first with)))
(body (second with))
(json-type json-input-class-symbol))
(when (null json-type)
(setf json-type 'common-lisp:string))
`(defmethod make-instance-from-json ((,the-class (eql (find-class ',target-class-symbol)))
(,json-input ,json-input-class-symbol))
,@body)))
;; deprecated use make-instance-from-json since it now has a method to handle a symbol as parameter
(defmacro make-instance-from-json* (class-symbol json-input)
"Shortcut macro for usability through code"
(make-instance-from-json (find-class class-symbol) json-input))
(defmethod make-instance-from-json ((the-class common-lisp:standard-class)
(json-input common-lisp:string))
(decode-json-to-clos (class-name the-class) json-input))
(defmethod make-instance-from-json ((the-class-symbol symbol)
(json-input common-lisp:string))
"fallback to use the method with a symbol which is bound to a class"
(make-instance-from-json (find-class the-class-symbol) json-input))
;;;; test tryout of a specifically definned instantiation:
;; (defmethod make-instance-from-json ((the-class (eql (find-class 'common-lisp:real)))
;; (json-input common-lisp:string))
;; (format t "hello test i'm a real~%~a" the-class))
;; (defmethod make-instance-from-json ((the-class (eql (find-class 'common-lisp:rational)))
;; (json-input common-lisp:string))
;; (format t "hello test i'm a RaTioNal~%~a" the-class))
;; (defmethod make-instance-from-json ((the-class (eql (find-class 'common-lisp:number)))
;; (json-input common-lisp:string))
;; (format t " hey number here!! ~%~a" the-class))
;; from here example classes to illustrate json2clos use.
(defpackage :test-company
(:use :common-lisp)
(:export #:company))
(in-package :test-company)
(declaim (optimize (safety 3) (debug 0) (speed 0)))
(defclass company ()
((name
:reader name
:initarg :name)
(address
:reader address
:initarg :address)
(phone-number
:reader phone-number
:initarg :phone)))
(defpackage :test-person
(:use :common-lisp :test-company)
(:export #:person #:alone-person))
(in-package :test-person)
(declaim (optimize (safety 3) (debug 0) (speed 0)))
(defclass person ()
((name
:reader name
:initarg :name)
(address
:reader address
:initarg :address)
(phone-number
:reader phone-number
:initarg :phone)
(favorite-color
:reader favorite-color
:initarg :color)
(partner
:type person
:reader person
:initarg :partner)
(employed-by
:type company
:reader employed-by
:initarg :employed-by)
))
(defclass alone-person ()
((name
:reader name
:initarg :name)
(address
:reader address
:initarg :address)
(phone-number
:reader phone-number
:initarg :phone)
(favorite-color
:reader favorite-color
:initarg :color)))
;;from here test instances to run json2clos code.
(in-package :cl-user)
(declaim (optimize (safety 3) (debug 0) (speed 0)))
(defvar *myperson*)
(defvar *myalone-partner*)
(defvar *mypartner*)
(defvar *mycompany*)
(defvar *mycompany2*)
(setf *mycompany* (make-instance 'test-company:company
:name "World Company"
:address "Wall street, NYC"
:phone "999-999999"))
(setf *mycompany2* (make-instance 'test-company:company
:name "World Company2"
:address "Brexit street, London"
:phone "123-456789"))
(setf *mypartner* (make-instance 'test-person:person
:name "Alice"
:address "Regent Street, London"
:phone "555-99999"
:color "blue"
:employed-by *mycompany*
))
(setf *myperson* (make-instance 'test-person:person
:name "Bob"
:address "Broadway, NYC"
:phone "555-123456"
:color "orange"
:partner *mypartner*
:employed-by *mycompany*
))
;to encode in json
(defvar *myperson-string*)
(setf *myperson-string* (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t))
(with-output-to-string (myperson-stream *myperson-string*)
(cl-json:encode-json *myperson* myperson-stream))
(defvar *my-decoded-person*)
(setf *my-decoded-person* (json2clos:make-instance-from-json 'test-person:person *myperson-string*))
(inspect *my-decoded-person*)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T22:44:33.243",
"Id": "451131",
"Score": "0",
"body": "Can you add an example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T07:30:24.780",
"Id": "451322",
"Score": "0",
"body": "Yes the 7 last lines are the run of the example.\nFirst I encode a PERSON in JSON, the I decode it back to the object PERSON\n`(json2clos:make-instance-from-json 'test-person:person *myperson-string*)`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T13:48:21.863",
"Id": "231309",
"Score": "4",
"Tags": [
"json",
"common-lisp"
],
"Title": "Thoughts about a json2clos decoding using cl-json"
}
|
231309
|
<p>I need to use large strings as a dictionary keys, and I want to optimize the repetitive <code>GetHashCode()</code> and <code>Equals()</code> calls in it.</p>
<p>The number of keys will be quite small (<1000), but each string length will be very big (it's generated SQL queries cache), and I expect a lot of hot lookups.</p>
<p>My idea is to make sure that each wrapped string is interned, so that we can rely on the string references of the same strings to be always the same:</p>
<pre><code>public sealed class InternedString : IEquatable<InternedString>
{
public InternedString(string s) => String = string.Intern(s);
public string String { get; }
public override bool Equals(object obj) => String.Equals(obj);
public bool Equals(InternedString other) => String.Equals(other?.String);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(String);
public static bool operator ==(InternedString l, InternedString r) =>
l?.String == r?.String;
public static bool operator !=(InternedString l, InternedString r) => !(l == r);
}
</code></pre>
<p>Can you review this class, with special attention to safety?</p>
<p><strong>UPDATE</strong></p>
<p>You can check the final code and benchmarks here: <a href="https://github.com/astef/InternedString" rel="nofollow noreferrer">https://github.com/astef/InternedString</a></p>
<p>Usage:</p>
<pre><code>// O(n) operation happens only here, so we want to re-use this object
var iString = new InternedString("typically_a_very_long_string_key");
// now any call to `GetHashCode()` and `Equals(...)` will run in a constant time
mySet.Add(iString);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T17:45:51.303",
"Id": "451102",
"Score": "0",
"body": "It sounded like you were only asking for an opinion, I edited your question so that it fits more our format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T18:51:18.903",
"Id": "451106",
"Score": "0",
"body": "Safety against what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T21:48:44.417",
"Id": "451127",
"Score": "0",
"body": "I mean safety in general. Against bugs, against unexpected behavior. In particular, I was not sure if RuntimeHelper.GetHashCode is doing what I need, and if interning is reliable technique for this purposes, and if I'm not missing any corner-cases. It's just a few lines, but very low-level for me, and very critical for a program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T11:08:28.757",
"Id": "453750",
"Score": "0",
"body": "Could you please show the code using InternedString?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T12:37:59.283",
"Id": "453768",
"Score": "0",
"body": "@KirylZ Check the Usage section here github.com/astef/InternedString. For a more real-world example, imagine a sql insert query which is need to be generated at some point, then executed once with saving results to dictionary, and then the results must be queried by a sql command."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T13:40:53.250",
"Id": "453781",
"Score": "0",
"body": "@astef I think it'd be better if you could add an example to your post."
}
] |
[
{
"body": "<p>Assuming each time you receive a new query you create an instance of InternedString to get/add another item from/into the dictionary, the performance benefit seems questionable:</p>\n\n<ol>\n<li><strong>Impact of string.Intern</strong></li>\n</ol>\n\n<p>a) It needs to calculate a hash of the original string to make a lookup in the pool of strings </p>\n\n<p>b) From <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.intern?view=netframework-4.5.2\" rel=\"nofollow noreferrer\">official documentation</a> - </p>\n\n<blockquote>\n <p>The memory allocated for interned String objects is not likely to be\n released until the common language runtime (CLR) terminates. The\n reason is that the CLR's reference to the interned String object can\n persist after your application, or even your application domain,\n terminates.</p>\n</blockquote>\n\n<ol start=\"2\">\n<li><strong>High rate of collisions seems to be the only beneficial scenario</strong></li>\n</ol>\n\n<p>The equality comparison that Dictionary does for items in the bucket is the case when you implementation might win when the bucket grows huge.</p>\n\n<p>But do you really have that many collisions?</p>\n\n<p><strong>P.S.</strong></p>\n\n<p>Comparing strings you're not using <strong>String.ReferenceEquals</strong> to compare references of the interned strings, but rather == operator which for (sting vs string) leads to values comparison. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T12:06:48.450",
"Id": "453759",
"Score": "0",
"body": "2 - No, Dictionary and other hash-based collections call both `GetHashCode` and `Equals` on each lookup, not only for comparing items in a bucket."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T12:17:07.813",
"Id": "453760",
"Score": "0",
"body": "PS - good point. Even while in a \"true\" comparison case it will lead to a reference comparison, in a \"false\" scenario O(n) comparison will be performed. It can be optimized"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T12:26:20.917",
"Id": "453764",
"Score": "0",
"body": "PS- I think that overloading `==` is a bad idea at all. And `Equals` is definitely need to do a reference comparison"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T13:10:17.717",
"Id": "453774",
"Score": "0",
"body": "Agreed on the second one. Will remove it. Good catch! As for ==, the general recommendation is to avoid using the == and != operators when you test for equality"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T13:30:51.210",
"Id": "453779",
"Score": "0",
"body": "Although given it more thought, the second point is still valid if remove the part \"more than one items\". As the more items it the bucket, the more gain you get comparing by references"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T11:55:18.427",
"Id": "232377",
"ParentId": "231311",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T16:54:01.260",
"Id": "231311",
"Score": "1",
"Tags": [
"c#",
"performance",
"strings",
"hashcode"
],
"Title": "InternedString as alternative to regular String"
}
|
231311
|
<p>I built a container that can hold objects of various types, and look up an object convertible to a given type. I wrote something about my intended use-case here:</p>
<p><a href="https://stackoverflow.com/questions/58562173/typesafe-way-to-provide-enriched-dependencies-to-derived-classes-in-c">https://stackoverflow.com/questions/58562173/typesafe-way-to-provide-enriched-dependencies-to-derived-classes-in-c</a></p>
<p>Basically I want to be able to throw a bunch of dependencies onto a pile and then grab the exact version I want from calling code -- for instance, if I just need an IWidget, I can do</p>
<pre><code>IWidget * widget = dependencies.get<IWidget *>();
</code></pre>
<p>but if the underlying widget is actually a FancyGreenWidget then I can do</p>
<pre><code>FancyGreenWidget * widget = dependencies.get<FancyGreenWidget *>();
</code></pre>
<p>and if it's <em>not</em> fancy and green then I'll get a helpful runtime error during program initialization rather than a surprise segfault sometime while the program is running.</p>
<p>I'm not really familiar with C++17, but it seemed like I needed a bunch of C++17 features to implement my use-case. I feel like someone who writes modern C++ on a daily basis can probably glance at this and tell me several things I'm doing wrong. In particular I suspect there's a much cleaner way to write the visitor in the <code>get<T>()</code> method.</p>
<pre><code>template<class... Types>
class VariantContainer
{
private:
std::vector<std::variant<Types...>> m_values;
public:
template<class T>
void add(const T &t)
{
static_assert(std::disjunction_v<std::is_same<T, Types>...>);
m_values.push_back(t);
}
template<class T>
T get()
{
for(int i = 0; i < m_values.size(); i++)
{
std::optional<T> result = std::visit(
[](auto&& arg) {
using Targ = std::decay_t<decltype(arg)>;
if constexpr(std::is_convertible_v<Targ, T>)
{
return std::optional<T>(static_cast<T>(arg));
}
else
{
return std::optional<T>();
}
},
m_values[i]);
if(result.has_value()) { return result.value(); }
}
std::string message = "Could not find member of type ";
message += abi::__cxa_demangle(typeid(T).name(), 0, 0, nullptr);
throw std::runtime_error(message);
}
};
</code></pre>
<p>Sample usage:</p>
<pre><code> VariantContainer<Base *, Derived1 *, Derived2 *> v;
Derived2 d;
v.add(&d);
Base * b = v.get<Base *>(); // returns a pointer to d
Derived1 * d1 = v.get<Derived1 *>(); // ERROR
Derived2 * d2 = v.get<Derived2 *>(); // returns a pointer to d
</code></pre>
<p>I'm also in the market for a more descriptive name for this class if anyone has any ideas.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T12:23:48.770",
"Id": "451161",
"Score": "0",
"body": "Do you only want this solution to work only on inheritance hierarchies (as your examples suggest), or also other types of conversion (e.g. `float` to `double`, `double` to `int`, or more nefarious ones like [this example](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#example-137) )?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:45:55.193",
"Id": "451186",
"Score": "0",
"body": "@hoffmale I guess in my use case it's always going to be pointers getting cast to base types. As for how it might be good to behave when other stuff is put it in, I haven't given it much thought."
}
] |
[
{
"body": "<p>You said you implemented</p>\n\n<blockquote>\n <p>a container that can hold objects of various types, and look\n up an object convertible to a given type</p>\n</blockquote>\n\n<p>This idea can be simplified and generalized: we want to</p>\n\n<blockquote>\n <p>look up an object convertible to a given a type in a sequence of variants</p>\n</blockquote>\n\n<p>We can focus on the <code>get</code> function and strip everything else. The container does not have to be a <code>std::vector<std::variant></code> — we can use iterators:</p>\n\n<pre><code>template <typename T, typename ForIt>\nT get_convertible(ForIt first, ForIt last);\n</code></pre>\n\n<p>In the code, you want to find an element that is convertible to <code>T</code>, and throw an exception if such an element is not found. You used <code>std::optional</code> to conditionally return the visited element. This overhead can be eliminated:</p>\n\n<pre><code>template <typename T, typename ForIt>\nT get_convertible(ForIt first, ForIt last)\n{\n auto it = std::find_if(first, last, [](const auto& variant) {\n return std::visit([](const auto& value) {\n using U = std::decay_t<decltype(value)>;\n return std::is_convertible_v<U, T>;\n }, variant);\n });\n\n if (it == last) {\n throw std::runtime_error{\"...\"};\n } else {\n return std::visit([](const auto& value) -> T {\n using U = std::decay_t<decltype(value)>;\n if constexpr (std::is_convertible_v<U, T>)\n return value;\n }, *it);\n }\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/4PiLaEmOfB6BdqlG\" rel=\"nofollow noreferrer\">live demo</a>, includes code to disable return warning)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T09:04:36.900",
"Id": "451151",
"Score": "0",
"body": "Just add `assert(0); throw something;` and you have the warning suppressed *portably*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T09:22:52.507",
"Id": "451152",
"Score": "1",
"body": "@Deduplicator It is not technically possible to suppress a warning \"portably\" - the standard allows a compiler to issue any number of diagnostics for a well-formed program ;-) Anyway, what's that `assert(0);` for? A simple `throw 0;` seems to suffice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T11:45:32.207",
"Id": "451158",
"Score": "1",
"body": "I'm not a C++ programmer, but the two very similar blocks of std::visit in the same method kind of sticks out. Is it possible to work around that? And how big is the overhead with std::optional you mentioned?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T13:27:00.877",
"Id": "451169",
"Score": "1",
"body": "@TomG Maybe not. `std::visit` is pretty much the standard way to access a variant in a type-dependent way. As for the overhead of `std::optional` ... Well, I don't really know, but probably not negligible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:49:46.363",
"Id": "451188",
"Score": "0",
"body": "@TomG indeed, I initially added the `std::optional` specifically because I couldn't see a cleaner way to avoid two very similar calls to `std::visit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T04:31:19.850",
"Id": "451227",
"Score": "0",
"body": "@L.F. I actually don't care about performance for my use case, but does it actually reduce overhead any to get rid of the `std::optional` and replace it with a nested lambda followed by a second call to `std::visit`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T05:01:17.430",
"Id": "451228",
"Score": "0",
"body": "@DanielMcLaury Nested lambda shouldn't be a problem. I'm not sure about the two `visit`s ..."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T07:54:01.777",
"Id": "231333",
"ParentId": "231316",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:14:25.743",
"Id": "231316",
"Score": "3",
"Tags": [
"c++",
"collections",
"c++17"
],
"Title": "Container that holds objects of various types, and can be searched for an object convertible to a given type"
}
|
231316
|
<p>Whenever I find myself <strong>repeating</strong> the same actions across different components in my projects, I immediately feel that I should <strong>extract the code to a function</strong>.</p>
<p>The problem this time is that I can't imagine a clean solution to this problem:</p>
<p>I have a angular service (<code>UIService</code>) that I inject in all my components. This service has a member <code>state$</code> which is a BehaviorSubject. This BehaviorSubject holds the state of the UI including the state of the <code>forms</code> inside my components.</p>
<pre><code>// abstration of my service because I like everything reusable
import { BehaviorSubject } from 'rxjs';
import { first, map, tap, concatMap } from 'rxjs/operators';
export abstract class UIStateAbstraction {
public state$ = new BehaviorSubject<any>(this.defaults);
public patchState = (patch) => this.state$.pipe(
first(),
map(state => {
console.log('UI state - old:', state);
console.log('UI state - mutation:', patch);
this.state$.next({ ...state, ...patch });
}),
concatMap(() =>
this.state$
.pipe(
first(),
tap(newState => console.log('UI state - new:', newState))
)
)
)
constructor(private defaults) { }
}
////////////
// UIService
////////////
import { Injectable } from '@angular/core';
import { UIStateAbstraction } from 'src/app/shared/abstraction-classes';
import { Artigo } from '../models';
export interface UI {
// modals
assistenciaModalVisible: boolean;
assistenciaModalID: number;
artigoModalVisible: boolean;
artigoModalID: number;
encomendaPromptModalVisible: boolean;
encomendaPromptModalArtigo: Artigo | {};
// pages
assistenciasCriarNovaPageContactoClienteForm: {};
assistenciasCriarNovaPageClienteForm: {};
assistenciasCriarNovaPageCriarNovaForm: {};
encomendaPageContactoClienteForm: {};
encomendaPageClienteForm: {};
encomendaPageArtigoForm: {};
encomendaPageEncomendaForm: {};
// prints
}
const defaults: UI = {
// modals
assistenciaModalVisible: false,
assistenciaModalID: null,
artigoModalVisible: false,
artigoModalID: null,
encomendaPromptModalVisible: false,
encomendaPromptModalArtigo: {},
// pages
assistenciasCriarNovaPageContactoClienteForm: {},
assistenciasCriarNovaPageClienteForm: {},
assistenciasCriarNovaPageCriarNovaForm: {},
encomendaPageContactoClienteForm: {},
encomendaPageClienteForm: {},
encomendaPageArtigoForm: {},
encomendaPageEncomendaForm: {},
// prints
};
@Injectable({ providedIn: 'root' })
export class UIService extends UIStateAbstraction {
constructor() {
super(defaults);
}
}
//////////////////////////////////////
// part of one of the many components
//////////////////////////////////////
import {
Component, OnInit, ChangeDetectionStrategy, OnDestroy,
ViewChild, ElementRef, AfterViewInit, ChangeDetectorRef
} from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Observable, merge, of } from 'rxjs';
import { tap, concatMap, map, first, mergeMap } from 'rxjs/operators';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe';
import { AssistenciasService, UsersService, UIService, UI } from 'src/app/shared/state';
import { PrintService } from 'src/app/pages/dashboard-page/prints';
import { User, Assistencia } from 'src/app/shared/models';
import { capitalize } from 'src/app/shared/utilities';
import { clone } from 'ramda';
import { ClientesPesquisarModalComponent } from 'src/app/pages/dashboard-page/modals';
@AutoUnsubscribe()
@Component({
selector: 'app-assistencias-criar-nova-page',
templateUrl: './assistencias-criar-nova-page.component.html',
styleUrls: ['./assistencias-criar-nova-page.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AssistenciasCriarNovaPageComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild('userSearchModalInput', { static: false }) userSearchModalInputEl: ElementRef<HTMLElement>;
@ViewChild(ClientesPesquisarModalComponent, { static: false }) clientesSearchModal: ClientesPesquisarModalComponent;
public oldAssists$: Observable<Assistencia[]>;
/* Declaration of the 3 Forms on the UI */
public contactoClienteForm = this.fb.group({
contacto: [null, Validators.min(200000000)] // por exemplo, contacto: 255486001
});
public clienteForm = this.fb.group({
nome: [null, [Validators.required, Validators.minLength(3)]],
email: [''],
endereço: [''],
nif: [''],
id: [null]
});
public criarNovaForm = this.fb.group({
categoria: ['', Validators.required],
marca: [''],
modelo: [''],
cor: ['', Validators.required],
serial: [''],
codigo: [''],
acessorios: [''],
problema: ['', Validators.required],
orcamento: [null]
});
/*########################################### */
private clienteChange$ = this.contactoClienteForm.valueChanges
.pipe(
tap(() => {
this.clienteForm.reset();
this.oldAssists$ = of();
}),
concatMap(({ contacto }) => this.user$(contacto).pipe(
map((users: User[]) => users.filter((user: User) => user.contacto === +contacto)),
map((users: User[]) => users[0]),
tap((cliente: User) => {
if (cliente) {
this.clienteForm.patchValue(cliente);
this.oldAssists$ = this.assistenciasService.find({ query: { cliente_user_id: cliente.id, estado: 'entregue' } });
setTimeout(() => {
this.cdr.detectChanges();
}, 200);
}
})
))
);
private user$ = (contacto: number) => this.usersService.find({ query: { contacto } }) as Observable<User[]>;
constructor(
private fb: FormBuilder,
private uiService: UIService,
private usersService: UsersService,
private assistenciasService: AssistenciasService,
private printService: PrintService,
private cdr: ChangeDetectorRef) { }
ngOnInit() {
merge(
this.clienteChange$,
this.uiService.state$
.pipe(
first(),
tap((state: UI) => {
this.contactoClienteForm.patchValue(state.assistenciasCriarNovaPageContactoClienteForm);
this.clienteForm.patchValue(state.assistenciasCriarNovaPageClienteForm);
this.criarNovaForm.patchValue(state.assistenciasCriarNovaPageCriarNovaForm);
})
),
this.contactoClienteForm.valueChanges
.pipe(
concatMap(value => this.uiService.patchState({ assistenciasCriarNovaPageContactoClienteForm: value }))
),
this.clienteForm.valueChanges
.pipe(
concatMap(value => this.uiService.patchState({ assistenciasCriarNovaPageClienteForm: value }))
),
this.criarNovaForm.valueChanges
.pipe(
concatMap(value => this.uiService.patchState({ assistenciasCriarNovaPageCriarNovaForm: value }))
),
)
.subscribe();
}
// more code ....
}
</code></pre>
<p>Take attention to the <code>ngOnInit()</code> member of the component. This member is similar in every other components so that I can sync every changes in the <code>forms</code> with the <code>UIService</code> and back.</p>
<p>How do you suggest that I extract this code to something more reusable?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T20:14:40.513",
"Id": "231317",
"Score": "1",
"Tags": [
"javascript",
"angular-2+",
"rxjs"
],
"Title": "Making code with interdependant observables reusable"
}
|
231317
|
<p>I wrote a small snippet to implement asyncio <code>Pipeline</code> - object that connects together <code>Layers</code>, and lets them create and pass through objects. Each <code>Layer</code> could perform some IO to create/store an object or calculate something to create on object on the go or remove an object. <code>Layers</code> are connected with Queues, and they have states with Events triggered when that state changes.</p>
<p>The most questionable part was about how to let the entire process (I mean running the pipeline, not the system process) from any point in <code>Layer</code> or outside of Pipeline. That's what I want to get help (or recommendation) with.</p>
<p><a href="https://gist.github.com/iAnanich/f3cae79eaa4b913d0f4d38f95620365b" rel="nofollow noreferrer">Original code snippet on GitHub Gist</a></p>
<p>P.S.: have plans of extending Pipeline so it will run multiple instances of exact layer concurrently. So it could have, let's say, 4 concurrent first layers and 16 concurrent second layers with a shared queue. But don't really know if I should create another question</p>
<p><strong>UPDATE</strong></p>
<ul>
<li>removed code from question</li>
</ul>
<p>I implement concurrency inside layers by adding a new entity - Node. The project became too big even for a snippet, so I moved code into GitHub repository - <a href="https://github.com/iAnanich/aio_pipelines" rel="nofollow noreferrer">https://github.com/iAnanich/aio_pipelines</a> </p>
<p>Here I will post a bit modified code containing key components that could be improved, but an example of usage (currently there are 3 of them) can be found inside the <code>examples</code> folder of GitHub repository.</p>
<p><em>1 - Pipeline</em></p>
<pre><code>class Pipeline(AbstractPipeline):
async def start(self) -> None:
self.state = STATES.RUNNING
self.started_event.set()
await self._run_layers()
await self.stop()
async def stop(self) -> None:
async with self._finalizer_lock:
if self.state == STATES.STOPPED:
return
self.state = STATES.GOING_TO_STOP
self.going_to_stop_event.set()
self._finalizer_task = asyncio.create_task(self._stop_layers())
await self._finalizer_task
self.state = STATES.STOPPED
self.stopped_event.set()
async def stop_at_event(self, event: asyncio.Event) -> None:
await event.wait()
await self.stop()
async def _run_layers(self):
async def gather_layers():
await asyncio.gather(
*[
layer.start() for layer in self.layers
],
return_exceptions=True,
)
# schedule tasks for chain-like stop of the layers
for idx in range(1, len(self.layers)):
layer = self.layers[idx - 1]
layer_to_stop = self.layers[idx]
coro = layer_to_stop.stop_at_event(event=layer.stopped_event)
asyncio.create_task(coro)
# schedule task for stopping Pipeline after last Layer stopped
asyncio.create_task(
self.stop_at_event(self.layers[-1].stopped_event)
)
self._running_layers_task = asyncio.create_task(gather_layers())
await self._running_layers_task
async def _stop_layers(self):
for layer in self.layers:
await layer.stop()
await self._running_layers_task
</code></pre>
<p><em>2 - Layer</em></p>
<pre><code>class BaseLayer(AbstractLayer, metaclass=abc.ABCMeta):
class DEFAULT:
QUEUE = asyncio.Queue(maxsize=0)
def connect_next_layer(self, next_layer: 'Layer') -> None:
self.next_layer = next_layer
async def start(self) -> None:
self.state = STATES.RUNNING
self.started_event.set()
await self.before_start()
await self._start_runner_task()
await self.stop(join_queue=False)
async def stop(self, join_queue: bool = True) -> None:
async with self._finalizer_lock:
if self.state == STATES.STOPPED:
return
self.state = STATES.GOING_TO_STOP
self.going_to_stop_event.set()
if join_queue:
await self.queue.join()
await self.before_stop()
self._finalizer_task = asyncio.create_task(self._finish_runner_task())
await self._finalizer_task
self.state = STATES.STOPPED
self.stopped_event.set()
async def _start_runner_task(self) -> None:
async def gather_nodes():
await asyncio.gather(
*(
node.start(layer=self)
for node in self.nodes
),
return_exceptions=True,
)
asyncio.create_task(self.stop_at_event(
event=self.aborting_event,
join_queue=False,
))
self._running_task = asyncio.create_task(gather_nodes())
await self._running_task
async def _finish_runner_task(self) -> None:
for node in self.nodes:
await node.stop()
await self._running_task
async def stop_at_event(self, event: asyncio.Event,
join_queue: bool = True) -> None:
await event.wait()
await self.stop(join_queue=join_queue)
def abort(self) -> None:
self.aborting_event.set()
</code></pre>
<p><em>3 - Node</em></p>
<pre><code>class Node(metaclass=abc.ABCMeta):
def __init__(self, name: str):
self.name = name
self.event = OwnedEvent(owner=self, name='node task completed')
self.task: asyncio.Task = None
self.layer = None
async def start(self, layer) -> None:
self.layer = layer
self.task = asyncio.create_task(
coro=self.run(layer=layer),
)
await self.task
self.event.set()
async def stop(self) -> None:
self.task.cancel()
@abc.abstractmethod
async def run(self, layer) -> None:
pass
</code></pre>
<p>And again, my main question is about proper shut down of the pipeline from any point - so any Node might want to safely stop the pipeline, and pipeline could be stopped by something outside of it.</p>
<p>Although, any recommendation on how to make this implementation of pipeline more stable (it is stable, yet), clear and simple are very appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T10:59:58.223",
"Id": "451157",
"Score": "0",
"body": "Can you clarity your phrase \"4 concurrent first layers and 16 concurrent second layers\"? Currently, the Pipeline connects layers in pairwise manner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T14:51:38.260",
"Id": "451180",
"Score": "0",
"body": "@RomanPerekhrest yes, you are right. Pipeline can't parallelize layers, yet. I meant that I plan to add such functionality soon. maybe that note was unrelated to main topic of the question, but I think that the mechanism of stopping the `Pipeline` with concurrent layers will be more complex than it is now and will need a review too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:42:38.620",
"Id": "451185",
"Score": "0",
"body": "Can you clarify the statement \"*how to let the entire process (I mean running the pipeline, not the system process) from any point in Layer or outside of Pipeline.*\"? It's not quite clear, as a Layer is inside a Pipeline and managed by that pipeline"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:54:26.377",
"Id": "451189",
"Score": "0",
"body": "@RomanPerekhrest for example, pipeline could be controlled by some message bus, which isn't represented by layer, but instead as a concurrent Task. Or any layer could stop the pipeline after retrieving some specific item from previous layer. `GOING_TO_STOP` state allows `Layer` to immediately stop item processing if needed, but it will continue working untill queue is processed by default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T01:47:07.080",
"Id": "451220",
"Score": "0",
"body": "@RomanPerekhrest I published an enhanced version on GitHub as [repository](https://github.com/iAnanich/aio_pipelines) - with concurrency implemented. Going to refactor a bit and edit original question here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T05:12:49.797",
"Id": "451229",
"Score": "0",
"body": "Ok, let me know after the question is edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T08:12:46.857",
"Id": "451234",
"Score": "0",
"body": "@RomanPerekhrest edited the question - removed old code, added the latest version with some additions, left the link to GitHub repo"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T00:24:45.607",
"Id": "231323",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"asynchronous",
"io",
"async-await"
],
"Title": "Python AsyncIO pipeline"
}
|
231323
|
<p>As the title says, this is my first Dockerfile. It won't be published on any registry, just for my internal use at home. I'd appreciate any critique of what I could do better. I'm currently working on a way to not hard-code the password into the docker-compose file...</p>
<p>This image is to run Postfix on Alpine as a SMTP relay for my devices to alert me (e.g., NAS, security cameras, etc...).</p>
<p><strong>Dockerfile</strong></p>
<pre><code>FROM alpine:3.10
ARG BUILD_DATE
LABEL maintainer="MyNameGoesHere" \
org.label-schema.schema-version="1.0" \
org.label-schema.name="postfixrelay" \
org.label-schema.build-date=$BUILD_DATE
RUN apk add --no-cache --update \
bash ca-certificates cyrus-sasl-login postfix rsyslog tzdata && \
rm -rf /var/cache/apk/*
EXPOSE 25
VOLUME [ "/var/spool/postfix" ]
COPY ./entrypoint.sh /
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
</code></pre>
<p><strong>entrypoint.sh</strong></p>
<pre><code>#!/bin/sh -e
#Set timezone
if [ ! -f /etc/timezone ] && [ ! -z "$TZ" ]; then
cp /usr/share/zoneinfo/$TZ /etc/localtime
echo $TZ >/etc/timezone
fi
# Set Postfix options
postconf -e "inet_interfaces = all" && \
postconf -e "mynetworks = 0.0.0.0/0" && \
postconf -e "relayhost = [$RELAY_IP]:$RELAY_PORT" && \
postconf -e "smtp_use_tls = yes" && \
postconf -e "smtp_sasl_auth_enable = yes" && \
postconf -e "smtp_sasl_security_options = noanonymous" && \
postconf -e "smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd"&& \
postconf -e "smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt" && \
# Create password file
echo "[$RELAY_IP]:$RELAY_PORT $EMAIL:$PASS" > /etc/postfix/sasl_passwd && \
chown root:root /etc/postfix/sasl_passwd && \
chmod 600 /etc/postfix/sasl_passwd && \
postmap /etc/postfix/sasl_passwd
# Start postfix
postfix start-fg
</code></pre>
<p><strong>docker-compose.yml</strong></p>
<pre><code>version: '3'
services:
postfixrelay:
container_name: postfixrelay
restart: unless-stopped
environment:
- TZ=America/New_York
- RELAY_IP=smtp.gmail.com
- RELAY_PORT=587
- EMAIL=my_email_address@gmail.com
- PASS=password
networks:
- postfixrelay
ports:
- '25:25'
volumes:
- 'postfixrelay_data:/var/spool/postfix'
image: postfixrelay
networks:
postfixrelay:
volumes:
postfixrelay_data:
driver: local
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:04:37.240",
"Id": "451143",
"Score": "2",
"body": "shameless self-promotion refer to https://stackoverflow.com/questions/58393555/how-to-check-if-i-am-writing-the-right-dockerfile/58394030#58394030"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:12:47.510",
"Id": "451144",
"Score": "0",
"body": "You can split the `apk add ...` packages on multiple lines in your `Dockerfile`, makes it easier to see what's changed in i.e. a `git diff` like [this](https://stackoverflow.com/a/57747991/1423507). I'd move the `VOLUME` and `EXPOSE` to before the `RUN` as they'll probably never change. For the `networks` you can use the `default` setting the `name: postfixrelay` in your `docker-compose.yml`."
}
] |
[
{
"body": "<p>I would set the execute permissions on the <code>entrypoint.sh</code> before building the <code>docker</code> image - <a href=\"https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#minimize-the-number-of-layers\" rel=\"nofollow noreferrer\">RUN, COPY and ADD create layers</a> - <code>COPY</code> preserves the file permissions so you can remove the <code>RUN chmod +x /entrypoint.sh</code> (a layer from your final image).</p>\n\n<pre><code>FROM alpine:3.10\n\nARG BUILD_DATE\n\nLABEL maintainer=\"MyNameGoesHere\" \\\n org.label-schema.schema-version=\"1.0\" \\\n org.label-schema.name=\"postfixrelay\" \\\n org.label-schema.build-date=$BUILD_DATE\n\nEXPOSE 25\n\nVOLUME [ \"/var/spool/postfix\" ]\n\nCOPY ./entrypoint.sh /\n\nRUN apk add --no-cache --update \\\n bash \\\n ca-certificates \\\n cyrus-sasl-login \\\n postfix \\\n rsyslog \\\n tzdata && \\\n rm -rf /var/cache/apk/*\n\nENTRYPOINT [\"/entrypoint.sh\"]\n</code></pre>\n\n<p>... moved the <code>EXPOSE</code>, <code>VOLUME</code> and <code>COPY</code> instructions above the <code>RUN</code> - the <code>VOLUME</code> and <code>EXPOSE</code> are not likely to change and the build cache for the <code>COPY</code> will only be invalidated if the contents of the file changes as explained in the <a href=\"https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy\" rel=\"nofollow noreferrer\"><code>ADD</code> or <code>COPY</code></a> best practices. Finally, split the packages being added on multiple lines to make it clearer at a glance in i.e. a <code>git diff</code> when something changes.</p>\n\n<p>Concerning the <code>entrypoint.sh</code> I'd suggest taking a look at the <a href=\"https://docs.docker.com/engine/reference/builder/#exec-form-entrypoint-example\" rel=\"nofollow noreferrer\">Exec form <code>ENTRYPOINT</code> example</a> to ensure that your process is receiving the Unix signals.</p>\n\n<p>For the <code>docker-compose</code> I'd pass the <code>PASS</code> environment variable from the hosts environment and name the <code>default</code> network explicitly:</p>\n\n<pre><code>version: '3'\nservices:\n postfixrelay:\n container_name: postfixrelay\n restart: unless-stopped\n environment:\n ...\n - PASS=${PASS}\n...\nnetworks:\n default:\n name: postfixrelay\n...\n</code></pre>\n\n<p>If you want to <code>docker-compose up --scale postfixrelay=3</code> you'd need to stop using <code>container_name</code>, trying to start multiple containers with the same name will conflict. You'd also need to stop publishing the ports to the host, will have port conflicts - would need to set up a <code>tcp</code> load balancer (i.e. <code>nginx</code>, <code>traefik</code>, ...) and proxy the connections to your upstream services.</p>\n\n<p>Then there is <code>docker swarm</code> and <code>kubernetes</code> (or other) as proper orchestration managers for your service(s).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T18:51:07.543",
"Id": "231325",
"ParentId": "231324",
"Score": "1"
}
},
{
"body": "<p>In <code>entrypoint.sh</code>, I prefer to have <code>set -eu</code> in line 2 instead of passing it in line 1. That way it is guaranteed to be set no matter how the program is run.</p>\n\n<p>Because of this <code>set -e</code>, you can omit the <code>&& \\</code>, since that code is neither in a subshell nor in a function. (The <code>set -e</code> mode is unreliable in either of them, I don't remember the exact rules though.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T06:54:51.603",
"Id": "231332",
"ParentId": "231324",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231325",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T16:23:13.800",
"Id": "231324",
"Score": "2",
"Tags": [
"docker",
"dockerfile"
],
"Title": "First Dockerfile, I would appreciate critique"
}
|
231324
|
<p>I have picture in certain cells. When I run following code (With Intersect Method) in smaller number of selected cells, it runs correctly but when the number of selected cells increase - say above 1000, then code slows down a bit (Intersect Method). Can it be optimized? Code without intersect method runs Ok.Can intersect method further optimize the code?</p>
<p><strong>Code Without Intersect Method:</strong></p>
<pre><code>Sub tagging3()
Dim rng As Range
Dim shp As Shape
Dim m As Long
Dim arr() As String
Dim sample As String
m = 1
ReDim arr(ActiveSheet.Shapes.Count)
For Each shp In ActiveSheet.Shapes
arr(m) = shp.TopLeftCell.Address
m = m + 1
Next
For Each rng In Selection
sample = rng.Address
rng.Offset(0, 30).Value = "No"
For m = 1 To ActiveSheet.Shapes.Count
If sample = arr(m) Then
rng.Offset(0, 30).Value = "Yes"
Exit For
End If
Next m
Next
End Sub
</code></pre>
<p><strong>Code With Intersect Method - Quite Slow</strong></p>
<pre><code>Sub shapesincells()
Dim sh As Shape, isect, rng As Range, n As Integer, arr() As Variant, sample As String
ReDim arr(ActiveSheet.Shapes.Count)
n = 1
For Each sh In ActiveSheet.Shapes
Set arr(n) = sh.TopLeftCell
n = n + 1
Next
For Each rng In Selection
sample = rng.Offset(0, 30).Address
For n = 1 To ActiveSheet.Shapes.Count
Set isect = Application.Intersect(arr(n), rng)
If Not isect Is Nothing Then
sample = "Yes"
End If
Next
If IsEmpty(sample) Then sample = "No"
Next
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T11:05:36.500",
"Id": "452472",
"Score": "0",
"body": "I wouldn't check for an Intersect. I would check/compare if column and row is the same, since you are comparing cell vs cell. Or i would check/compare the address field."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T05:47:45.537",
"Id": "454301",
"Score": "0",
"body": "Intersect method quite slow in such scenarios (large number of cells in selection) It compares objects directly (e.g. range object) rather than references to an objects (e.g. range addresses). Here we are simply interested in whether cell has object over it. So instead of using intersect to check cells themselves first, all cell addresses where object exist are stored in an array (first method above - code without intersect) and then each cell address in selected range is compared against each element of array and next steps of the code (flagging \"Yes\" or \"No\") in offset cell are carried out."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T05:08:52.513",
"Id": "231330",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Intersect Method Slows Down Code In Large Selection Of Cells"
}
|
231330
|
<p>This is my first TUI program implemented via the curses module for Python.</p>
<p>I use the program to input some data (numbers only) via the terminal, which are then saved to a .txt file.</p>
<p>Any kind of feedback is highly appreciated, especially regarding the way I input data (I basically catch every character that the user inputs, if it's a number it is saved to a list and printed on screen, if it's an arrow key I move between the cells) and the way I handle terminal resizing (I delete everything and print it again).</p>
<pre><code>#!/usr/bin/env python3
# last updated on 2019/10/26
import curses
class Twod2small(object):
def __init__(self, stdwin):
curses.init_pair(1, 40, 0) # save green
curses.init_pair(2, 9, 0) # red
curses.init_pair(3, 255, 0) # white
self.green = curses.color_pair(1)
self.red = curses.color_pair(2)
self.white = curses.color_pair(3)
self.stdwin = stdwin
# set the main window's rows and columns
self.winheight = 29
self.winwidth = 120
# two 2d lists containing the input rows and cols for each part of the main window
self.inputrow = [[5, 9, 13, 16, 18, 21, 23], [5, 9, 12, 14, 17, 19]]
self.inputcol = [[36, 50], [int(self.winwidth/2) + 36, int(self.winwidth/2) + 50]]
# measures is the list in which I store all the data inputed
self.measures = [[["----", "----"] for i in range(7)], [["----", "----"] for i in range(6)]]
self.kcell = "----"
# current input side (ciside) is either 0 or 1, respectively for the left and right
# part of the screen
self.ciside = 0
self.cirow = 0
self.cicol = 0
self.initScreen()
self.inputMeasures()
def initScreen(self):
# don't show the screen until the terminal has the minimal dimensions
while True:
self.stdwin.erase()
rows, cols = self.stdwin.getmaxyx()
if rows < 35 or cols < 134:
msg = "Make terminal at least 134x35"
if rows > 3 and cols > len(msg):
self.stdwin.addstr(int(rows/2) - 1 + rows%2, int((cols - len(msg))/2), msg)
ch = self.stdwin.getch()
else:
break
self.stdwin.refresh()
# draw the command window
self.commandwin = curses.newwin(3, cols, rows - 3, 0)
msg = "Press 'S' to save, 'Q' to quit."
self.commandwin.addstr(1, int((cols - len(msg))/2), msg, curses.A_BOLD)
self.commandwin.chgat(1, int((cols - len(msg))/2) + 7, 1, self.green|curses.A_BOLD)
self.commandwin.chgat(1, int((cols - len(msg))/2) + 20, 1, self.red|curses.A_BOLD)
self.commandwin.refresh()
# set the y and x coordinates for the upper left corner of the measure window
uly = int((rows - 2 - self.winheight)/2)
ulx = int((cols - self.winwidth)/2)
# create the window and enable the keypad
self.measurewin = curses.newwin(self.winheight, self.winwidth, uly, ulx)
self.measurewin.keypad(True)
self.measurewin.border()
# print the vertical bar separating the two areas of the window
for i in range(self.winheight - 6):
self.measurewin.addch(i + 2, int(self.winwidth/2), curses.ACS_VLINE)
# print the horizontal bar at the bottom of the window
for i in range(self.winwidth - 1):
self.measurewin.addch(self.winheight - 3, i, curses.ACS_HLINE)
# make the corners seamless
self.measurewin.addch(self.winheight - 3, 0, curses.ACS_LTEE)
self.measurewin.addch(self.winheight - 3, self.winwidth - 1, curses.ACS_RTEE)
# print the windows entry points
self.measurewin.addstr(2, self.inputcol[0][0] - 3, "1", self.white)
self.measurewin.addstr(2, self.inputcol[0][1] - 3, "2", self.white)
self.measurewin.addstr(2, self.inputcol[1][0] - 3, "1", self.white)
self.measurewin.addstr(2, self.inputcol[1][1] - 3, "2", self.white)
self.measurewin.addstr(5, 5, "A")
self.measurewin.addstr(9, 5, "B")
self.measurewin.addstr(13, 5, "C")
self.measurewin.addstr(17, 5, "D")
self.measurewin.addstr(16, 20, "D.I")
self.measurewin.addstr(18, 20, "D.II")
self.measurewin.addstr(22, 5, "E")
self.measurewin.addstr(21, 20, "E.I")
self.measurewin.addstr(23, 20, "E.II")
self.measurewin.addstr(5, int(self.winwidth/2) + 5, "F")
self.measurewin.addstr(9, int(self.winwidth/2) + 5, "G")
self.measurewin.addstr(13, int(self.winwidth/2) + 5, "H")
self.measurewin.addstr(12, int(self.winwidth/2) + 20, "H.I")
self.measurewin.addstr(14, int(self.winwidth/2) + 20, "H.II")
self.measurewin.addstr(18, int(self.winwidth/2) + 5, "J")
self.measurewin.addstr(17, int(self.winwidth/2) + 20, "J.I")
self.measurewin.addstr(19, int(self.winwidth/2) + 20, "J.II")
# print each value of measures at the proper place
for i, side in enumerate(self.measures):
for j, row in enumerate(side):
for k, measure in enumerate(row):
self.measurewin.addstr(self.inputrow[i][j], self.inputcol[i][k] - 4,
"{} \"".format(measure))
self.measurewin.addstr(self.winheight - 2, int(self.winwidth/2) - 2, "{} K".format(self.kcell))
self.measurewin.refresh()
def inputMeasures(self):
# if kcell is True I'm in the 11th cell
kcell = False
# I only display the cursor when its counter is a multiple of 2
cursorcntr = 0
while True:
i = self.ciside
j = self.cirow
k = self.cicol
if kcell == False:
row = self.inputrow[i][j]
col = self.inputcol[i][k]
else:
row = self.winheight - 2
col = int(self.winwidth/2) + 2
# If the current cell is empty a blank space is added
if (((kcell == False and self.measures[i][j][k] == "----")
or (kcell == True and self.kcell == "----")) and cursorcntr%2 == 0):
self.measurewin.addstr(row, col - 4, " ")
chars = []
# if it isn't, I save the current characters of the entry of the cell
# in a list called chars
else:
if kcell == False:
chars = list(self.measures[i][j][k])
else:
chars = list(self.kcell)
while True:
# display the cursor only if cursorcntr is even
if cursorcntr%2 == 0:
curses.curs_set(1)
ch = self.measurewin.getch(row, col)
curses.curs_set(0)
# If the user hits the enter key, the cursor counter's value is flipped and
# I exit the main loop
if ch == 10:
cursorcntr += 1
break
# I also exit the loop if one of the following conditions if verified
if ((ch == curses.KEY_UP and j > 0)
or (ch == curses.KEY_DOWN and kcell == False)
or (ch == curses.KEY_LEFT and (i != 0 or k != 0) and kcell == False)
or (ch == curses.KEY_RIGHT and (i != 1 or k != 1) and kcell == False)
or (ch in [ord("s"), ord("S")])
or (ch in [ord("q"), ord("Q")])):
break
# If the user hits the backspace key and there are characters to be removed,
# they are removed
elif ch == 127 and len(chars) > 0 and cursorcntr%2 == 0:
chars.pop(len(chars) - 1)
self.measurewin.addstr(row, col - len(chars) - 1, " " + "".join(chars))
# If the user resizes the screen I call the initScreen method and reprint the
# whole screen
elif ch == curses.KEY_RESIZE:
self.initScreen()
self.measurewin.addstr(row, col - 4, " "*4)
if len(chars) > 0:
self.measurewin.addstr(row, col - len(chars), "".join(chars))
# if the key entered is none of the above I try to see if it's a number (or the
# character '.'). If it is, I add it to the chars list and print it on screen
else:
try:
if (chr(ch).isdigit() or ch == ord(".")) and len(chars) < 6 and cursorcntr%2 == 0:
chars.append(chr(ch))
self.measurewin.addstr(row, col - len(chars), "".join(chars))
except ValueError:
pass
# At this point I have exited the main loop and I check whether or not chars is empty or
if len(chars) > 0:
if kcell == False:
self.measures[i][j][k] = "".join(chars)
else:
self.kcell = "".join(chars)
else:
if kcell == False:
self.measures[i][j][k] = "----"
else:
self.kcell = "----"
self.measurewin.addstr(row, col - 4, "----")
# here I check which key has been entered that caused me to exit the loop, and
# perform actions accordingly for every option
if ch == curses.KEY_UP:
if kcell == True:
kcell = False
else:
self.cirow -= 1
# If I pressed an arrow key the value of the cursor counter is always set to a
# multiple of two (which means that when an arrow key is entered I will always
# get a blinking cursos in the destination cell)
cursorcntr *= 2
elif ch == curses.KEY_DOWN:
if (i == 0 and j == 6) or (i == 1 and j == 5):
kcell = True
else:
self.cirow += 1
cursorcntr *= 2
elif ch == curses.KEY_LEFT:
self.cicol -= 1
if i == 1 and k == 0:
self.ciside -= 1
self.cicol += 2
cursorcntr *= 2
elif ch == curses.KEY_RIGHT:
self.cicol += 1
if i == 0 and k == 1:
self.ciside += 1
self.cicol -= 2
if self.cirow == 6:
self.cirow -= 1
cursorcntr *= 2
# check If the user wants to save/quit
elif ch in [ord("s"), ord("S")]:
self.exit("save")
elif ch in [ord("q"), ord("Q")]:
self.exit("quit")
def exit(self, saveorquit):
if saveorquit == "save":
self.save()
raise SystemExit
def save(self):
pass
if __name__ == "__main__":
curses.wrapper(Twod2small)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T13:51:37.183",
"Id": "451175",
"Score": "1",
"body": "Please provide an example session so that reviewers can understand the program better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T14:07:07.160",
"Id": "451179",
"Score": "2",
"body": "@L.F. I'm not sure what you mean by 'example session', but what I want the program to do is: let me input some numbers in every cell, move through the cells with the arrow keys, save those numbers to a text file if I press 'S' (I omitted the save method in the code I posted as it isn't relevant to the curser part), exit without saving any number if I press 'Q', and it should handle terminal resizing. Nothing more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T18:01:19.050",
"Id": "451191",
"Score": "1",
"body": "By example session, @L.F. probably means show all input and output for an example run of the application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T23:28:07.973",
"Id": "451216",
"Score": "0",
"body": "Yeah, just show the contents of the terminal, including the input and output. Preferably demonstrate all the features. An example is worth 1000 words :)"
}
] |
[
{
"body": "<p>I can't run this unfortunately. <code>curses</code> seems to have issues on Windows. I'll just focus mainly on style and design.</p>\n\n<p>There's a few notable things about this chunk:</p>\n\n<pre><code># I also exit the loop if one of the following conditions if verified\nif ((ch == curses.KEY_UP and j > 0)\nor (ch == curses.KEY_DOWN and kcell == False)\nor (ch == curses.KEY_LEFT and (i != 0 or k != 0) and kcell == False)\nor (ch == curses.KEY_RIGHT and (i != 1 or k != 1) and kcell == False)\nor (ch in [ord(\"s\"), ord(\"S\")])\nor (ch in [ord(\"q\"), ord(\"Q\")])):\n break\n</code></pre>\n\n<ul>\n<li><code>== False</code> should really just be <code>not</code> instead</li>\n<li>You need more indentation. It's confusing to see the <code>or</code>s aligned with the <code>if</code>s. I'd indent it at least all the way up to align with the opening brace.</li>\n<li>Those two <code>ch in</code> checks at the bottom could be cleaned up.</li>\n</ul>\n\n<p>I'd write this closer to:</p>\n\n<pre><code>if ((ch == curses.KEY_UP and j > 0)\n or (ch == curses.KEY_DOWN and not kcell)\n or (ch == curses.KEY_LEFT and (i != 0 or k != 0) and not kcell)\n or (ch == curses.KEY_RIGHT and (i != 1 or k != 1) and not kcell)\n or (chr(ch).lower() in {\"s\", \"q\"})):\n break\n</code></pre>\n\n<p>I think you could probably factor out the <code>not kcell</code> check too, but my tired brain can't think of a good way at the moment.</p>\n\n<p>There is another approach though that lets you skip all the <code>or</code>s: <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a>. <code>any</code> is like a function version of <code>or</code> (and <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> is like <code>and</code>). You could change this to:</p>\n\n<pre><code>if any([ch == curses.KEY_UP and j > 0,\n ch == curses.KEY_LEFT and (i != 0 or k != 0) and not kcell,\n ch == curses.KEY_RIGHT and (i != 1 or k != 1) and not kcell,\n chr(ch).lower() in {\"s\", \"q\"}]):\n break\n</code></pre>\n\n<p>Normally, I'd say that this is an abuse of <code>any</code>, but chaining <code>or</code>s over multiple lines like you had isn't ideal either.</p>\n\n<hr>\n\n<p>In terms of design decisions, does this really need to be a class? Honestly, I'd probably store the necessary state using a <code>dataclass</code> or <code>NamedTuple</code> (or a couple distinct states), then just pass around and alter state(s) as needed. Making <code>self</code> a grab-bag of everything you may need seem messy to me.</p>\n\n<p>For example, <code>winwidth</code> and <code>winheight</code> appear to be constants. They never change throughout your program, so they should treated as constants. I'd have them outside at the top as:</p>\n\n<pre><code>WINDOW_WIDTH = 120\nWINDOW_HEIGHT = 29\n</code></pre>\n\n<p>And do <code>ciside</code>, <code>cicol</code> and <code>cirow</code> need to be attributes of the class as well? It seems like they're only used in <code>inputMeasures</code>, so why aren't they just variables local to that function? By having them \"global\" within the object, you're forcing your reader to keep them in the back of their mind in case those states are needed elsewhere in the object.</p>\n\n<hr>\n\n<p>Finally, in terms of naming, you're violating PEP8. Variable and function names should be in <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">snake_case unless you have a good reason</a>, and class names should be <a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">UpperCamelCase</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T15:58:58.903",
"Id": "451273",
"Score": "0",
"body": "@D.BenKnoble Corrected. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T16:28:45.543",
"Id": "451825",
"Score": "0",
"body": "Virtualbox runs on Windows. It is very easy to run a Linux virtual machine and use the program."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:05:27.753",
"Id": "231344",
"ParentId": "231337",
"Score": "8"
}
},
{
"body": "<p>Besides of that I support the idea of having constant values like window's <code>height</code>, <code>width</code> and <code>input_row</code> settings as class constants (uppercase names) and referencing <em>negative</em> <code>kcell</code> flag as <strong><code>not kcell</code></strong> instead of <code>kcell == False</code>\nhere's some list of advises in terms of better code organizing, restructuring conditionals and eliminating duplicates:</p>\n\n<ul>\n<li><p>window's half of <code>width</code> <code>int(self.winwidth / 2)</code> is calculated 13 times across 3 methods. <br>Instead, we'll apply <em>Extract variable</em> technique, extracting precalculated expression into the instance field <strong><code>self.win_width_half = int(self.winwidth / 2)</code></strong> and referencing it in all places it's needed <br>\n(like <code>self.inputcol = [[36, 50], [self.win_width_half + 36, self.win_width_half + 50]]</code>)</p></li>\n<li><p>setting <em>\"windows entry points\"</em> in <code>initScreen</code> method (should be renamed to <strong><code>init_screen</code></strong>):\ninvolves consecutive 20 calls of <code>self.measurewin.addstr(...)</code> function.<br>\nInstead, we can define <em>entry points</em> attributes beforehand and then pass them in simple iteration:</p>\n\n<pre><code>win_entry_points_attrs = [\n (2, self.inputcol[0][0] - 3, \"1\", self.white),\n (2, self.inputcol[0][1] - 3, \"2\", self.white),\n (2, self.inputcol[1][0] - 3, \"1\", self.white),\n (2, self.inputcol[1][1] - 3, \"2\", self.white),\n\n (5, 5, \"A\"),\n (9, 5, \"B\"),\n (13, 5, \"C\"),\n (17, 5, \"D\"),\n (16, 20, \"D.I\"),\n (18, 20, \"D.II\"),\n (22, 5, \"E\"),\n (21, 20, \"E.I\"),\n (23, 20, \"E.II\"),\n\n (5, self.win_width_half + 5, \"F\"),\n (9, self.win_width_half + 5, \"G\"),\n (13, self.win_width_half + 5, \"H\"),\n (12, self.win_width_half + 20, \"H.I\"),\n (14, self.win_width_half + 20, \"H.II\"),\n (18, self.win_width_half + 5, \"J\"),\n (17, self.win_width_half + 20, \"J.I\"),\n (19, self.win_width_half + 20, \"J.II\"),\n]\n# print the windows entry points\nfor attrs in win_entry_points_attrs:\n self.measurewin.addstr(*attrs) \n</code></pre></li>\n</ul>\n\n<p><em>Optimizations</em> within <code>inputMeasures</code> method (should be renamed to <strong><code>input_measures</code></strong>):</p>\n\n<ul>\n<li><p>the condition:</p>\n\n<pre><code>if ((ch == curses.KEY_UP and j > 0)\n or (ch == curses.KEY_DOWN and kcell == False)\n or (ch == curses.KEY_LEFT and (i != 0 or k != 0) and kcell == False)\n or (ch == curses.KEY_RIGHT and (i != 1 or k != 1) and kcell == False)\n or (ch in [ord(\"s\"), ord(\"S\")])\n or (ch in [ord(\"q\"), ord(\"Q\")])):\n break\n</code></pre>\n\n<p>has a common check <code>kcell == False</code> (should be <code>not kcell</code>) in 3 branches (in the middle) and that's a sign of <em>Consolidate conditional</em> refactoring technique:</p>\n\n<pre><code>if ((ch == curses.KEY_UP and j > 0)\n or (not kcell and (ch == curses.KEY_DOWN\n or (ch == curses.KEY_LEFT and (i != 0 or k != 0))\n or (ch == curses.KEY_RIGHT and (i != 1 or k != 1))))\n or (chr(ch).lower() in (\"s\", \"q\"))):\n break\n</code></pre></li>\n<li><p>the variable <code>cursorcntr</code> (<em>cursor counter</em>) deserves for a more meaningful variable name (<em>Rename variable</em> technique) - I would suggest <strong><code>cursor_cnt</code></strong></p></li>\n<li><p>the last complex <code>if .. elif .. elif</code> conditional of 6 branches at the end of method <code>input_measures</code> seems to be a good candidate for <a href=\"https://refactoring.com/catalog/replaceConditionalWithPolymorphism.html\" rel=\"nofollow noreferrer\">Replace Conditional with Polymorphism</a> technique (OOP approach) but that would require more knowledge and vision about your program conception/settings. <br>For now, the first 4 branches of that conditional perform the same action <strong><code>cursor_cnt *= 2</code></strong> - we can eliminate duplication with additional check.<br>\nIt's good to move \"<code>save/quit</code>\" branches <strong>up</strong>, as they call <code>self.exit()</code> which will throw <code>raise SystemExit</code> to exit the program.<br>\nThus the reorganized conditional would look as:</p>\n\n<pre><code># set of key codes defined in the parent scope (at least before the loop or as instance variable)\nkey_set = set((curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT))\n...\n# check If the user wants to save/quit\ninp_char = chr(ch).lower()\nif inp_char == 's':\n self.exit(\"save\")\nelif inp_char == 'q':\n self.exit(\"quit\")\n\nif ch in key_set:\n cursor_cnt *= 2\n\nif ch == curses.KEY_UP:\n if kcell:\n kcell = False\n else:\n self.cirow -= 1\n # If I pressed an arrow key the value of the cursor counter is always set to a\n # multiple of two (which means that when an arrow key is entered I will always\n # get a blinking cursos in the destination cell)\n\nelif ch == curses.KEY_DOWN:\n if (i == 0 and j == 6) or (i == 1 and j == 5):\n kcell = True\n else:\n self.cirow += 1\n\nelif ch == curses.KEY_LEFT:\n self.cicol -= 1\n if i == 1 and k == 0:\n self.ciside -= 1\n self.cicol += 2\n\nelif ch == curses.KEY_RIGHT:\n self.cicol += 1\n if i == 0 and k == 1:\n self.ciside += 1\n self.cicol -= 2\n if self.cirow == 6:\n self.cirow -= 1\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T20:13:19.043",
"Id": "231350",
"ParentId": "231337",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "231350",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T11:59:42.340",
"Id": "231337",
"Score": "12",
"Tags": [
"python",
"curses"
],
"Title": "Python Curses input screen"
}
|
231337
|
<p>I've written a function that takes a list of extensions and recursively finds files of those types, and logs their paths to a text file.</p>
<p><strong>Usage example (finding image files in a home directory):</strong></p>
<pre class="lang-cpp prettyprint-override"><code>// set up filestream for unicode
const std::locale utf8_locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
std::wofstream log("image_paths.txt", std::ios::app); // append mode
log.imbue(utf8_locale);
const std::set<std::wstring> image_extensions = {L".jpeg", L".jpg", L".tiff", L".gif", L".bmp", L".png"};
get_files(L"C:\\Users\\username", image_extensions, log);
</code></pre>
<p><strong>Output to image_paths.txt:</strong></p>
<pre><code>C:\Users\username\image.jpg
C:\Users\username\image.png
C:\Users\username\directory\ajdsk.bmp
C:\Users\username\directory\subdirectory\other file.tiff
C:\Users\username\directory with spaces\file with spaces.jpeg
</code></pre>
<p><strong>Function Code:</strong></p>
<pre class="lang-cpp prettyprint-override"><code>// return 0 -- all good
// return 1 -- root doesn't exist
// return 2 -- root isn't a directory
// return 3 -- no matching files found or error opening first file
// return 4 -- hit recursion limit
auto get_files(_In_ const std::wstring root, // root dir of search
_In_ const std::set<std::wstring> &ext, // extensions to search for
_Out_ std::wofstream &log, // file to write paths to
_In_ unsigned limit = 10 /* default recursion limit */) -> int
{
if(limit == 0) return 4;
// check root path
{
DWORD root_attrib = GetFileAttributesW(root.c_str());
if(root_attrib == INVALID_FILE_ATTRIBUTES) return 1; // root doesn't exist
if(!(root_attrib & FILE_ATTRIBUTE_DIRECTORY)) return 2; // root isn't a directory
}
LPCWSTR dir; // root directory + "\*"
HANDLE file = INVALID_HANDLE_VALUE; // handle to found file
WIN32_FIND_DATAW file_info; // attributes of found file
// prepare path for use with FindFile functions
std::wstring root_slash = root;
root_slash.append(L"\\*");
dir = root_slash.c_str();
file = FindFirstFileW(dir, &file_info);
if(file == INVALID_HANDLE_VALUE) return 3; // no matching files found or error opening first file
do { // for each file in directory
// for some reason
// file_info != L"." && file_info != L".."
// won't work unless file_info.cFileName is assigned to a var
std::wstring name = file_info.cFileName;
std::wstring path = root; // full path to current file
path.append(L"\\").append(name);
if(!(file_info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) // not read-only
&& !(file_info.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) // not physically moved to offline storage
&& !(file_info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) // not a system file
&& file_info.dwFileAttributes != INVALID_FILE_ATTRIBUTES // not invalid
&& (name != L"." && name != L"..")) { // not "." or ".."
if(file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // file is a directory
get_files(path, ext, log, --limit);
else // file is not a directory
if(ext.find(PathFindExtensionW(path.c_str())) != ext.end()) // extension matches
log << path << '\n' << std::flush; // log path to file
}
} while(FindNextFileW(file, &file_info) != 0);
FindClose(file);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T13:55:06.357",
"Id": "451177",
"Score": "0",
"body": "Welcome to Code Review! You can take the [tour] for an overview of our site."
}
] |
[
{
"body": "<p>The declarations for <code>dir</code> and <code>file</code> can be moved lower, where they are first assigned values. However, since <code>dir</code> is only used in one place, it can be eliminated and the value used directly.</p>\n\n<pre><code>HANDLE file = FindFirstFileW(root_slash.c_str(), &file_info);\n</code></pre>\n\n<p>When testing file attributes, the check for invalid attributes should be first, and you can combine several individual tests into one:</p>\n\n<pre><code>if (file_info.dwFileAttributes != INVALID_FILE_ATTRIBUTES && \n !(file_info.dwFileAttributes & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_SYSTEM) &&\n (name != L\".\" && name != L\"..\"))\n</code></pre>\n\n<p>Since there are three attributes you want to ignore, you can define a constant to hold them rather than list them out in your if statement.</p>\n\n<p>Incidentally, since <code>cFileName</code> is a C array, you need to assign it to a string variable to be able to use the equality comparisons with it. Or you could leave it in <code>cFileName</code> and use basic comparisons like <code>strcmp</code>. Since there are two similar strings that are very short, you could also do direct character comparison but that makes the code larger and harder to understand and should only be done when absolutely necessary.</p>\n\n<p>Since you decrement <code>limit</code> with each recursive call to <code>get_files</code>, you reduce the limit for the current directory as well. If your initial directory has 16 subdirectories, your search will skip the 10th, may skip some of the subdirectories of the first 9, and will search all of the directories under the 11th and later subdirectories. You should use</p>\n\n<pre><code>get_files(path, ext, log, limit - 1);\n</code></pre>\n\n<p>instead. If any of the recursive calls fail in some way (return nonzero) you ignore the error and keep going. This is reasonable in this instance, but does make the \"recursion limit reached\" error somewhat pointless since it will never be returned to the caller. This one value should probably be handled differently, so that if any search reaches the recursion limit, this value is returned to the original caller to indicate that the results are incomplete.</p>\n\n<p>Potentially more serious is that your extension comparison is case sensitive. A file called \"IMAGE.JPG\" will not be listed, because the extension ins in uppercase and you're looking for a lowercase one.</p>\n\n<p>Unless there's an absolute need for it, you should omit the <code>std::flush</code> from the log outputs. This will reduce the performance as every filename will be written one at a time, instead of in larger chunks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T13:44:35.803",
"Id": "231340",
"ParentId": "231338",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231340",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T12:21:31.100",
"Id": "231338",
"Score": "2",
"Tags": [
"c++",
"recursion",
"file-system",
"windows",
"winapi"
],
"Title": "Recursively find files of certain types and log their paths (C++)"
}
|
231338
|
<p>I am trying to create a program where a user inputs two numbers - a base and an exponent, while exponent is a binary number. Then prints out the last two digits of the result. My code is working well, but according to the time execution it is not the fastest way to do it. I read a little about using Horner's method, is there a way to use it here? If so, how?</p>
<pre><code>base = int(input())
exponent = int(input())
def binaryToDec(binary):
decimal, i = 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
return decimal
exponent = binaryToDec(exponent)
result = base ** exponent
result = abs(result)%100
print(result)
</code></pre>
<p>For example, the output of <code>3</code> and <code>1010</code> should be <code>49</code>.</p>
<p>Another example:</p>
<p>Input:</p>
<pre><code>111111111111111111111111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111111111111111111
</code></pre>
<p>Output:</p>
<pre><code>31
</code></pre>
<p>I expect the program to work faster in doing so, how can I do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T16:14:10.017",
"Id": "451181",
"Score": "1",
"body": "Are you aware Python has an in-built function for this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T17:40:44.530",
"Id": "451190",
"Score": "1",
"body": "What are the two least significant digits of 101\\*\\**n* and 9876543201\\*\\**n*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T18:26:18.980",
"Id": "451194",
"Score": "0",
"body": "@Mast for the method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T18:27:21.593",
"Id": "451195",
"Score": "0",
"body": "@greybeard how can i check this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T18:56:17.350",
"Id": "451198",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T21:58:16.323",
"Id": "451214",
"Score": "0",
"body": "`how can [I check something general about natural numbers]?` If you can't convince yourself by reasoning, try a few values for *n*. Put up a hypothesis, try to prove it. Induction is a prime candidate where natural numbers are involved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T21:41:44.587",
"Id": "470363",
"Score": "0",
"body": "@Hemal `pow(base, exponent, 10**d)` gives the last `d` digits computed efficiently."
}
] |
[
{
"body": "<ul>\n<li><strong>document your code. In the code.</strong><br>\nPython got it right with <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstrings</a>:<br>\nThe laziest copying of a function includes its docstring, ready for introspection.</li>\n<li><strong>document what everything is there for</strong> wherever not blatantly obvious.<br>\nThis would include the problem description - if it was in the source code, one might notice that the statements use an <code>abs()</code> where the description never mentions it.</li>\n<li>let a tool help you to follow the <a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>.</li>\n<li>your naming is OK (with the exception of <code>result</code> - there should be <em>digits of power</em> or <em>modulus of power</em>)</li>\n<li>your <code>binaryToDec()</code> is too weird to mention - just try to describe what it does accomplish, and how.</li>\n<li>read the requirement specification carefully. If possible, fix in writing how to check requirements are met.<br>\nYou mention that your implementation <code>is not the fastest way to do [modular exponentiation]</code>: is there an upper limit on execution time? Rank among course-mates?<br>\nThe way the exponent is specified looks constructed to head you to use one particular way to implement exponentiation.</li>\n<li>know your python library. <a href=\"https://codereview.stackexchange.com/questions/231342/printing-the-last-two-digits-of-an-exponential-calculation#comment451181_231342\">Mast</a> commented the existence of a built-in - for conversion of strings to numbers using a non-default base, more likely than not.</li>\n</ul>\n\n<p>How not to do more than hardly avoidable (/be \"fast\"):<br>\nFor starters, only the last <em>d</em> digits of a number have any influence on the last <em>d</em> digits of its integral powers represented using the same base <em>b</em>.<br>\nMoreover, those last <em>d</em> digits become cyclic with <em>b**d</em> an integral multiple of cycle length - just watch out for things like <code>2**100</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T09:14:40.690",
"Id": "452461",
"Score": "0",
"body": "Without change of base, `only the last d digits of a number have any influence on the last d digits of its integral powers`, products, sums, differences - propagation in direction of lower significance starts only with division."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T08:06:59.893",
"Id": "231770",
"ParentId": "231342",
"Score": "1"
}
},
{
"body": "<p>You say the exponent is written in binary, but then you're reading it as decimal, call it <code>binary</code> (even though it's a number, not a string, so it's neither binary nor decimal), somehow convert it, and call the result <code>decimal</code> (again not true, as it's a number, not a string). Just read it as binary instead of all of that.</p>\n<p>For efficiency, don't compute the whole power. That's highly inefficient, both time and space. Use <code>pow</code> appropriately, making it work modulo 100 <em>during</em> the exponentiation so it's super fast.</p>\n<p>The whole efficient solution:</p>\n<pre><code>base = int(input())\nexponent = int(input(), 2)\nprint(pow(base, exponent, 100))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-30T12:02:25.937",
"Id": "483791",
"Score": "0",
"body": "Hmm, just realized this question is old. Was one of the Top Questions on the front page, due to \"modified 1 hour ago Community♦ 1\". Not sure what that means. I don't see any modification..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-30T11:55:43.263",
"Id": "246242",
"ParentId": "231342",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T14:44:46.270",
"Id": "231342",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Printing the last two digits of an exponential calculation"
}
|
231342
|
<p>Here are ~100 lines of code implementing three classes (<code>ZipRef</code>, <code>ZipIter</code>, <code>Zip</code>) which should satisfy the zip iterator pattern in a STL-compatible way. This means that, unlike <code>boost::zip_iterator</code>, <code>ZipIter</code> can be safely (I hope!) used in various algorithms like <code>std::rotate</code> and <code>std::sort</code>. I tried to embrace the power of C++17, aiming at writing much more readable (variadic) template code compared to what allowed by C++11.</p>
<p>Note: maintained on <a href="https://github.com/dpellegr/ZipIterator" rel="nofollow noreferrer">GitHub</a> (includes a usage example and some extra notes), the code in this post is not going to be edited.</p>
<pre><code>//
// C++17 implementation of ZipIterator by Dario Pellegrini <pellegrini.dario@gmail.com>
// Still unsure about the licence, but something in the line of just providing attribution
// October 2019
//
#include <tuple>
template <typename ...T>
class ZipRef {
std::tuple<T*...> ptr;
public:
ZipRef() = delete;
ZipRef(const ZipRef& z) = default;
ZipRef(ZipRef&& z) = default;
ZipRef(T* const... p): ptr(p...) {}
ZipRef& operator=(const ZipRef& z) { return copy_assign( z); }
ZipRef& operator=(const std::tuple<T...>& val) { return val_assign(val); }
template <size_t I = 0>
ZipRef& copy_assign(const ZipRef& z) {
*(std::get<I>(ptr)) = *(std::get<I>(z.ptr));
if constexpr( I+1 < sizeof...(T) ) return copy_assign<I+1>(z);
return *this;
}
template <size_t I = 0>
ZipRef& val_assign(const std::tuple<T...>& t) {
*(std::get<I>(ptr)) = std::get<I>(t);
if constexpr( I+1 < sizeof...(T) ) return val_assign<I+1>(t);
return *this;
}
std::tuple<T...> val() const {return std::apply([](auto&&...args){ return std::tuple((*args)...); }, ptr);}
operator std::tuple<T...>() const { return val(); }
template <size_t I = 0>
void swap(const ZipRef& o) const {
std::swap(*(std::get<I>(ptr)), *(std::get<I>(o.ptr)));
if constexpr( I+1 < sizeof...(T) ) swap<I+1>(o);
}
#define OPERATOR(OP) \
bool operator OP(const ZipRef & o) const { return val() OP o.val(); } \
inline friend bool operator OP(const ZipRef& r, const std::tuple<T...>& t) { return r.val() OP t; } \
inline friend bool operator OP(const std::tuple<T...>& t, const ZipRef& r) { return t OP r.val(); }
OPERATOR(==) OPERATOR(<=) OPERATOR(>=)
OPERATOR(!=) OPERATOR(<) OPERATOR(>)
#undef OPERATOR
};
template<typename ...IT>
class ZipIter {
std::tuple<IT...> it;
template<int N, typename... T> using NthTypeOf =
typename std::tuple_element<N, std::tuple<T...>>::type;
template<typename... T> using FirstTypeOf = NthTypeOf<0, T...>;
public:
using iterator_category = typename std::iterator_traits<FirstTypeOf<IT...>>::iterator_category;
using difference_type = typename std::iterator_traits<FirstTypeOf<IT...>>::difference_type;
using value_type = std::tuple<typename std::iterator_traits<IT>::value_type ...>;
using pointer = std::tuple<typename std::iterator_traits<IT>::pointer ...>;
using reference = ZipRef<typename std::iterator_traits<IT>::value_type ...>;
ZipIter() = default;
ZipIter(const ZipIter &rhs) = default;
ZipIter(ZipIter&& rhs) = default;
ZipIter(const IT&... rhs): it(rhs...) {}
ZipIter& operator=(const ZipIter& rhs) = default;
ZipIter& operator=(ZipIter&& rhs) = default;
ZipIter& operator+=(const difference_type d) {
std::apply([&d](auto&&...args){((std::advance(args,d)),...);}, it); return *this;
}
ZipIter& operator-=(const difference_type d) { return operator+=(-d); }
reference operator* () const {return std::apply([](auto&&...args){return reference(&(*(args))...);}, it);}
pointer operator->() const {return std::apply([](auto&&...args){return pointer (&(*(args))...);}, it);}
reference operator[](difference_type rhs) const {return *(operator+(rhs));}
ZipIter& operator++() { return operator+=( 1); }
ZipIter& operator--() { return operator+=(-1); }
ZipIter operator++(int) {ZipIter tmp(*this); operator++(); return tmp;}
ZipIter operator--(int) {ZipIter tmp(*this); operator--(); return tmp;}
difference_type operator-(const ZipIter& rhs) const {return std::get<0>(it)-std::get<0>(rhs.it);}
ZipIter operator+(const difference_type d) const {ZipIter tmp(*this); tmp += d; return tmp;}
ZipIter operator-(const difference_type d) const {ZipIter tmp(*this); tmp -= d; return tmp;}
inline friend ZipIter operator+(const difference_type d, const ZipIter& z) {return z+d;}
inline friend ZipIter operator-(const difference_type d, const ZipIter& z) {return z-d;}
#define OPERATOR(OP) \
bool operator OP(const ZipIter& rhs) const {return it OP rhs.it;}
OPERATOR(==) OPERATOR(<=) OPERATOR(>=)
OPERATOR(!=) OPERATOR(<) OPERATOR(>)
#undef OPERATOR
};
template<typename ...Container>
class Zip {
std::tuple<Container&...> zip;
public:
Zip() = delete;
Zip(const Zip& z) = default;
Zip(Zip&& z) = default;
Zip(Container&... z): zip(z...) {}
#define HELPER(OP) \
auto OP(){return std::apply([](auto&&... args){ return ZipIter((args.OP())...);}, zip);}
HELPER( begin) HELPER( end)
HELPER(rbegin) HELPER(rend)
#undef HELPER
};
#include <utility>
using std::swap;
template<typename ...T> void swap(const ZipRef<T...>& a, const ZipRef<T...>& b) { a.swap(b); }
#include <sstream>
template< class Ch, class Tr, class...IT, typename std::enable_if<(sizeof...(IT)>0), int>::type = 0>
auto& operator<<(std::basic_ostream<Ch, Tr>& os, const ZipRef<IT...>& t) {
std::basic_stringstream<Ch, Tr> ss;
ss << "[ ";
std::apply([&ss](auto&&... args) {((ss << args << ", "), ...);}, t.val());
ss.seekp(-2, ss.cur);
ss << " ]";
return os << ss.str();
}
</code></pre>
<p>Usage example from the <a href="https://github.com/dpellegr/ZipIterator#example" rel="nofollow noreferrer">README</a>:</p>
<blockquote>
<p>Consider this minimal example:</p>
<pre><code>#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include "ZipIterator.hpp" //Header only ;)
int main() {
std::vector<int> a{3,1,4,2};
std::vector<std::string> b{"Alice","Bob","Charles","David"};
auto zip = Zip(a,b);
for (const auto & z: zip) std::cout << z << std::endl;
std::cout << std::endl;
std::sort(zip.begin(), zip.end());
for (const auto & z: zip) std::cout << z << std::endl;
return 0;
}
</code></pre>
<p>It can be compiled by simply enabling the c++17 (or more recent)
standard and the produced output is:</p>
<pre class="lang-none prettyprint-override"><code>$ g++ -std=c++17 main.cpp -o main.out && ./main.out
[ 3, Alice ]
[ 1, Bob ]
[ 4, Charles ]
[ 2, David ]
[ 1, Bob ]
[ 2, David ]
[ 3, Alice ]
[ 4, Charles ]
</code></pre>
<p>Behind the curtain the permutations (either by swapping or copying)
applied by <code>std::sort</code> to the elements of vector <code>a</code> have been
simultaneously applied to vector <code>b</code> as well.</p>
<p>Note that it would have been possible to zip a third (and more) vector
as well, as the implementation leverages on variadic templates.</p>
</blockquote>
<p>The reason for <code>ZipRef</code> over <code>std::tuple</code> is that one needs special constructor, assignment and comparison operators to be able to handle the tuple of pointers with a value-like semantics. One also needs a tuple of pointers because it allows to manipulate the data even if the tuple is constant, so one can extend the lifetime of non-const lvalues references of ZipRef (as the one returned when dereferencing ZipIter) by binding them to const references, while still being able, later, to modify the data being pointed to. Note that the custom swap, quite unusually, takes const references!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T13:12:54.290",
"Id": "451259",
"Score": "0",
"body": "I have copied the usage example on your README file into the question. This is probably a good idea because it helps make the question more self-contained. Feel free to roll back if that's not desired :)"
}
] |
[
{
"body": "<p>A constant <code>Zip</code> can't easily be iterated:</p>\n<pre><code> auto const zip = Zip(a,b);\n\n for (const auto & z: zip) std::cout << z << std::endl;\n</code></pre>\n<p>All that's necessary for that to work is to add some <code>const</code> operators:</p>\n<pre><code> #define HELPER(OP) \\\n auto OP() const {return std::apply([](auto&&... args){ return ZipIter((args.OP())...);}, zip);}\n HELPER( begin) HELPER( end)\n HELPER(rbegin) HELPER(rend)\n HELPER( cbegin) HELPER( cend)\n HELPER(crbegin) HELPER(crend)\n #undef HELPER\n</code></pre>\n<p>There's still more to do here, as it's surprising that a <code>const Zip</code> returns mutable iterators. Unfortunately, I haven't yet come up with a solution to that problem. The nearest I got was to separate out the const <code>(r){begin,end}</code> like this:</p>\n<pre><code>#define HELPER(OP) \\\n auto OP() const {return std::apply([](auto&&... args) { return ZipIter((args.c##OP())...);}, zip);}\n HELPER(begin) HELPER(end)\n HELPER(rbegin) HELPER(rend)\n#undef HELPER\n</code></pre>\n<p>but it fails because <code>ZipIter::reference</code> is based on <code>IT::value_type</code>, which doesn't carry the constness with it. I think I'd need to define a parallel <code>const_ZipIter</code> to support that.</p>\n<hr />\n<p>From C++20 onwards, we can implement <code>operator <=></code> instead of all the relational operators in <code>ZipIter</code>.</p>\n<hr />\n<p><code>std::size_t</code> is misspelt (and is missing its header), where it's used as a non-type template argument.</p>\n<p>We're also missing an include of <code><utility></code>, for <code>std::swap</code> used in <code>ZipRef</code>.</p>\n<hr />\n<p>I think we should be allowing argument-dependent lookup of <code>swap</code> here:</p>\n<blockquote>\n<pre><code> template <size_t I = 0>\n void swap(const ZipRef& o) const {\n std::swap(*(std::get<I>(ptr)), *(std::get<I>(o.ptr)));\n if constexpr( I+1 < sizeof...(T) ) swap<I+1>(o);\n }\n</code></pre>\n</blockquote>\n<p>I suggest:</p>\n<pre><code> void swap(const ZipRef& o) const {\n swap_impl<0>(o);\n }\n\nprivate:\n template <std::size_t I>\n void swap_impl(const ZipRef& o) const {\n using std::swap;\n swap(*std::get<I>(ptr), *std::get<I>(o.ptr));\n if constexpr(I+1 < sizeof...(T)) swap_impl<I+1>(o);\n }\n</code></pre>\n<p>I guess that reversing the order might make for simpler code, but could fail the strong exception guarantee if an element's <code>swap()</code> might throw.</p>\n<p>Also with <code>swap()</code>, I think that this being <code>const</code> is sufficiently weird to justify a decent explanatory comment in the code. It might save you trying to "fix" this "bug" later!</p>\n<hr />\n<p>Just before our non-member swap, we have a <code>using</code> declaration:</p>\n<pre><code>using std::swap;\n</code></pre>\n<p>Not only do we not need this, it's also poor practice to inflict this on users of the header.</p>\n<hr />\n<p>Misuse can give hard-to-detect problems. For example, the program crashed when I tried passing inputs of different length. We could add some error checking to the <code>Zip</code> constructor:</p>\n<pre><code>#include <algorithm>\n#include <functional>\n</code></pre>\n\n<pre><code> Zip(Container&... z)\n : zip{z...}\n {\n auto const len = {(zip.size())...,};\n if (std::adjacent_find(len.begin(), len.end(), std::not_equal_to()) != len.end())\n throw std::invalid_argument("array lengths differ");\n }\n</code></pre>\n<p>A little further work should be able to add the actual lengths to the exception message to improve its value to the programmer.</p>\n<hr />\n<h1>Modified code</h1>\n<p>This is with my changes; I'm sure there's more improvements that could be made.</p>\n<pre><code>#include <cstdint>\n#include <algorithm>\n#include <functional>\n#include <tuple>\n#include <utility>\n\ntemplate <typename ...T>\nclass ZipRef {\n std::tuple<T*...> ptr;\npublic:\n ZipRef() = delete;\n ZipRef(const ZipRef& z) = default;\n ZipRef(ZipRef&& z) = default;\n ZipRef(T* const... p): ptr(p...) {}\n\n ZipRef& operator=(const ZipRef& z) { return copy_assign(z); }\n ZipRef& operator=(const std::tuple<T...>& val) { return val_assign(val); }\n\n template <std::size_t I = 0>\n ZipRef& copy_assign(const ZipRef& z) {\n *(std::get<I>(ptr)) = *(std::get<I>(z.ptr));\n if constexpr(I+1 < sizeof...(T)) return copy_assign<I+1>(z);\n return *this;\n }\n template <std::size_t I = 0>\n ZipRef& val_assign(const std::tuple<T...>& t) {\n *(std::get<I>(ptr)) = std::get<I>(t);\n if constexpr(I+1 < sizeof...(T)) return val_assign<I+1>(t);\n return *this;\n }\n\n std::tuple<T...> val() const {return std::apply([](auto&&...args) { return std::tuple((*args)...); }, ptr);}\n operator std::tuple<T...>() const { return val(); }\n\n void swap(const ZipRef& o) const {\n swap_impl<sizeof...(T)-1>(o);\n }\n\nprivate:\n template <std::size_t I>\n void swap_impl(const ZipRef& o) const {\n using std::swap;\n swap(*std::get<I>(ptr), *std::get<I>(o.ptr));\n if constexpr(I) swap_impl<I-1>(o);\n }\n\npublic:\n#define OPERATOR(OP) \\\n bool operator OP(const ZipRef & o) const { return val() OP o.val(); } \\\n inline friend bool operator OP(const ZipRef& r, const std::tuple<T...>& t) { return r.val() OP t; } \\\n inline friend bool operator OP(const std::tuple<T...>& t, const ZipRef& r) { return t OP r.val(); }\n\n OPERATOR(==) OPERATOR(<=) OPERATOR(>=)\n OPERATOR(!=) OPERATOR(<) OPERATOR(>)\n#undef OPERATOR\n\n};\n\ntemplate<typename ...IT>\nclass ZipIter {\n std::tuple<IT...> it;\n\n template<int N, typename... T> using NthTypeOf =\n typename std::tuple_element<N, std::tuple<T...>>::type;\n template<typename... T> using FirstTypeOf = NthTypeOf<0, T...>;\n\npublic:\n using iterator_category = typename std::iterator_traits<FirstTypeOf<IT...>>::iterator_category;\n using difference_type = typename std::iterator_traits<FirstTypeOf<IT...>>::difference_type;\n using value_type = std::tuple<typename std::iterator_traits<IT>::value_type ...>;\n using pointer = std::tuple<typename std::iterator_traits<IT>::pointer ...>;\n using reference = ZipRef<typename std::iterator_traits<IT>::value_type ...>;\n\n ZipIter() = default;\n ZipIter(const ZipIter &rhs) = default;\n ZipIter(ZipIter&& rhs) = default;\n ZipIter(IT... rhs): it(std::move(rhs)...) {}\n\n ZipIter& operator=(const ZipIter& rhs) = default;\n ZipIter& operator=(ZipIter&& rhs) = default;\n\n ZipIter& operator+=(const difference_type d) {\n std::apply([&d](auto&&...args) {((std::advance(args,d)),...);}, it); return *this;\n }\n ZipIter& operator-=(const difference_type d) { return operator+=(-d); }\n\n reference operator* () const {return std::apply([](auto&&...args) {return reference(&(*(args))...);}, it);}\n pointer operator->() const {return std::apply([](auto&&...args) {return pointer(&(*(args))...);}, it);}\n reference operator[](difference_type rhs) const {return *(operator+(rhs));}\n\n ZipIter& operator++() { return operator+=(1); }\n ZipIter& operator--() { return operator+=(-1); }\n ZipIter operator++(int) {ZipIter tmp(*this); operator++(); return tmp;}\n ZipIter operator--(int) {ZipIter tmp(*this); operator--(); return tmp;}\n\n difference_type operator-(const ZipIter& rhs) const {return std::get<0>(it)-std::get<0>(rhs.it);}\n ZipIter operator+(const difference_type d) const {ZipIter tmp(*this); tmp += d; return tmp;}\n ZipIter operator-(const difference_type d) const {ZipIter tmp(*this); tmp -= d; return tmp;}\n inline friend ZipIter operator+(const difference_type d, const ZipIter& z) {return z+d;}\n inline friend ZipIter operator-(const difference_type d, const ZipIter& z) {return z-d;}\n\n#define OPERATOR(OP) \\\n bool operator OP(const ZipIter& rhs) const {return it OP rhs.it;}\n OPERATOR(==) OPERATOR(<=) OPERATOR(>=)\n OPERATOR(!=) OPERATOR(<) OPERATOR(>)\n#undef OPERATOR\n};\n\ntemplate<typename ...Container>\nclass Zip {\n std::tuple<Container&...> zip;\n\npublic:\n Zip() = delete;\n Zip(const Zip& z) = default;\n Zip(Zip&& z) = default;\n Zip(Container&... z)\n : zip {z...}\n {\n auto const len = {(z.size())...,};\n if (std::adjacent_find(len.begin(), len.end(), std::not_equal_to()) != len.end())\n throw std::invalid_argument("array lengths differ");\n }\n\n#define HELPER(OP) \\\n auto OP() {return std::apply([](auto&&... args) { return ZipIter((args.OP())...);}, zip);}\n HELPER(begin) HELPER(end)\n HELPER(rbegin) HELPER(rend)\n#undef HELPER\n\n#define HELPER(OP) \\\n auto OP() const {return std::apply([](auto&&... args) { return ZipIter((args.OP())...);}, zip);}\n HELPER(begin) HELPER(end)\n HELPER(rbegin) HELPER(rend)\n HELPER(cbegin) HELPER(cend)\n HELPER(crbegin) HELPER(crend)\n#undef HELPER\n};\n\n#include <utility>\nusing std::swap;\ntemplate<typename ...T> void swap(const ZipRef<T...>& a, const ZipRef<T...>& b) { a.swap(b); }\n\n#include <sstream>\ntemplate< class Ch, class Tr, class...IT, typename std::enable_if<(sizeof...(IT)>0), int>::type = 0>\nauto& operator<<(std::basic_ostream<Ch, Tr>& os, const ZipRef<IT...>& t) {\n std::basic_stringstream<Ch, Tr> ss;\n ss << "[ ";\n std::apply([&ss](auto&&... args) {((ss << args << ", "), ...);}, t.val());\n ss.seekp(-2, ss.cur);\n ss << " ]";\n return os << ss.str();\n}\n\n\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\nint main() {\n std::vector<int> a {3,1,4,2};\n std::vector<std::string> b {"Alice","Bob","Charles","David"};\n\n auto const zip = Zip(a,b);\n\n for (const auto & z: zip) std::cout << z << std::endl;\n\n std::cout << std::endl;\n std::sort(zip.begin(), zip.end());\n for (const auto & z: zip) std::cout << z << std::endl;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T23:05:12.647",
"Id": "451716",
"Score": "1",
"body": "Your solution to the problem with different length ranges won't work for input iterators (no way to measure length without consuming the range -> later iteration will fail) or infinite ranges (size measurement will never finish). A more general approach would be to use a sentinel returned by `Zip::end` that compares `true` to any `ZipIter` where any contained iterator is equal to its respective end iterator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:04:33.893",
"Id": "451750",
"Score": "1",
"body": "Yes, good point - I was seduced by the word `Container` into assuming we could use `size()` safely. Can I claim in defence that it was only meant as an illustration that we could at least *try* validating input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T15:11:06.027",
"Id": "451802",
"Score": "0",
"body": "I attempted to modify the ADL of swap (which I also don't like in its current state) as you suggested, but I did not manage to satisfy the compiler. It's probably my fault, but it would be great if you could expand a bit on that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T14:48:15.990",
"Id": "231546",
"ParentId": "231352",
"Score": "5"
}
},
{
"body": "<h1>Lies, damned lies, ... and <code>iterator_category</code></h1>\n<p>This line from <code>ZipIter</code> is a big lie:</p>\n<pre><code> using iterator_category = typename std::iterator_traits<FirstTypeOf<IT...>>::iterator_category;\n</code></pre>\n<p>Why? Because it unequivocally expands the capabilities of the first iterator type to all the other ones.</p>\n<p>This has some bad consequences: Some operations (e.g. <code>std::sort</code>) require at least some specific iterator category to work.</p>\n<p>Example:</p>\n<pre><code>auto a = std::vector<std::string>{ "A", "B", "C", "A" };\nauto b = std::forward_list<int>{ 4, 3, 2, 1 };\n\nauto zip = Zip(a, b);\nstd::sort(zip.begin(), zip.end()); // This cannot succeed\n</code></pre>\n<p>In this case, <code>std::sort</code> requires random access iterators, which <code>std::vector</code> does provide. However, <code>std::forward_list</code> doesn't (it only provides forward iterators). But <code>ZipIter</code> promises that it is a random access iterator, even though random access operations are not supported on some contained iterators.</p>\n<p>Ok, <code>ZipIter::iterator_category</code> is a lie, but why is it so damning?</p>\n<p>Because <code>iterator_category</code> is an easy to use feature check (with strong constraints mandated by the standard). So many algorithm implementations just check for <code>iterator_category</code>. If you're lucky, they will still fail at compile time, but in some subtler cases you just silently run into undefined behavior.</p>\n<p>How to fix this?</p>\n<p>Instead of using the first available <code>iterator_category</code>, use the minimal <code>iterator_category</code> of all provided iterators:</p>\n<pre><code> using iterator_category = std::common_type_t<typename std::iterator_traits<IT>::iterator_category...>;\n // this works since more powerful iterator categories inherit from less powerful ones\n // thus the common ancestor tag is supported by all\n</code></pre>\n<p>But wait a moment...</p>\n<p>Remember when I said that the standard mandates strong constraints for certain iterator categories?</p>\n<p>Well, if an iterator wants to be categorized as forward iterator or above, among <a href=\"https://en.cppreference.com/w/cpp/named_req/ForwardIterator\" rel=\"nofollow noreferrer\">other constraints</a> the following must be true:</p>\n<blockquote>\n<p><code>reference</code> must be either <code>value_type&</code> or <code>const value_type&</code>.</p>\n</blockquote>\n<p>Based on this constraint, the most powerful legal <code>iterator_category</code> for this iterator is actually <code>std::input_iterator_tag</code>. (Which in turn means that <code>std::sort</code> won't work at all, as it requires random access iterators.)</p>\n<blockquote>\n<p>There are arguments to be made why the standard is overly restrictive with this clause, but as of C++17 these are the given requirements and shall not be violated. This is why <code>boost::zip_iterator</code> cannot be used with algorithms like <code>std::sort</code>: There is no legally possible way to meet all requirements under all circumstances.</p>\n<p>Fun fact: <code>std::vector<bool>::iterator</code> has the same issue.</p>\n</blockquote>\n<h1>Constant pain</h1>\n<p>There are some issues with regard to <code>const</code>ness.</p>\n<pre><code>auto a = std::vector<int>{ 1, 2, 3, 4 };\nauto b = std::vector<std::string>{ "A", "B", "C", "D" };\nconst auto c = b;\n\nauto zip_one = Zip(a, b);\nauto zip_two = Zip(a, c);\n\nfor(auto&& value : zip_one) std::cout << value << "\\n"; // this works\nfor(auto&& value : zip_two) std::cout << value << "\\n"; // this fails to compile\n</code></pre>\n<p>What happened? <code>c</code> is an exact copy of <code>b</code> - the only difference being a small <code>const</code>. But the consequences are dire: Compilation failure!</p>\n<p>What changed? Since <code>c</code> is constant, <code>c.begin()</code> and <code>c.end()</code> only return <code>const_iterator</code>s, since elements within should also not change.</p>\n<p>How to fix? The culprit in this case is the definition for <code>ZipIter::reference</code>:</p>\n<pre><code> using reference = ZipRef<typename std::iterator_traits<IT>::value_type ...>;\n</code></pre>\n<p>Using a different definition that takes into account the actual iterator <code>reference</code> fixes this:</p>\n<pre><code> using reference = ZipRef<std::remove_reference_t<typename std::iterator_traits<IT>::reference>...>;\n</code></pre>\n<p>But the trouble with <code>const</code> doesn't end here: Once any type of the template type parameters of <code>ZipRef</code> is <code>const</code>, some operations of <code>ZipRef</code> won't work anymore: assignment fails (<code>const</code> values cannot be reassigned) and <code>swap</code> fails (same reason). And there is no easy fix for this!</p>\n<h1>To the end of the universe... and beyond!</h1>\n<pre><code>auto a = std::vector<std::string>(10, "A");\nauto b = std::vector<std::string>(2, "C");\n\nauto zip = Zip(a, b);\nstd::distance(zip.begin(), zip.end()); // uh oh\n</code></pre>\n<p>How many zipped elements should <code>zip</code> contain?</p>\n<p>Logically, there should at most be two, as there aren't any values in <code>b</code> to continue any further.</p>\n<p>Instead, the current implementation gives undefined behavior:</p>\n<pre><code>auto endReached = std::next(zip.begin(), 2);\nassert(endReached != zip.end());\n</code></pre>\n<p><code>endReached</code> is the <code>ZipIter</code> pointing just at <code>b.end()</code>, i.e. where the iteration should stop. But the check against <code>zip.end()</code> fails, since not all iterators have yet reached their corresponding end iterator.</p>\n<p>And this is where undefined behavior happens: <code>++endReached</code> advances a past-the-end-iterator, and after that nothing can be trusted anymore.</p>\n<p>How can this be fixed?</p>\n<p>The most common approach is to use a sentinel value as end iterator so that any <code>ZipIter</code> compares <code>true</code> if any (instead of all) of its contained iterators matches the corresponding end iterator.</p>\n<h1>Licensed trouble (or freedom?)</h1>\n<pre><code>// Still unsure about the licence, but something in the line of just providing attribution\n</code></pre>\n<p>When posting the code on this site, you have already released it under the CC-BY-SA 4.0 license. You can of course release it under another license model (you're free to do so as the license holder).</p>\n<h1>Other issues</h1>\n<p>I won't repeat much of <a href=\"/a/231546/75307\">Toby Speight's answer</a>, but some additional notes:</p>\n<ul>\n<li><code>ZipRef::swap</code> is modelled on <code>std::iter_swap</code>, not <code>std::swap</code>. Maybe the name should be adjusted to reflect this?</li>\n<li><code>ZipIter::difference_type</code> has the same issue as <code>ZipIter::reference</code>: It only uses the <code>difference_type</code> of the first iterator. (Usually not much of a deal, since most iterators use <code>std::ptrdiff_t</code>. Still, beware of the edge case!)</li>\n<li><code>ZipRef</code>s <code>operator std::tuple<T...>()</code> is unlikely to work in generic context as intended (conversions are excluded when matching templated arguments, e.g. <code>std::get<1>(zipRef)</code> doesn't work). It works in specialized contexts (<code>void f(std::tuple<std::string, int>); f(zipRef);</code>, but this might cause unexpected issues.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T09:08:47.180",
"Id": "451751",
"Score": "0",
"body": "Impressive: I found the \"const pain\" you noted (and forgot to mention it), but couldn't identify a solution. Thanks for that enlightenment!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:39:43.323",
"Id": "451786",
"Score": "0",
"body": "What about `enabling_if` `std::common_type_t<typename std::iterator_traits<IT>::iterator_category...>` is at least `forward_iterator`? It still violates the overly restrictive standard (which one has to take into account when migrating between different implementation of the STL), but otherwise either the idea or the whole standard-conforming ecosystem should be scrapped..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T17:33:58.880",
"Id": "451860",
"Score": "0",
"body": "@DarioP: From what I understand, there are currently some ongoing proposals to amend the c++ standard to allow for these kinds of proxy iterators. (I'm not quite up to date whether it will make C++20, but if it does, just migrate to C++20 and enjoy.) If you are forced to use C++17 though, either accept the `std::input_iterator_tag`, or violate it at your own risk (pretending to be something you are not will very likely lead to UB)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T20:04:24.563",
"Id": "451902",
"Score": "0",
"body": "I think that C++20 will not update the situation. Eric Niebler's range-v3 has been partially adopted, but Zip is one of the few components that were purposely left out. Let's wait for C++23, I guess."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T23:00:01.080",
"Id": "231570",
"ParentId": "231352",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "231570",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T21:44:53.887",
"Id": "231352",
"Score": "8",
"Tags": [
"c++",
"iterator",
"c++17"
],
"Title": "C++17 zip iterator compatible with std::sort"
}
|
231352
|
<p><strong>Hey there guys, I have just completed an exercise for uni and I would really like some feedback as I'm pretty new to using java. Areas that I could especially use some input in this instance: readability of the code, the names of the variables, the javaDoc comments, correct use of error statements AND MOST IMPORTANTLY the not3TimesHigher method, which took me ages to do, I'm still not sure whether this is the best way to do it.</strong></p>
<p><strong>A warning before anybody writes anything here:
Please do not suggest any overly complex updates to my code, I'm a beginner and I'm required to work within those limitations.</strong></p>
<p><strong>Anyway here is the problem sheet for reference:</strong></p>
<p>A company stores the salaries of its employees in an ArrayList
allSalaries, an ArrayList of arrays of type double. Each entry in allSalaries is an array of the 12
salaries of an employee for the 12 months of the year.</p>
<p>Write a class Salaries with the constructor
• public Salaries() having no parameters to create an initially empty ArrayList.
And write the following methods:</p>
<p>• public void add(double[] employeeSalaries) to add the salaries of one employee to the field variable allSalaries.</p>
<p>• The method public static double average(double[] employeeSalaries) computes the average
salary for an employee. Note that any 0 entry should be disregarded, since a 0 means that the employee was
not employed in that particular month. For instance, the average of {1000,1000,2000,2000,0,0,0,0,0,0,0,0}
should be 1500.0 as the sum of the four non-zero values divided by 4.
If all values in the annualSalaries array are zero, the method should throw an IllegalArgumentException.</p>
<p>• The method public ArrayList averageSalaries() generates an ArrayList storing the average salaries of all employees that have at least one non-zero monthly salary. Make use of the method
average.
Hint: You need to catch possible exceptions thrown by the method average.</p>
<p>• The method public boolean not3TimesHigher() checks whether for each employee with at least one
non-zero monthly salary their average salary is not higher than three times the overall average salary of
the other employees. That is, you need here the average of the averages.</p>
<pre><code>import java.util.ArrayList;
public class Salaries {
private ArrayList<double[]> allSalaries;
public Salaries() {
allSalaries = new ArrayList<double[]>();
}
public void add(double[] employeeSalaries) {
allSalaries.add(employeeSalaries);
}
/**
* @param takes an array of doubles; each index of the array represents
* the earnings of an employee for that particular month.
*
* @return average salary of an employee.
*/
public static double average(double[] employeeSalaries) {
double totalSalary = 0;
int totalMonths = 0;
for (int i=0; i<employeeSalaries.length; i++) {
if (employeeSalaries[i] > 0) {
totalSalary += employeeSalaries[i];
totalMonths++;
}
if (totalSalary == 0) {
throw new IllegalArgumentException("This chump didn't earn any money!");
}
}
return totalSalary / totalMonths;
}
/**
* Method traverses allSalaries calculating the average salary for each employee
* and appending it to a newly a instantiated ArrayList.
*
* @return ArrayList containing average salaries for all employees with at least one
* monthly salary above 0.
*/
public ArrayList<Double> averageSalaries() {
ArrayList<Double> averageSalaries = new ArrayList<Double>();
try {
for (int i=0; i<allSalaries.size(); i++) {
double avgEmployeeSalary = average(allSalaries.get(i));
averageSalaries.add(avgEmployeeSalary);
}
} catch (IllegalArgumentException e) {
System.out.println("Warning, attempted to add employee with zero earnings.");
}
return averageSalaries;
}
/**
* Method creates a new instance of averageSalaries which it then traverses,
* comparing each index (average employee salary) with the total average value
* of all other indexes * 3.
*
* @return false if any employee average salary is greater than the average of
* all other employee salaries * 3, true otherwise.
*/
public boolean not3TimesHigher() {
ArrayList<Double> avgS = averageSalaries();
for (int i=0; i<avgS.size(); i++) {
double employee = avgS.get(i);
avgS.remove(i);
double[] allOtherEmployees = new double[avgS.size()];
for (int j=0; j<allOtherEmployees.length; j++) {
allOtherEmployees[j] = avgS.get(j);
}
if (employee > (average(allOtherEmployees) * 3)) {
return false;
}
} return true;
}
public static void main(String[] args) {
//double[] bowie = {2456, 1330, 0, 5470};
double[] paul = {5, 8, 4, 6};
double[] ringo = {5, 7, 4, 6};
double[] john = {0, 0, 0, 0};
double[] george = {3, 7, 9, 8};
Salaries a = new Salaries();
//a.add(bowie);
a.add(paul);
//a.add(john);
a.add(ringo);
a.add(george);
//System.out.println(Salaries.average(john));
System.out.println(a.averageSalaries());
System.out.println(a.not3TimesHigher());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>I think you did a good job on this exercise.\nTherefore I have only a few points to mention:</p>\n\n<h1>Correctness</h1>\n\n<p>I think your method <code>averageSalaries()</code> is not correct, since it returns after the first exception is caught and no other input rows are processed.\nAs I understand the exercise the \"unpayed\" entries should be ignored and all other entries should be processed. \nThis means, the code should be like this:</p>\n\n<pre><code>public ArrayList<Double> averageSalaries() {\n ArrayList<Double> averageSalaries = new ArrayList<Double>();\n\n for (int i=0; i<allSalaries.size(); i++) {\n try {\n double avgEmployeeSalary = average(allSalaries.get(i));\n averageSalaries.add(avgEmployeeSalary);\n } catch (IllegalArgumentException e) {\n System.out.println(\"Warning, attempted to add employee with zero earnings.\");\n }\n }\n return averageSalaries;\n}\n</code></pre>\n\n<h1>Readability</h1>\n\n<h2>Code Format</h2>\n\n<p>Use an <em>Integrated Development Environment</em> (like <code>eclipse</code>, <code>intelliJ</code> <code>NetBeans</code> or alike (if you don't do already) and use it's <em>auto formatter</em> feature.</p>\n\n<h2>Naming</h2>\n\n<h3>Make your names as specific as possible.</h3>\n\n<p>In your method <code>average()</code> you have a variable <code>totalMonths</code>. \nBy this name I'd expect the <em>total number of month processed</em>, but it contains the <em>count of moth with non zero payment</em>.\nIn my view <code>monthsWithPayment</code> would be a better name.</p>\n\n<h3>avoid single letter names.</h3>\n\n<p>In your <code>main()</code> method the variable to refer to the <code>Salaries</code> object is named <code>a</code>. \nFinding good names is the hardest part in programming.\nSo you should not give away a chance to practice good naming even it it is only a test methods for your exercise solution.</p>\n\n<h2>for loop</h2>\n\n<p>At many if not at all places the \"for each\" form of the <code>for</code> loop would improve readability:</p>\n\n<pre><code>for (double[] emploeeMonthlyPayments : allSalaries) {\n try {\n double avgEmployeeSalary = average(emploeeMonthlyPayments);\n averageSalaries.add(avgEmployeeSalary);\n // ...\n</code></pre>\n\n<hr>\n\n<h1>Off Topic</h1>\n\n<p>I think this exercise is not a good one:</p>\n\n<h2>naming</h2>\n\n<p>The exercise requests you to write a method named <code>not3TimesHigher</code> returning a <code>boolean</code> value.\nIn my view this name is bad in thee ways:</p>\n\n<ul>\n<li>according to the (Java Code Conventions)[ <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html]\" rel=\"nofollow noreferrer\">https://www.oracle.com/technetwork/java/codeconventions-135099.html]</a> names of variables of type <code>boolean</code> and methods returning a <code>boolean</code> should start with <em>is</em>, <em>has</em>, <em>can</em> or alike.</li>\n<li><p>names of variables of type <code>boolean</code> and methods returning a <code>boolean</code> should express <em>positive</em> conditions.</p></li>\n<li><p>when using digits in names they should be the last part in the name</p></li>\n</ul>\n\n<p>Therefore name of this method had better been <code>isLessThanAverageTimes3()</code></p>\n\n<p>Referring to the same (Java Code Conventions)[ <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html]\" rel=\"nofollow noreferrer\">https://www.oracle.com/technetwork/java/codeconventions-135099.html]</a> names of methods should start with a <em>verb</em>.\nBut the method names requested in this exercise (<code>average()</code>, <code>averageSalaries()</code>) are <em>nouns</em>.\nThey should better be <code>calculateAverage()</code>, <code>calculateAverageSalaries()</code>.</p>\n\n<h1>use of the <code>static</code> key word</h1>\n\n<p>The use of the <code>static</code> key word has more drawbacks than advantages.\nIt should be used with care and for a good reason. \nI cannot see such a \"good reason\" for the use of the <code>static</code> key word in the method <code>average()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T01:09:41.770",
"Id": "451218",
"Score": "0",
"body": "Small note, \"average\" [can be used as a verb as well as a noun](https://www.merriam-webster.com/dictionary/average)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T11:15:24.570",
"Id": "451250",
"Score": "0",
"body": "@cbojar in that case the readability should be increased by making the identifier name unambiguous. Also: for me as a non native english speaker *to average* would mean: *make all the same average value* and thus imply a *state change* in the `Salleries` object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T14:44:40.223",
"Id": "451269",
"Score": "1",
"body": "Thanks @Timothy Truckle, I really appreciate it. You make some really good points about the not3TimesHigher exercise, I think the worksheet itself was rushed, the version I posted was actually updated from a previous worksheet with more errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T18:45:01.530",
"Id": "451289",
"Score": "0",
"body": "@TimothyTruckle I think it really depends on the team. If they frequently refer to averaging the salaries, using average as a verb method name is fine. If instead they talk about calculating an average, then calculateAverage is more appropriate, even if more verbose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T20:41:12.440",
"Id": "451299",
"Score": "0",
"body": "@cbojar what about new team members who are not (yet) familiar with your use of the wording?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T02:43:14.220",
"Id": "451310",
"Score": "0",
"body": "@TimothyTruckle The same way they learn anything else when joining a team: through documentation, training, reading the code, and interacting with their teammates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:27:37.183",
"Id": "451352",
"Score": "0",
"body": "@cbojar If I need to lookup the meaning of an identifier in any documentation the code is the opposite of *readable*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T02:01:44.717",
"Id": "451421",
"Score": "0",
"body": "@TimothyTruckle I would say it is much like checking a translation dictionary when learming a language. To continue the metaphor, a new team member would learn the common terms much like a language learner would in an immersive language environment. The newcomer picks up more and more advanced topics as they work. Code shouldn't be incomprehensible, but only writing for the lowest level of understanding would handicap the team and their ability to create higher level abstractions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T19:28:01.120",
"Id": "451542",
"Score": "0",
"body": "@cbojar you can dig for more excuses but the need to lookup the exact meaning of an identifier is a **no go** for readable code."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T22:53:11.453",
"Id": "231355",
"ParentId": "231353",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T21:48:49.403",
"Id": "231353",
"Score": "2",
"Tags": [
"java",
"beginner",
"object-oriented",
"homework"
],
"Title": "Salaries exercise"
}
|
231353
|
<p>Hello and thanks for clicking!</p>
<p>I'm currently studying the relationship between a database and user objects. This is a very simple program and the "database" itself is a dictionary. This will be used in a website (after studying a lot, of course, as I am fairly new to the "programming world", if you will), but I've abstracted a lot of details (e.g. adding the inputs directly into Python). The code became a bit... unnecessary at times, because of that - e.g. constantly doing checks to see if the inputs are correctly formatted.</p>
<p>It also has a password generator... probably not the best, but works for me right now.</p>
<p>Here is the code:</p>
<pre class="lang-py prettyprint-override"><code>from random import randint
lower_char = ["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"]
upper_char = [let.upper() for let in lower_char]
special_char = ['!', '@', '#', '$', "%", "&", "*", "(", ")", "-"]
number_char = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
all_char = [lower_char, upper_char, special_char, number_char]
user_db = {}
class User():
def __init__(self, username, password, random):
# Check if user already exists - self.username becomes None if so
self.username = username if username not in user_db else print("Username already exists!")
# Case random = true
if random and not password and self.username != None:
while True:
try:
num_of_let = int(input("Please type the number of characters in your password: [has to be between 8 and 40 characters]\n"))
if num_of_let >= 8 and num_of_let <= 40:
break
else:
print("Password has to be between 8 and 40 characters!")
except ValueError:
print("Integers only!")
self.password = self.createRPassword(num_of_let)
# Case random = false
else:
self.password = password
if self.username != None:
user_db.update({self.username.lower(): self.password})
def createRPassword(self, num_of_let):
"""Creates (pseudo) random password with given number of letters"""
pw = []
for _ in range(num_of_let):
current_list = all_char[randint(0, 3)]
pw.append(current_list[randint(0, len(current_list)-1)])
pw = "".join(str(let) for let in pw)
print(f"Okay! Your new password is\n{pw}")
return hash(pw)
def validateCredentials(self, username, password):
if username in user_db:
if password == user_db[username]:
print("Success!")
return ("Success!")
else:
print("Wrong Password!")
return ("Wrong Password!")
else:
print("Username does not exist!")
return ("Username does not exist!")
if __name__ == "__main__":
while True:
create_or_login = input("[Create] a new user or [login]?\n").lower()
if create_or_login == "create":
new_username = input("Please type a username to create it: [has to be between 3 and 12 characters]\n")
is_random = False if input("Random password? [y] [n]\n") == 'n' else True
new_password = hash(input("Please type a new password: [has to be between 8 and 40 characters]\n")) if not is_random else False
user = User(new_username, new_password, is_random) if len(new_username) >= 3 and len(new_username) <= 12 else print("Username is too short")
elif create_or_login == "login":
username = input("Username:\n").lower()
password = hash(input("Password:\n"))
user.validateCredentials(username, password)
wanna = input("Wanna stop? [y] [n]\n").lower()
if wanna == 'y':
break
elif wanna == 'n':
print(f"Current db: {user_db}")
pass
else:
print("Really?")
</code></pre>
<p>I have a few questions, though: </p>
<ol>
<li>How to securely handle user information? </li>
</ol>
<p>For the security, I've read about 'salting' the hash and, of course, using different hashing algorithms, but I'll use the pre-built one from Python, for testing purposes. I can imagine that securing the username is not AS important as the password... but how do I store these credentials in the system at all? Should it be stored as it currently is - user and hashed password?</p>
<p>Also, do I hash the password <strong>BEFORE</strong> sending it to the script that will handle it (in this case, Python) and, then, send it to the database? Or does the password go directly to the script and then gets hashed? (Maybe we can double hash it :) )</p>
<p>[As an example for the above, let's say there is a login website. Should the password be hashed before the POST request or after?]</p>
<ol start="2">
<li>How should the User object be saved in the database?</li>
</ol>
<p>Should it have things like blocked status that gets activated if user tried to login many times with the wrong password? Other suggestions are welcomed, but I guess it depends on the usage of the user 'object'.</p>
<p>A simple implementation would be, in the case of this example, to have something like this:</p>
<pre class="lang-py prettyprint-override"><code>user_db = {example_user: {password: hashedpw, blocked: False, tried: 0}}
</code></pre>
<ol start="3">
<li>Should I be doing all this logic inside <code>__init__</code>?</li>
</ol>
<p>Pretty straight-forward question... should I only initialize the variables inside <strong>init</strong> and do the rest of the logic elsewhere? It does work as it is, but not sure if it is the best way to do it.</p>
<ol start="4">
<li>Should I use more functions for better readability?</li>
</ol>
<p>An example of this would be saving the user object in the database... should that be a function?</p>
<p>I do know there are, most likely, a lot of code improvements to be made. I came back very recently to Python and do not remember some of the best practices (and I was never a professional as well, as you probably can see).</p>
<p>I will happily accept any code improvements, <strong>but please focus on the main logic</strong>, instead of the small little improvements. I've seen that Python 3.8 gave us the awesome <code>print(f'{var=}')</code> functionality, which technically could be used in my program, but not that important ;)</p>
<p>Also, sorry if this is not the right place to ask this question or if there are any issues with the question at all. I will modify it as needed :)</p>
<p>Thank you for your attention!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:59:27.400",
"Id": "451361",
"Score": "1",
"body": "How important is security? Because if this is production software to protect consumer data, you don't want to use python's build in hash algorithm, but instead grab a module offering cryptographically secure hash functions. You'll also want to use a salt first. Also, python's `random` module is NOT random enough for secure applications. Use [secrets](https://docs.python.org/3/library/secrets.html) instead. And take your code to [security](https://security.stackexchange.com) when you're done here. (They'll probably just tell you to use a reliable library, though.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:01:38.553",
"Id": "451514",
"Score": "0",
"body": "@Gloweye In this case, this is a simulation (hence why I'm using the hash algorithm and randint from random module). But security will be **really** important, once I start to make and deploy my project. I did read about salt, but will have to dig into encryption and hashing, first, then I'll check about salting (as I am unsure on how to properly do it, right now). Thanks for the library recommendation, did not know about it until now :) I'll definitely check and study it! Also... did not know there was a security area in SE... it will be super helpful! Thank you so much for your help!"
}
] |
[
{
"body": "<p>A few notes...</p>\n\n<ul>\n<li><strong>How to securely handle user information?</strong></li>\n</ul>\n\n<p>You should hash after you encrypt however you may be better using HMAC which are hash MACS.</p>\n\n<ul>\n<li><strong>How should the User class be saved in the database?</strong></li>\n</ul>\n\n<p>You save the variable/user info in the DB not the class itself. </p>\n\n<ul>\n<li><strong>Should I be doing all this logic inside __init__?</strong></li>\n</ul>\n\n<p>You can but it may be easier to compare your conditions in a function to see if the condition from a user input.</p>\n\n<ul>\n<li><strong>Should I use more functions for better readability?</strong></li>\n</ul>\n\n<p>Don't make your code longer unnecessarily, The code below is an example of a simple version of what your trying to achieve from the main logic aspect. I have put things such as the attempt effort and db search into 1 function. </p>\n\n<pre><code>import string\n\n\nlower_char = string.ascii_lowercase\nupper_char = string.ascii_uppercase\nspecial_char = ['!', '@', '#', '$', \"%\", \"&\", \"*\", \"(\", \")\", \"-\"]\nnumber_char = string.digits\nall_char = [lower_char, upper_char, special_char, number_char]\nuser_db = 'test' # Your DB in here\nuser_pwd = 'password' # Your DB in here\nprint(all_char)\n\n\n#class User():\n\nclass User:\n def __init__(self, name, pwd):\n self.name = name\n self.pwd = pwd\n\nuser = User\n\ndef run():\n while True:\n attempts = 3\n while attempts >= 0:\n try:\n q1 = input('Username:> ')\n if q1 == user_db: # if q1 in user_db\n q2 = input('Password:> ')\n # search for value against q1 key in user_db\n if q2 == user_pwd: # id q2 in user_db\n print('DO SOMETHING ELSE') # do something else. Other function\n exit()\n else:\n print('Incorrect password')\n else:\n print('Username invalid')\n attempts -= 1\n except ValueError:\n pass\n else:\n print('Too many failed attempts')\n break\n\nrun()\n</code></pre>\n\n<p>This is the output. At the top I printed out the string.ascii variables so you don't have to type out each letter and number:</p>\n\n<pre><code>['abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ['\n!', '@', '#', '$', '%', '&', '*', '(', ')', '-'], '0123456789']\nUsername:> test\nPassword:> password\nDO SOMETHING ELSE\n</code></pre>\n\n<p>and when you put in the wrong user or password. You will need to add arguments to check your db keys as names and values assigned to them for the password:</p>\n\n<pre><code>Username:> d\nUsername invalid\nUsername:> f\nUsername invalid\nUsername:> test\nPassword:> s\nIncorrect password\nUsername:> j\nUsername invalid\nUsername:> wksd\nUsername invalid\nToo many failed attempts\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T01:40:38.197",
"Id": "451219",
"Score": "0",
"body": "Awesome, thank you so much! Also... I edited the question... I meant saving each user object. That question is, essentially, if I should insert only information like username and password, or if I should store things like the attempt count. Also, same question, I should store the hashed password in the database, correct? One other question, regarding the encryption... just so this does not get super long, do you have any recommendations on links to understand that type of data encryption (and if it’s customizable - depends on environment, etc). Thank you again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T02:02:31.690",
"Id": "451222",
"Score": "0",
"body": "https://en.wikipedia.org/wiki/HMAC for the encryption. You want to read up on SQL lite for database's, they are really helpful. You can use your db to store anything you want."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T01:21:06.100",
"Id": "231362",
"ParentId": "231357",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231362",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T23:11:16.340",
"Id": "231357",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"security",
"database"
],
"Title": "Simple User and Database Relationship"
}
|
231357
|
<p>I wrote a function to generate a complicated version of the pascal triangle. The generated triangle should look like that:</p>
<pre class="lang-bsh prettyprint-override"><code>┌─────────┬───┬───┬────┬────┬────┬────┬────┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │
├─────────┼───┼───┼────┼────┼────┼────┼────┼───┼───┤
│ 0 │ 1 │ │ │ │ │ │ │ │ │
│ 1 │ 1 │ 1 │ 1 │ │ │ │ │ │ │
│ 2 │ 1 │ 2 │ 3 │ 2 │ 1 │ │ │ │ │
│ 3 │ 1 │ 3 │ 6 │ 7 │ 6 │ 3 │ 1 │ │ │
│ 4 │ 1 │ 4 │ 10 │ 16 │ 19 │ 13 │ 10 │ 4 │ 1 │
└─────────┴───┴───┴────┴────┴────┴────┴────┴───┴───┘
</code></pre>
<p>My implementation is like that</p>
<pre><code>function createTriangle (n) {
// initialize the holding matrix
let matrix = [];
// iterate over the matrix rows, and for each row construct a new array of row number + 1
for (let row = 0; row < n; row++) {
matrix[row] = new Array(row+1);
// iterate over each row and check conditions
for (let col = 0; col <= 2*row; col++) {
if ((col === 0 && row >= 0) || (col === 2 * row)) {
matrix[row][col] = 1;
// first case
} else if(col === row && col === 1){
matrix[row][col] = 1;
// second case ;
} else if(row > col && matrix[row][col-1]=== 1 ) {
matrix[row][col] =
1 + matrix[row-1][col];
// third case
} else if(row > col && matrix[row][col-1]!== 1 ) {
matrix[row][col] =
matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// fourth case
} else if((row === col && (matrix[row][col-1] !== 1))) {
matrix[row][col] =
matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// fifth case
// if the col number is even, add only the previous 2 elements in the previous row
} else if(row < col && col % 2 === 0){
matrix[row][col] = matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// sixth case
// if the col number is odd add the previous 3 elements in the previous row
} else if(row < col && col % 2 === 1){
matrix[row][col] = matrix[row-1][col-2] + matrix[row-1][col-1];
}
}
}
return matrix;
}
console.table(createTriangle(5))
</code></pre>
<p>I feel that my code is a bit confusing. In addition, there is a bug on matrix[4, 5] it should be 16,but it is 13?? Could anyone advise if there is a more refactored elegant solution? Appreciate your time and help.</p>
<p><strong>Edit</strong>
The algorithm should generate a matrix that have number of columns twice number of rows. The elements before the element at matrix[row][col] <strong>where col = row</strong> should be the same but reversed in a desc. order. for example, matrix[4,4] => [1,4,10,16,19,16,10,4,1]. element at matrix[4,4] <strong>19</strong> should be equal to 6+7+6</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T20:03:12.430",
"Id": "451294",
"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)*. The changes you made were explicitly mentioned in an answer, so you can't make them in this post."
}
] |
[
{
"body": "<p>You are not properly calculating the pascal triangle. Here is my solution, in this code I take advantage of the function <code>.splice()</code> to modify the content of every row. You know that the outter elements of each row are 1s and in between you make the calculations of the sum of the top \"root elements\", and just like that you get the Pascal's Triangle.</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>function pascalTriangle(level) {\n let matrix = [[1]];\n\n for (let row = 1; row < level; row++) {\n matrix.push([1, 1]);\n for (let col = 1; col < row; col++) {\n matrix[row].splice(col, 0, matrix[row - 1][col - 1] + matrix[row - 1][col]);\n }\n }\n\n return matrix;\n}\n\nconsole.log(pascalTriangle(7));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<pre><code>┌─────────┬───┬───┬────┬────┬────┬───┬───┐\n│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │\n├─────────┼───┼───┼────┼────┼────┼───┼───┤\n│ 0 │ 1 │ │ │ │ │ │ │\n│ 1 │ 1 │ 1 │ │ │ │ │ │\n│ 2 │ 1 │ 2 │ 1 │ │ │ │ │\n│ 3 │ 1 │ 3 │ 3 │ 1 │ │ │ │\n│ 4 │ 1 │ 4 │ 6 │ 4 │ 1 │ │ │\n│ 5 │ 1 │ 5 │ 10 │ 10 │ 5 │ 1 │ │\n│ 6 │ 1 │ 6 │ 15 │ 20 │ 15 │ 6 │ 1 │\n└─────────┴───┴───┴────┴────┴────┴───┴───┘\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T07:32:33.513",
"Id": "451231",
"Score": "2",
"body": "Since you don't need the second 1 for calculating the inner cells, the code may become clearer if you first `matrix.push([1])`, then `matrix[row].push(matrix[row - 1][col - 1] + matrix[row - 1][col])` in the loop and finally `matrix[row].push(1)`. Thereby you avoid the `splice` function and the extra `0` in that function call. It's also more efficient since the last `1` does not have to be moved in the array so often. Sure, the code would become one line longer, but it uses fewer incredients and only appends, which in my view is easier to understand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T05:06:14.593",
"Id": "231365",
"ParentId": "231359",
"Score": "4"
}
},
{
"body": "<h2>Pascals Triangle?</h2>\n\n<p>The output of your code is not <a href=\"https://en.wikipedia.org/wiki/Pascal%27s_triangle\" rel=\"nofollow noreferrer\">Pascals triangle</a> (even if the bug? is ignored). </p>\n\n<p>As you only present one example with the statement <em>\"The generated triangle should look like that:\"</em>, that contains what you state is a bug (erroneous? 13) </p>\n\n<p>What the rules defining the correct result are is anyone's guess. I will address your code as is and ignore the bug or not bug.</p>\n\n<h2>Style and logic</h2>\n\n<ul>\n<li>Don't add comments that state the obvious. Eg <code>// first case</code>, <code>// second case</code> and so on. </li>\n<li><p>Don't add comments that are just an alternative representation of the code Eg <code>// if the col number is even, add only the previous 2 elements in the previous row</code>. This just add another line of maintainable content, which can be dangerous because if you change the code there is nothing forcing you to change the comment. Even worse than redundant comments are comments that are in conflict with the actual logic</p></li>\n<li><p>Use <code>const</code> for variables that do not change. Eg <code>let matrix = [];</code> can be <code>const matrix = []</code></p></li>\n<li><p>Don't repeat code. </p>\n\n<ul>\n<li>You calculate <code>row - 1</code> (and the like) many times</li>\n<li>You index <code>matrix[row]</code> and <code>matrix[row-1]</code> many times</li>\n</ul></li>\n<li><p>You are repeating logic. Eg the second last statement <code>else if (j < i && i % 2 === 0) {</code> is followed by <code>else if (j < i && i % 2 === 1) {</code> but you know that <code>i % 2 === 1</code> as the previous statement determined its value. </p></li>\n<li><p>Don't calculate known data. Eg the very last <code>else if</code> statement can just be a <code>else</code> because you must add to the array each iteration, the last statement MUST pass.</p></li>\n</ul>\n\n<p>There is no advantage using let in for loops when performance is a concern. Try to favor function scoped variables and declare them at the top of the function.</p>\n\n<h2>Rewrite (cleanup)</h2>\n\n<p>The snippets below is the same logic you used, just cleaned up using the points above </p>\n\n<pre><code>function createTriangle(n) {\n var i, j;\n const matrix = [];\n for (j = 0; j < n; j++) {\n const prevRow = matrix[j - 1], row = []; \n matrix.push(row);\n for (i = 0; i <= 2 * j; i++) {\n if ((i === 0 && j >= 0 || i === 2 * j) || (i === j && i === 1)) {\n row[i] = 1;\n } else {\n const r1 = row[i - 1], pr = prevRow[i], pr12 = prevRow[i - 1] + prevRow[i - 2];\n if (j > i && r1 === 1) {\n row[i] = 1 + pr;\n } else if (j > i && r1 !== 1) {\n row[i] = pr + pr12;\n } else if (j === i && r1 !== 1) {\n row[i] = pr + pr12;\n } else if (j < i && i % 2 === 0) {\n row[i] = pr + pr12;\n } else {\n row[i] = pr12;\n }\n }\n }\n }\n return matrix;\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>function createTriangle(n) {\n var i, j, row;\n const matrix = [];\n for (j = 0; j < n; j++) {\n const prevRow = row; \n matrix.push(row = []);\n for (i = 0; i <= 2 * j; i++) {\n if ((i === 0 && j >= 0 || i === 2 * j) || (i === j && i === 1)) {\n row[i] = 1;\n } else {\n const r1 = row[i - 1], pr = prevRow[i], pr12 = prevRow[i - 1] + prevRow[i - 2];\n if (j > i && r1 === 1) { row[i] = 1 + pr }\n else if (j > i && r1 !== 1) { row[i] = pr + pr12 }\n else if (j === i && r1 !== 1) { row[i] = pr + pr12 }\n else if (j < i && i % 2 === 0) { row[i] = pr + pr12 }\n else { row[i] = pr12 }\n }\n }\n }\n return matrix;\n}\n</code></pre>\n\n<h2>Pascals triangle example</h2>\n\n<p>As an example pascals triangle can be calculated as follows. I would assume that the rules you use are similar and thus it is likely that your triangle can be calculated using a modification of this method that does not require indexing into the previous row.</p>\n\n<pre><code>function pascalsTriangle(rows) {\n var i, j, row, p, result = [[1]];\n for (i = 1; i <= rows; i++) {\n result.push(row = [p = 1]);\n for (j = 1; j <= i; j++) { row.push(p = p * (i - j + 1) / j) }\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T16:22:23.330",
"Id": "451274",
"Score": "0",
"body": "Thanks @Bilndman67 your feedback were really helpful. I agree with you that this is not a pascal isosceles triangle with the number of cols = number of the rows. It should instead have the number of col = twice the number of col. Also, there is a pattern the numbers after matrix[row][col] where (row=col) is the same numbers but reversed in a desc order (1,3,6,7,6,3,1). This problem I am trying to solve is from the Introduction to algorithms-A creative approach textbook - p(32, 2.11)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T12:00:23.010",
"Id": "231376",
"ParentId": "231359",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T00:05:50.477",
"Id": "231359",
"Score": "4",
"Tags": [
"javascript",
"performance",
"algorithm"
],
"Title": "complicated pascal triangle using JavaScript"
}
|
231359
|
<p>I'm brand new and been going through some beginner code problems on checkIO. I finished this one today and am posting because I'm sure there is a much more elegant way to accomplish this, and I think this particular problem has a lot of useful applications. I would like to know what are the 'clean and efficient' ways to do it, or maybe what built-ins I haven't learned yet that I should explore. My version seems pretty ugly. Thanks!</p>
<p>Problem: take a tuple of phrases, anytime the word 'right' appears, replace it with 'left'. Create a new string combining all the phrases separated with a comma.</p>
<pre><code>def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
phrases = list(phrases)
newstr = ''
for j, phrase in enumerate(phrases):
if 'right' in phrase:
mod = dict(enumerate(phrase))
for key in mod:
if mod[key] == 'r' and mod[key+4] == 't':
i = key
mod[i] = 'l'
mod[i+1] = 'e'
mod[i+2] = 'f'
mod[i+3] = 't'
mod[i+4] = ''
switch = (list(mod.values()))
phrase = ''.join(switch)
if j == (len(phrases) - 1) or len(phrases) == 1:
newstr += phrase
else:
newstr += phrase + ','
else:
if j == (len(phrases) - 1) or len(phrases) == 1:
newstr += phrase
else:
newstr += phrase + ','
return newstr
test1 = ("bright aright", "ok", "brightness wright",)
test2 = ("lorem","ipsum","dolor", "fright", "nec","pellentesque","eu",
"pretium","quis","sem","nulla","consequat","massa","quis",)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T09:32:18.127",
"Id": "451243",
"Score": "0",
"body": "Try your code on test3=(“crash”,)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T16:36:40.693",
"Id": "451275",
"Score": "0",
"body": "It returned \"crash\". I was expecting it to fail. Trying to find what you were getting at I did see another error my code would introduce, if a a five letter sub-string begins with `r` and ends with `t` that is not the word right, it would modify that too. That's not good. What did you see about the test `(\"crash\",)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T16:39:41.290",
"Id": "451277",
"Score": "0",
"body": "sorry, I had missed a line in your code. Try “rightcrash”."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T16:41:59.273",
"Id": "451278",
"Score": "1",
"body": "Aha, I kind of thought that's what you were getting at, lucky guess on my part. I see now. `KeyError: 10`. Originally, I had a break statement so it would pop out after it found the word, but then it would miss another instance of 'right' in the phrase if there was one. I'm going to play around with a fix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T16:56:21.503",
"Id": "451281",
"Score": "0",
"body": "I think I got it, I added a `try` statement after for key and before the `if` statement: `try:\n mod[key] == 'r' and mod[key+4] == 't'\n except KeyError:\n break`"
}
] |
[
{
"body": "<p>Welcome to code review, good job using a docstring and trying to make your code readable.</p>\n\n<ul>\n<li><p><strong>Space after a comma:</strong> </p>\n\n<p><code>test2 = (\"lorem\",\"ipsum\",\"dolor\", \"fright\", \"nec\",\"pellentesque\",\"eu\",\n\"pretium\",\"quis\",\"sem\",\"nulla\",\"consequat\",\"massa\",\"quis\",)</code></p>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP0008</a> which I recommend checking for being the official Python style guide: a space should be left after a comma for readability.</p>\n\n<p><strong>Which should look like:</strong></p>\n\n<p><code>test2 = ('lorem', 'ipsum', ...)</code></p></li>\n<li><strong>Use descriptive names:</strong> names like <code>left_join()</code> <code>newstr</code> <code>j</code> are not describing the objects they represent ex: your function name can be <code>def replace_word(words, word, new_word):</code> </li>\n<li><p><strong>Type hints:</strong> You may use type hints to indicate what are the inputs and outputs in the following way: </p>\n\n<p><code>def your_function_name(phrases: tuple) -> str:</code></p></li>\n<li><p><strong>Docstrings:</strong> Good job using a docstring for your function, however the description is not very clear here's a better description and btw docstrings should indicate what the input and the output is (what the function parameters are and what it returns):</p>\n\n<pre><code>def your_function_name(phrases: tuple, old_word: str, new_word: str) -> str:\n \"\"\"\n Replace the old_word by the new_word if found in phrases.\n Args:\n phrases: Tuple of words.\n old_word: The word to replace.\n new_word: The replacement.\n Return:\n Joined string after replacements.\n \"\"\"\n</code></pre></li>\n<li><p><strong><code>str.replace()</code> and <code>str.join()</code></strong> You can use the <code>replace</code> method to achieve the same results in a shorter code and since you're familiar with <code>join()</code>:</p>\n\n<p><strong>Instead of doing this for every letter in every word:</strong></p>\n\n<pre><code>else:\n newstr += phrase + ','\n</code></pre>\n\n<p><strong>You can do:</strong></p>\n\n<pre><code>', '.join(words)\n</code></pre>\n\n<p><strong>Code might look like:</strong></p>\n\n<p>And Note: You usually wouldn't be creating a function for such a simple task but use <code>replace()</code> and <code>join()</code> directly, I'm creating a function just for the sake of the example.</p>\n\n<pre><code>def replace_word(phrases: tuple, old_word: str, new_word: str) -> str:\n \"\"\"\n Replace the old_word by the new_word if found in phrases.\n Args:\n phrases: Tuple of words.\n old_word: The word to replace.\n new_word: The replacement.\n Return:\n Joined string after replacements.\n \"\"\"\n return ', '.join(word.replace(old_word, new_word) for word in phrases)\n\n\nif __name__ == '__main__': \n test1 = (\"bright aright\", \"ok\", \"brightness wright\",)\n test2 = (\"lorem\",\"ipsum\",\"dolor\", \"fright\", \"nec\",\"pellentesque\",\"eu\",\n \"pretium\",\"quis\",\"sem\",\"nulla\",\"consequat\",\"massa\",\"quis\",)\n print(replace_word(test1, 'right', 'left'))\n print(replace_word(test2, 'right', 'left'))\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<blockquote>\n <p>bleft aleft, ok, bleftness wleft</p>\n \n <p>lorem, ipsum, dolor, fleft, nec, pellentesque, eu, pretium, quis, sem, nulla, \n consequat, massa, quis</p>\n</blockquote></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T01:59:11.537",
"Id": "451221",
"Score": "0",
"body": "wow, exactly what I was looking for. so concise. thanks for taking the time. (not supposed to thank but it won't show my upvote)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T02:21:23.070",
"Id": "451224",
"Score": "0",
"body": "You're welcome and I guess the upvotes will work when you're past reputation of 15"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T01:17:00.643",
"Id": "231361",
"ParentId": "231360",
"Score": "6"
}
},
{
"body": "<p>To replace the \"right\" instances from your phrases you could do it in a more elegant and quicker way using regular expressions.</p>\n\n<pre><code>#Import Regex Library\nimport re \n#Function to replace all \"right\" instances from your phrases\ndef replace_right(phrase): \n phrase=list(phrase)\n for i in range(len(phrase)):\n #If the search of \"right\" is succesful\n if re.search(r\"right\",phrase[i]):\n #Substitutes \"right\" with \"left\"\n phrase[i]=re.sub(r\"right\",\"left\",phrase[i])\n return phrase\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T19:01:05.883",
"Id": "451290",
"Score": "3",
"body": "welcome to code review, as per regulations of this website: https://codereview.stackexchange.com/help/how-to-answer you should make at least one insightful observation about the code in the question and answers that provide an alternative solution without explaining their reasoning are invalid answers and may be deleted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:22:45.507",
"Id": "231385",
"ParentId": "231360",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231361",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T00:07:24.577",
"Id": "231360",
"Score": "9",
"Tags": [
"python",
"strings"
],
"Title": "python search replace and join with delimiter"
}
|
231360
|
<p>To summarize what I've been trying to do, I basically tried to make a safe <code>narrow_cast</code> operator, which casts to the Target type if and only if the value is unchanged (not narrowed) in the process, and throws an exception if the conversation will cause the value to change.</p>
<p>So I implemented this by making two templates, one for when <code>std::numeric_limits</code> of the Target type is specialized (by using <code>std::numeric_limits<T>::is_specialized</code> in conjunction with <code>std::enable_if</code>), and check if base is higher than the max value of target type of lower than the min value of target type, if it is, then throw an exception, elsewise, just do a static cast to the target.</p>
<p>And the second for when the <code>numeric_limits</code> are not specialized, by basically casting to the Target type, then casting back to the Base, and then comparing the old value with the new one. If both are the same, just return the Target casted value, if not, throw an exception.</p>
<p>But then, I got a response from the comments that my code might cause problems when Integer and Floating Point types are mixed, as even though a Floating point might fit inside an Integer range, it can still not be completely expressed by that type, so I stuck to ALWAYS using the second alternative.</p>
<hr>
<p><strong>Old Code [BAD, doesn't work properly when Integer and Floating Point types are mixed]</strong></p>
<pre class="lang-cpp prettyprint-override"><code>// utils.hh
// Contains globally used utility functions, templates, using declarations, etc.
#ifndef PHI_SRC_UTILS_HH
#define PHI_SRC_UTILS_HH
#include <string>
#include <vector>
#include <limits>
template <typename T>
using Vector = std::vector<T>;
using String = std::string;
using Size = std::size_t;
class bad_narrow_cast : public std::bad_cast
{
public:
bad_narrow_cast(const char* message) : what_(message)
{
}
char const *what() { return what_; }
private:
char const *what_;
};
template <typename Target, typename Base> static inline
typename std::enable_if<std::numeric_limits<Target>::is_specialized,
Target>::type narrow_cast(Base const &base)
{
if(base > static_cast<Base>(std::numeric_limits<Target>::max()) ||
base < static_cast<Base>(std::numeric_limits<Target>::min()))
{
throw(bad_narrow_cast((String() + "Invalid narrowing conversation from type " +
typeid(Target).name() + " to type " + typeid(Base).name()).c_str()));
}
return static_cast<Target>(base);
}
template <typename Target, typename Base> static inline
typename std::enable_if<!std::numeric_limits<Target>::is_specialized,
Target>::type narrow_cast(Base const &base)
{
Target target = static_cast<Target>(base);
Base narrowed_base = static_cast<Base>(target);
if (base == narrowed_base)
return target;
throw(bad_narrow_cast((String() + "Invalid narrowing conversation from type " +
typeid(Target).name() + " to type " + typeid(Base).name()).c_str()));
}
#endif
</code></pre>
<hr>
<p><strong>Fixed Code:</strong></p>
<pre class="lang-cpp prettyprint-override"><code>// utils.hh
// Contains globally used utility functions, templates, using declarations, etc.
#ifndef PHI_SRC_UTILS_HH
#define PHI_SRC_UTILS_HH
#include <string>
#include <vector>
#define UNUSED(x) (void)x
template <typename T>
using Vector = std::vector<T>;
using String = std::string;
using Size = std::size_t;
class bad_narrow_cast : public std::bad_cast
{
public:
bad_narrow_cast(char const *message) : what_(message)
{
}
char const *what() { return what_; }
private:
char const *what_;
};
template <typename Target, typename Base> static inline
Target narrow_cast(Base const &base)
{
Target target = static_cast<Target>(base);
Base narrowed_base = static_cast<Base>(target);
if (base == narrowed_base)
return target;
throw(bad_narrow_cast((String() + "Invalid narrowing conversation from type " +
typeid(Target).name() + " to type " + typeid(Base).name()).c_str()));
}
#endif
</code></pre>
<p>But I'm still unsure if I'm doing things the right way, so, comments on the code is appreciated, it'd be really helpful to improve it more if possible</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-21T15:43:27.063",
"Id": "519815",
"Score": "0",
"body": "You could make use of the curly-brace style initialization, which already disallows narrowing conversions."
}
] |
[
{
"body": "<p>I've attempted this before, and it's a little more complicated than checking if the value round-trips correctly. Consider:</p>\n<pre><code>int x = -3;\nunsigned int y = narrow_cast<unsigned int>(x);\n</code></pre>\n<p>This passes the round-trip test, but <code>y</code> has a different value than <code>x</code>. Before you know it, you'll be writing a lot of <code>if constexpr</code> with type traits in order to try to match the narrowing rules.</p>\n<p>The Guidelines Standard Library has a <code>narrow_cast</code> that's explored in <a href=\"https://stackoverflow.com/questions/52863643/understanding-gslnarrow-implementation\">Understanding <code>gsl::narrow</code> implementation</a> on Stack Overflow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-18T22:21:51.780",
"Id": "263204",
"ParentId": "231364",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T03:41:09.357",
"Id": "231364",
"Score": "6",
"Tags": [
"c++",
"casting"
],
"Title": "Implementation of narrow_cast in C++"
}
|
231364
|
<p>I want to create a collection (in this case a map due to the extended function 'groupBy') that maps an IntRange to a list of a data class, which members are determined whether an int inside the data class is within the IntRange.
The IntRanges are 0..9, 10..19, 20..29, etc.</p>
<p>Concrete example:</p>
<pre><code>data class Trip(
val (...)
val distance: Double
)
[...]
val mappedTrips = trips.groupBy {
((it.duration-(it.duration)%10))..((it.duration-(it.duration)%10)+9) }
</code></pre>
<p>Explicitly the </p>
<pre><code>((it.duration-(it.duration)%10))..((it.duration-(it.duration)%10)+9)
</code></pre>
<p>part seems to be not very concise, hard to read and therefore I was wondering if there is a way to make it more efficient, meaning more easy to read, concise.</p>
<p>Thank you in advance.</p>
<p>Edit:</p>
<pre><code>TaxiPark Class
package taxipark
data class TaxiPark(
val allDrivers: Set<Driver>,
val allPassengers: Set<Passenger>,
val trips: List<Trip>)
data class Driver(val name: String)
data class Passenger(val name: String)
data class Trip(
val driver: Driver,
val passengers: Set<Passenger>,
// the trip duration in minutes
val duration: Int,
// the trip distance in km
val distance: Double,
// the percentage of discount (in 0.0..1.0 if not null)
val discount: Double? = null
) {
// the total cost of the trip
val cost: Double
get() = (1 - (discount ?: 0.0)) * (duration + distance)
}
</code></pre>
<p>Task</p>
<p>Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on.
Return any period if many are the most frequent, return <code>null</code> if there're no trips.</p>
<p>Test sample</p>
<pre><code>class TestTask5TheMostFrequentTripDurationPeriod {
private fun testDurationPeriod(expected: Set<IntRange?>, tp: TaxiPark) {
val actual = tp.findTheMostFrequentTripDurationPeriod()
val message = "Wrong result for 'findTheMostFrequentTripDurationPeriod()': $actual."
if (expected.size <= 1) {
Assert.assertEquals(
message + tp.display(),
expected.firstOrNull(), actual)
} else {
Assert.assertTrue(message +
tp.display() +
"\nPossible results: $expected" +
"\nActual: $actual\n",
actual?.let { it in expected } ?: expected.isEmpty())
}
}
@Test
fun test00() = testDurationPeriod(setOf(null), taxiPark(0..1, 0..10))
@Test
fun test01() {
// The period 30..39 is the most frequent since there are two trips (duration 30 and 35)
testDurationPeriod(setOf(30..39), taxiPark(1..3, 1..5,
trip(1, 1, duration = 10),
trip(3, 4, duration = 30),
trip(1, 2, duration = 20),
trip(2, 3, duration = 35)))
}
@Test
fun test02() = testDurationPeriod(setOf(30..39), taxiPark(0..5, 0..9,
trip(0, listOf(2, 9), duration = 14, distance = 25.0),
trip(1, listOf(8), duration = 39, distance = 37.0, discount = 0.2),
trip(5, listOf(0, 5), duration = 27, distance = 28.0, discount = 0.3),
trip(4, listOf(0, 6), duration = 33, distance = 14.0),
trip(2, listOf(5, 1, 4, 3), duration = 2, distance = 15.0),
trip(4, listOf(7), duration = 27, distance = 2.0),
trip(4, listOf(4, 6), duration = 31, distance = 31.0),
trip(3, listOf(9, 0), duration = 34, distance = 7.0),
trip(5, listOf(3), duration = 25, distance = 33.0),
trip(1, listOf(0, 7, 2, 3), duration = 13, distance = 17.0))
)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T13:49:04.113",
"Id": "451263",
"Score": "0",
"body": "I don't quite see why you want to group by a *range*. Why not simply `trips.groupBy { it.duration / 10 }` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T21:01:23.853",
"Id": "451300",
"Score": "0",
"body": "Ah, sorry. Did not mention it. The task requires the return value to be an IntRange, that's why. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T22:30:03.573",
"Id": "451304",
"Score": "0",
"body": "Could you provide some more information about the task? The more we know about what you want to accomplish and why, the easier it is to give a better answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T08:57:01.533",
"Id": "451324",
"Score": "0",
"body": "Sure, just added the class, the task description and 2 task examples :)"
}
] |
[
{
"body": "<p>Since <code>it.duration</code> is quite long, you could use the alternative expression:</p>\n\n<pre><code>(it.duration / 10 * 10) .. (it.duration / 10 * 10 + 9)\n</code></pre>\n\n<p>You still have common subexpressions, though. To avoid these, you can define a cluster:</p>\n\n<pre><code>fun cluster(x: Double, size: Double) = (x - x % size) .. (x - x % size + size - 1)\n</code></pre>\n\n<p>or, to avoid the common subexpression:</p>\n\n<pre><code>fun cluster(x: Double, size: Double) = (x - x % size).let { it .. (it + size - 1) }\n</code></pre>\n\n<p>(I wrote the above without a compiler, so it may or may not work, but you get the idea.)</p>\n\n<p>Then, you can group the trips by their cluster:</p>\n\n<pre><code>trips.groupBy { cluster(it.duration, 10.0) }\n</code></pre>\n\n<p>By the way, the group \"30-39\" also contains 39.999, so you might get contacted by a nitpicker that your range should better be called \"[30,40)\". ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T07:17:15.637",
"Id": "231368",
"ParentId": "231366",
"Score": "2"
}
},
{
"body": "<ol>\n<li>You can use <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html\" rel=\"nofollow noreferrer\"><code>with</code></a> to avoid repeating the calculation of the <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/-int-range/start.html\" rel=\"nofollow noreferrer\"><code>start</code></a> of your <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/-int-range/index.html\" rel=\"nofollow noreferrer\"><code>IntRange</code></a>.</li>\n<li>You can use <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-double/to-int.html\" rel=\"nofollow noreferrer\"><code>toInt</code></a> and integer division and multiplication as a more direct approach to calculating the <code>start</code> of your <code>IntRange</code> (similiar to how <a href=\"https://codereview.stackexchange.com/users/6499/roland-illig\">Roland Illig</a> <a href=\"https://codereview.stackexchange.com/a/231368/91387\">suggests</a>).</li>\n<li>You can use <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/until.html\" rel=\"nofollow noreferrer\"><code>until</code></a> to clarify that your <code>IntRange</code>s are \"[0,10)\", \"[10,20)\", etc. which I think may be a bit clearer than \"[0,9]\", \"[10,19]\", etc. as the later will make readers think twice about if these ranges form a contiguous range or not whereas using closed-open ranges makes it, in my opinion, more clear.</li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>val mappedTrips = trips.groupBy {\n with(it.duration.toInt() / 10 * 10) { this until this + 10 }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T13:08:42.670",
"Id": "231595",
"ParentId": "231366",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231368",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T05:31:35.213",
"Id": "231366",
"Score": "2",
"Tags": [
"lambda",
"kotlin"
],
"Title": "Concise way of creating a IntRange out of an Int"
}
|
231366
|
<p>I'm new to C++ and I'm writting some kind of chat server and client who talk to each other through commands for learning purposes. I serialize and deserialize these commands using a JSON library. My first approach has been to create a base class called Command and have a derived class for each command. </p>
<p>The use case would be to be able to directly create objects of the derived classes on the client and to call a deserialize function that will return an object of the derived class on the server. I have something like this.</p>
<pre><code>enum class Commands {
NAME = 0,
QUIT,
WHISPER,
JOIN,
CREATE,
UNKNOWN
};
class Command {
protected:
Commands command;
public:
Commands getCommandType();
virtual Message serialize();
static Command* deserialize(Message message);
};
</code></pre>
<p>I thought it would be better to leave command private and make the Command constructor initialize that value and then for every derived class, have it call the "super" constructor. But I don't know if this is a good approach in C++.
I serialize the enum too because each command will have a different number of fields when serialized. For the implementation of deserialize I have this:</p>
<pre><code>Command* Command::deserialize(Message message) {
auto parsed_message = json::parse(message);
if (parsed_message["type"] != "command") {
throw "Unexpected message";
}
//Insert every command.
if (parsed_message["command"] == Commands::QUIT) {
return QuitCommand::deserialize(message);
}
if (parsed_message["command"] == Commands::NAME) {
return NameCommand::deserialize(message);
}
if (parsed_message["command"] == Commands::WHISPER) {
return WhisperCommand::deserialize(message);
}
throw "Unknown command";
}
</code></pre>
<p>And then as an example for a deserialize method:</p>
<pre><code>NameCommand* NameCommand::deserialize(Message message) {
auto parsed_message = json::parse(message);
if (parsed_message["type"] == "command" && parsed_message["command"] == Commands::NAME) {
return new NameCommand(parsed_message["name"]);
} else {
throw "NAME command not valid";
}
}
</code></pre>
<p>Now, the code right now works (or at least it seems like it does), but I don't see how it is maintainable or well structued. Could anyone please give me their opinion of the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-09T15:29:48.733",
"Id": "453063",
"Score": "2",
"body": "It's hard to review because a lot is missing. It's not clear, for example, why `NameCommand` and `QuitCommand` are different classes or what they do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-11T16:25:47.450",
"Id": "453265",
"Score": "1",
"body": "I think you should add the implementation of each command. Don't worry about your post being long."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T07:43:23.623",
"Id": "231369",
"Score": "3",
"Tags": [
"c++",
"beginner",
"object-oriented",
"parsing"
],
"Title": "Implementing chat commands"
}
|
231369
|
<p>I'm trying to write a program where computer attempts to guess a number entered by user. Computer should keep asking until guessed number will be equal to user number.</p>
<p>If you know what can be improved to make this code more readable, if implementation of the binary search algorithm is efficient, let me know!</p>
<pre><code>#include <cstdlib>
#include <iostream>
int main() {
std::srand(time(nullptr));
constexpr int MIN = 1;
constexpr int MAX = 100;
std::cout << "Choose a number from " << MIN << " to " << MAX << "\n";
int number;
std::cin >> number;
int high = MAX;
int low = MIN;
int guess = (high + low) / 2;
char lessThan = std::rand() % 2 == 0 ? 'y' : 'n';
char greaterThan = std::rand() % 2 == 0 ? 'y' : 'n';
while (greaterThan == lessThan)
greaterThan = std::rand() % 2 == 0 ? 'y' : 'n';
while (guess != number) {
if (lessThan == 'y' && greaterThan == 'n') {
std::cout << "Is your number less than " << guess << "? [y|n]\n";
std::cin >> lessThan;
if (lessThan == 'y') {
high = guess - 1;
greaterThan = 'n';
} else if (lessThan == 'n') {
low = guess + 1;
greaterThan = 'y';
}
} else if (greaterThan == 'y' && lessThan == 'n') {
std::cout << "Is your number greater than " << guess << "? [y|n]\n";
std::cin >> greaterThan;
if (greaterThan == 'y') {
low = guess + 1;
lessThan = 'n';
} else if (greaterThan == 'n') {
high = guess - 1;
lessThan = 'y';
}
}
guess = (high + low) / 2;
}
std::cout << "I guessed!\n";
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>A couple points here, first you should always use curly braces <code>{</code> <code>}</code>, even when the code to be executed is 1 line long.</p>\n\n<p>More importantly, you potentially have an infinite loop. Even if you had more than 2 values to choose from, this is a bad approach. A better idea is <code>greaterThan = greaterThan == 'y' ? 'n' : 'y';</code>.</p>\n\n<pre><code>while (greaterThan == lessThan)\n greaterThan = std::rand() % 2 == 0 ? 'y' : 'n';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:09:08.877",
"Id": "231384",
"ParentId": "231370",
"Score": "0"
}
},
{
"body": "<p>I don't know, if you can understand all my code, but I would implement the task this way:</p>\n\n<pre><code>#include <iostream>\n#include <random>\n#include <string>\n\nenum class CompareAnswer { LESS, LESS_OR_EQUAL, GREATER, GREATER_OR_EQUAL };\nenum class TruthAnswer { YES, NO };\n\nCompareAnswer ask_user_compare(int compare_with) {\n static auto randfn = []() -> bool {\n static auto dist = std::uniform_int_distribution<>(0, 1);\n static auto gen = std::default_random_engine();\n return static_cast<bool>( dist(gen) );\n };\n\n char user_input;\n std::cout << \"Is your number \";\n\n if (randfn()) {\n std::cout << \"less than \" << compare_with << \"? [y|n]\\n\";\n std::cin >> user_input;\n if (user_input == 'y')\n return CompareAnswer::LESS;\n if (user_input == 'n')\n return CompareAnswer::GREATER_OR_EQUAL;\n throw std::runtime_error(\"invalid answer\");\n };\n\n std::cout << \"greater than \" << compare_with << \"? [y|n]\\n\";\n std::cin >> user_input;\n if (user_input == 'y')\n return CompareAnswer::GREATER;\n if (user_input == 'n')\n return CompareAnswer::LESS_OR_EQUAL;\n throw std::runtime_error(\"invalid answer\");\n};\n\nTruthAnswer ask_user_is(int number) {\n std::cout << \"Is your number \" << number << \"? [y|n]\\n\";\n char user_input;\n std::cin >> user_input;\n\n if (user_input == 'y')\n return TruthAnswer::YES;\n if (user_input == 'n')\n return TruthAnswer::NO;\n throw std::runtime_error(\"invalid answer\");\n}\n\nint guess_number(const int min, const int max) {\n // std::cout << \"\\ndebug: min=\" << min << \" max=\" << max << \"\\n\";\n\n const int median = (min + max) / 2; // (77+78)/2 =77\n\n if (median == min) {\n return ask_user_is(min) == TruthAnswer::YES ? min : max;\n };\n\n switch (ask_user_compare(median)) {\n case CompareAnswer::GREATER:\n return guess_number(median + 1, max);\n case CompareAnswer::GREATER_OR_EQUAL:\n return guess_number(median, max);\n case CompareAnswer::LESS:\n return guess_number(min, median - 1);\n case CompareAnswer::LESS_OR_EQUAL:\n return guess_number(min, median);\n default:\n throw std::logic_error(\"need case for some of 'enum Answer' \");\n };\n};\n\nint main() {\n constexpr int MIN = 0;\n constexpr int MAX = 10000;\n\n std::cout << \"Choose a number from \" << MIN << \" to \" << MAX << \"\\n\";\n int number;\n std::cin >> number;\n if(number < MIN || number > MAX) throw std::runtime_error(\"Invalid number\");\n\n int guessed = guess_number(MIN, MAX);\n std::cout << \"Your number is: \" << guessed << \"\\n\";\n}\n</code></pre>\n\n<p>Even though <code>guess_number</code> is recursive function, probability of stack overflow extremely low (cause <code>log(N)</code> complexity). Asking user again instead of throwing exception may be good idea too. </p>\n\n<p><strong>Also:</strong>\nGenerally <strong>forget</strong> about <code>srand</code>, use <strong><code><random></code></strong> instead (<code>srand</code> is only for homework) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T20:36:39.073",
"Id": "231390",
"ParentId": "231370",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T08:20:51.337",
"Id": "231370",
"Score": "5",
"Tags": [
"c++",
"homework",
"binary-search"
],
"Title": "Binary search guess game in C++"
}
|
231370
|
<p>Left limit, right limit and the digit to be counted is entered. This code works only for whole numbers i. e. from 0 to n. This code returns the number of occurence of the digit <code>n</code> in the given range. Please review this code and suggest improvements.</p>
<pre><code>#include <iostream>
int count_n(int l, int r, int n)
{
if (r <= l)
{
std::cerr << "Right limit must greater then left limit\n";
return 0;
}
if (l < 0)
{
std::cerr << "Only positive integers\n";
return 0;
}
int count = 0;
for (int i = l; i <= r; ++i)
{
int i_copy = i;
while (i_copy != 0)
{
if (i_copy % 10 == n)
{
count++;
}
i_copy = i_copy / 10;
}
}
return count;
}
int main()
{
int left_limit, right_limit, num;
std::cout << "Enter left limit, right limit and the number(Only positive numbers)\n";
std::cin >> left_limit >> right_limit >> num;
int result = count_n(left_limit, right_limit, num);
std::cout << result << "\n";
}
</code></pre>
<p>Output:</p>
<pre><code>Enter left limit, right limit and the number(Only for positive numbers)
1 20 0
2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T18:09:46.480",
"Id": "451288",
"Score": "0",
"body": "There is a much better algorithm. See [this answer](https://codereview.stackexchange.com/questions/117670/finding-the-sum-of-all-the-segment-counts-of-a-7-segment-display-in-a-range/117693#117693) for some hints as to how to derive it."
}
] |
[
{
"body": "<h3>1. Error handling</h3>\n\n<p>Since <code>0</code> could also be a valid result for the input (e.g. <code>6 10 5</code>), I'd prefer to indicate invalid input via exceptions rather than the return value:</p>\n\n<pre><code>int count_n(int l, int r, int n) {\n if (r <= l) {\n throw std::invalid_argument(\"Right limit must greater then left limit\");\n }\n\n if (l < 0) {\n throw std::invalid_argument(\"Only positive integers\");\n }\n\n // ...\n}\n</code></pre>\n\n<p>Thus the caller of the function can distinguish invalid input parameters from valid results by putting the call of <code>count_n()</code> into a <code>try / catch</code> block.</p>\n\n<h3>2. Function and parameter naming</h3>\n\n<p>Naming the function <code>count_n()</code> and the parameter for the digit to count <code>n</code> is a bit unclear.<br>\nYou should rather use the signature </p>\n\n<pre><code> int count_digit(int min_left, int max_right, int digit);\n</code></pre>\n\n<p>to make the intend of that function clearer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T10:23:02.250",
"Id": "231373",
"ParentId": "231371",
"Score": "1"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/231373/136864\">this</a>, you should specify validation for <code>n</code> ( <code>digit</code> ).\nAlso, it may be better to group validations into separate function.</p>\n\n<pre><code>void check_input(int min_left, int max_right, int digit) {\n if (max_right <= min_left)\n throw std::invalid_argument(\"right is <= left, expected right > left\");\n if (min_left < 0)\n throw std::invalid_argument(\"left < 0, expected left > 0\");\n if (digit <= 0)\n throw std::invalid_argument(\"digit <= 0\");\n //throw std::invalid_argument(\"number <= 0\"); \n if (digit > 9)\n throw std::invalid_argument(\"digit > 9\");\n\n ////number:\n //if (digit > max_right)\n // throw std::invalid_argument(\"number > right limit\");\n}\n\nint count_digit_entries(int min_left, int max_right, int digit) {\n//...\n}\n\nint main() {\n int left_limit, right_limit, num;\n std::cout << \"Enter left limit, right limit and the number(Only positive numbers)\\n\";\n std::cin >> left_limit >> right_limit >> num;\n\n check_input(left_limit, right_limit, num);\n\n int result = count_digit_entries(left_limit, right_limit, num);\n\n std::cout << \"\\nTotal: \" << result << \"\\n\";\n}\n</code></pre>\n\n<p>You may want to find not only digits but a whole numbers.</p>\n\n<pre><code>//...\n\n\n#define DEBUG\n#ifdef DEBUG\n#define debug(x) x\n#else \n#define debug(x)\n#endif\n\n\nint count_digit_entries(int min_left, int max_right, int search_number) {\n int count = 0;\n\n int mod = 10;\n while(search_number / mod > 0) mod = mod * 10; // 279 -> 1000\n\n for (int current_number = min_left, right = max_right; current_number < right; ++current_number) {\n int copied_current_number = current_number; // 542793\n\n while (copied_current_number >= search_number) {\n // 542793 - 279 % 1000 >0 \n // 54279 - 279 % 1000 =0\n\n if ( ( (copied_current_number - search_number) % mod ) == 0 ) { \n debug(std::cout << current_number << \" \");\n ++count;\n };\n copied_current_number = copied_current_number / 10; \n // 542793 -> 54279\n\n };\n };\n\n return count;\n};\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Enter left limit, right limit and the number(Only positive numbers)\n0 1000 25\n25 125 225 250 251 252 253 254 255 256 257 258 259 325 425 525 625 725 825 925 \nTotal: 20\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T16:34:13.410",
"Id": "231382",
"ParentId": "231371",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T08:55:53.670",
"Id": "231371",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Count number of occurences of a digit in the range"
}
|
231371
|
<blockquote>
<h3>Problem description</h3>
<p>Scarpi, who owns a restaurant, decided to remodel
it with his friends because the interior of the restaurant is too old.
The place where the restaurant is located is a very cold area in the
snow town, so it is necessary to check the condition of the exterior
walls periodically during the interior work.</p>
<p>The structure of the restaurant is completely round and the total
circumference of the outer wall is n meters, and some points on the
outer wall have vulnerable points which may be damaged in extreme
cold. Therefore, we decided to periodically send friends to check
whether the vulnerable points of the outer wall were not damaged
during the internal construction. However, the inspection time was
limited to 1 hour for quick construction. The distance that friends
can travel for an hour is different, so try to get at least a few
friends to check for vulnerabilities and the rest of the friends to
help with the construction. For convenience, the north-facing point of
the restaurant is represented by 0, and the location of the vulnerable
point is indicated by the distance clockwise from the north-facing
point. In addition, friends only move along the outer wall clockwise
or counterclockwise from the starting point.</p>
<p>When given as a parameter the length of the outer wall n, an array
containing the location of the weak point, and an array dist with the
distance each friend can move for 1 hour, return the minimum number of
friends that should be sent to check for the weak point. Complete the
solution function.</p>
<h3>Limitations</h3>
<ul>
<li><span class="math-container">\$n\$</span> is a natural number between <span class="math-container">\$1\$</span> and <span class="math-container">\$200\$</span>, inclusive. </li>
<li>A weakness has a length between <span class="math-container">\$1\$</span> and <span class="math-container">\$15\$</span>, inclusive. </li>
<li>Two different vulnerabilities are not given the same location. </li>
<li>The location of the weak point is given in ascending order. </li>
<li>The weak element is an integer greater than or equal to <span class="math-container">\$0\$</span> and less than <span class="math-container">\$n-1\$</span>. </li>
<li>The length of dist is <span class="math-container">\$1\$</span> or more and <span class="math-container">\$8\$</span> or less. </li>
<li>The elements of dist are natural numbers between <span class="math-container">\$1\$</span> and <span class="math-container">\$100\$</span>, inclusive.</li>
</ul>
</blockquote>
<p><a href="https://tech.kakao.com/2019/10/02/kakao-blind-recruitment-2020-round1/" rel="nofollow noreferrer">https://tech.kakao.com/2019/10/02/kakao-blind-recruitment-2020-round1/</a><br>
<a href="https://programmers.co.kr/learn/courses/30/lessons/60062" rel="nofollow noreferrer">https://programmers.co.kr/learn/courses/30/lessons/60062</a><br>
The first link is the website to the description and second link is the challenge site. But I don't think this would be of help since it's in Korean language.</p>
<p>This simulation is given finding the minimum numbers of patrollers, given patroller's coverage and position of the weak points. The weak points are the weak points on the wall that needs to be fixed. The wall is circular, and that's why there exists additional push_back when creating create_dist_btw_wp.</p>
<p>I stored the distances between weakpoints as vector, and tried to test all permutations of the patrollers.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <bits/stdc++.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
inline int num_patrolling(vector<int>::const_iterator cit, vector<int>::const_iterator cbegin) {
return int(cit - cbegin) + 1;
}
vector<int>& create_dist_btw_wp(vector<int>& weak_points, int wall_length) {
vector<int>* result = new vector<int>;
for (int i = 1; i < weak_points.size(); ++i)
result->push_back(weak_points[i] - weak_points[i - 1]);
result->push_back(weak_points[0] + wall_length - weak_points.back());
return *result;
}
int main() {
int wall_length = 12;
vector<int> weak_points = {1, 5, 6, 10};
vector<int> patrol_dists = {1, 2, 3, 4};
cout <<solution(wall_length, weak_points, patrol_dists) << endl;
return 0;
}
// wp stands for weakpoints
// weak_points stores dist of wps at wall from 0
int solution(int wall_length, vector<int> weak_points, vector<int> patrol_dists) {
if (weak_points.size() == 1)
return 1;
vector<int> dist_btw_wp = create_dist_btw_wp(weak_points, wall_length);
sort(patrol_dists.begin(), patrol_dists.end());
auto num_wp = weak_points.size();
int ans = 0x3f3f3f3f;
// TODO//
// seems next_permutation is enough and 2 for loops inside
// do_while loop seems overkill.
// Needs to be checked
do {
for (int first_wp_idx = 0; first_wp_idx < num_wp; ++first_wp_idx) {
int end_wp_idx = (first_wp_idx + num_wp - 1) % num_wp;
bool wp_patrolled[20]{};
auto it_patrol_dists = patrol_dists.cbegin();
int patrolled_dist = 0;
for (int cur_wp_idx = first_wp_idx; cur_wp_idx != end_wp_idx; (++cur_wp_idx) %= num_wp)
{
if (it_patrol_dists == patrol_dists.cend()) break; // can't patrol all
wp_patrolled[cur_wp_idx] = true;
patrolled_dist += dist_btw_wp[cur_wp_idx];
if (patrolled_dist > *it_patrol_dists)
{
++it_patrol_dists;
patrolled_dist = 0;
}
}
if (it_patrol_dists != patrol_dists.cend())
ans = min(ans, num_patrolling(it_patrol_dists, patrol_dists.cbegin()));
}
} while (next_permutation(patrol_dists.begin(), patrol_dists.end()));
return ans == 0x3f3f3f3f ? -1 : ans;
}
</code></pre>
|
[] |
[
{
"body": "<h2>Avoid Using Namespace <code>std</code></h2>\n<p>It is possible that <code>#include <bits/stdc++.h></code> and <code>using namespace std;</code> was provided by the challenge site, in that case it might be better to delete that from the code when you answer the challenge.</p>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<p>As an example of how the <code>using namespace std;</code> can be confusing, while reviewing the code I found the code</p>\n<pre><code> } while (next_permutation(patrol_dists.begin(), patrol_dists.end()));\n</code></pre>\n<p>since I don't know every std library routine I performed a search for <code>next_permutation</code> in the code. I ended up in the algorithm include header.</p>\n<h2>Include Headers</h2>\n<p>The code contains <code>#include <string></code> and is missing <code>#include <algorithm></code>. The <code>string</code> header is not necessary because string are not used in the program. The only reason the code was compiling on the challenge site is because the <code>#include <bits/stdc++.h></code> was there. Make sure to include all the headers necessary.</p>\n<h2>Magic Numbers</h2>\n<p>There is a numeric constant in the <code>solution()</code> function (<code>0x3f3f3f3f</code>), it might be better to create symbolic constants for this to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. In this particular instance it isn't clear what this value means.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h2>Memory Leak</h2>\n<p>The function <code>std::vector<int>& create_dist_btw_wp(std::vector<int>& weak_points, int wall_length)</code> allocates a vector, but the vector is never deleted. In a larger program this would lead to a memory leak that could have serious side effects. If returning a reference was done for performance reasons, then at the end of the function <code>solution()</code> the vector should be deleted. If it was done for any other reason perhaps the function should be rewritten as</p>\n<pre><code>std::vector<int> create_dist_btw_wp(std::vector<int>& weak_points, int wall_length) {\n std::vector<int> result;\n \n for (size_t i = 1; i < weak_points.size(); ++i)\n {\n result.push_back(weak_points[i] - weak_points[i - 1]);\n }\n result.push_back(weak_points[0] + wall_length - weak_points.back());\n \n return result;\n}\n</code></pre>\n<p>The memory allocated for the <code>result</code> vector in the function will automatically be deleted when the function ends, a copy of <code>result</code> is returned to the <code>solution()</code> function. That copy will be automatically deleted when the function <code>solutions</code> ends.</p>\n<h2>Use Code Blocks</h2>\n<p>Primarily for maintenance reasons it is a good habit to create code blocks within if statements, else clauses and within loops. Many bugs have been created during maintenance when one or more statements was added to an if statement or a loop. There is an example of this in the code above. It also makes the code a little easier to read. Vertical spacing should also be used to make the code more readable.</p>\n<h2>Complexity</h2>\n<p>The function <code>solution()</code> is too complex (does too much). Perhaps the contents of the outer <code>for</code> loop of the <code>do while</code> should be a function.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\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",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T06:56:43.823",
"Id": "451952",
"Score": "0",
"body": "Thank you so much with your works. It really helped me with what i should be doing for the next time i make questions here, and what has been problem with my codes. With memory leak problem you’ve suggested, I thought having vector result returned without copied will be of better performance for there’s no need for copying it. And I didn’t want to suffer from having pointer type returned because i don’t know how to use iterators with pointer type of vector. Also thank you with all 5e links. I enjoyed reading those"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:07:53.357",
"Id": "231474",
"ParentId": "231375",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T11:45:11.793",
"Id": "231375",
"Score": "1",
"Tags": [
"c++",
"programming-challenge",
"simulation"
],
"Title": "Simulation to find the minimum number of patrollers to cover a wall"
}
|
231375
|
<p>The idea about this code is that it's a full replacement of Redux — in 22 lines of code.</p>
<pre><code>let state = null
const beforeSetStateCallbacks = []
const afterSetStateCallbacks = []
export const beforeSetState = (fn) => beforeSetStateCallbacks.push(fn)
export const afterSetState = (fn) => afterSetStateCallbacks.push(fn)
export const setState = async (key, value) => {
if (state === null) state = {}
// QUESTION: Should I use Promise.all for performance reason?
// Note that the order might be important though
for (const fn of beforeSetStateCallbacks) await fn(key, value)
state[key] = value
for (const fn of afterSetStateCallbacks) await fn(key, value)
}
export const stateEmpty = () => {
return !state
}
export const getState = (key) => {
if (!state) return null
return state[key]
}
</code></pre>
<p>There is no <code>dispatch()</code> because the whole actions/reducers madness melts away, simple functions are meant to modify the state and then call (for example) <code>setState('userInfo', userInfo)</code>.</p>
<p>Example usage is here: <a href="https://glitch.com/edit/#!/lacy-ornament" rel="nofollow noreferrer">https://glitch.com/edit/#!/lacy-ornament</a></p>
<p>The rundown:</p>
<ul>
<li><code>index.html</code> contains this:</li>
</ul>
<pre><code><script type="module" src="./one.js"></script>
<my-one></my-one>
</code></pre>
<p>The first line defines a custom element <code>my-one</code>. The second line places that element.</p>
<ul>
<li><code>StateMixin.js</code> contains this:</li>
</ul>
<pre><code>import { setState, getState, afterSetState, stateEmpty } from './reducs.js'
export const StateMixin = (base) => {
return class Base extends base {
constructor () {
super()
if (stateEmpty()) {
setState('basket', { items: [], total: 0 })
}
this.basket = getState('basket')
afterSetState((k, value) => {
this[k] = { ...value }
})
}
}
}
</code></pre>
<p>Basically, something is added to the constructor where if the state isn't yet defined, it gets assigned a default initial state.
Then, assigning<code>this.basket</code> makes sure that the <code>basket</code> property of the element is current, and <code>afterSetState()</code> will make sure that further modifications to the basket will also update <code>this.basket</code>.</p>
<p>This means that any element that has <code>this.basket</code> as a property will get updated when <code>this.basket</code> is changed.</p>
<ul>
<li><code>one.js</code> contains this:</li>
</ul>
<pre><code>import { LitElement, html } from 'lit-element/lit-element.js'
import { StateMixin } from './StateMixin.js'
import { addItemToBasket } from './actions.js'
// Extend the LitElement base class
class MyOne extends StateMixin(LitElement) {
static get properties () {
return {
basket: {
type: Object,
attribute: false
}
}
}
render () {
return html`
<p>Basket</p>
<p>Total items: ${this.basket.total}</p>
<p>Items:</p>
<ul>
${this.basket.items.map(item => html`
<li>${item.description}</li>
`)}
</ul>
<input type="text" id="description">
<button @click="${this._addItem}">Add</button>
`
}
_addItem () {
const inputField = this.shadowRoot.querySelector('#description')
addItemToBasket( { description: inputField.value })
inputField.value = ''
}
}
// Register the new element with the browser.
customElements.define('my-one', MyOne)
</code></pre>
<p>This is a very minimalistic element, where a few interesting things happen. First of all, it's mixed with <code>StateMixin.js</code>, which will ensure that the constructor deals with status and registration for changes. It also defines a <code>basket</code> property, which means that when the basket is changed, the element will re-render.</p>
<p>Finally, <code>_addItem()</code> will run the action <code>addItemToBasket()</code> which is the only action defined.</p>
<ul>
<li><code>actions.js</code> contains this:</li>
</ul>
<pre><code>import { getState, setState } from './reducs.js'
export const addItemToBasket = (item) => {
const basket = getState('basket')
basket.items. push(item)
basket.total = basket.items.length
basket.items = [ ...basket.items ]
setState('basket', basket)
}
</code></pre>
<p>This is simple: first of all, the state is loaded with <code>getState()</code>. Then, it's modified. Note that lit-html only re-renders changed things. So, basket.items is re-assigned. Finally, the state is set with <code>setState()</code>.</p>
<p>Note: you might have multiple branches in your state: <code>basket</code>, <code>userInfo</code>, <code>appConfig</code>, and so on.</p>
<p>Questions:</p>
<ul>
<li>If I use <code>Promise.all</code>, I will lose the certainty that the calls are called in order. Do you think I should still do it?</li>
<li>Is there a way to prevent the check on state every single time in <code>setState()</code> and <code>stateEmpty()</code>? The idea is that stateEmpty() returns false if the state has never been initialised.</li>
<li>How would you recommend to implement an "unlisten" function here? As in, what's the simplest possible path to provide the ability to stop listening?</li>
<li>Since this is indeed a working 100% replacement on Redux (in 22 lines), shall I name the functions more ala Redux? Redux has "subscribe", but I like giving the option to subscribe to before and after the change. Maybe <code>subscribe()</code> and <code>subscribeBefore()</code>? </li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T13:38:26.683",
"Id": "451262",
"Score": "0",
"body": "@Merc, please add a testable https://jsfiddle.net/ link (or alike) with code (and sample object)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T21:14:20.373",
"Id": "451301",
"Score": "0",
"body": "OK doing it now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T22:46:36.283",
"Id": "451305",
"Score": "0",
"body": "OK done. @RomanPerekhrest doing this was a JOB AND A HALF :D I hope what I wrote makes sense. I really do look (humbly) forward to comments and reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T23:18:00.407",
"Id": "451308",
"Score": "1",
"body": "I just saw the tag \"reinventing-the-wheel\". I think we should also add the tag \"simplifying-an-overcomplex-wheel\" :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T10:56:14.000",
"Id": "451332",
"Score": "0",
"body": "I am not a redux user so my knowledge is limited. However I have some questions? There is no state history?, The sate is being mutated and holding references, not copies. Are you relying on the components to ensure only copies are passed and that the callbacks do not mutate the state value? The callbacks (Before, and After) are state global, this seams very clumbersum for large states models. Is the need to be 22 lines forcing the code using your mini redux to be longer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:03:20.193",
"Id": "451338",
"Score": "0",
"body": "1) Redux doesn't have any state history either 2) Mutation (or not) is always possible in Javascript, Redux or Reducs can't stop code from doing so. 2a) I returned a copu of the object in my example because lit-element requires it. Some frameworks won't need you to do that 3) Callbacks are not state global, they are called for the right branch of the state (basket, userInfo, appconfig) 4) The code that uses Redux is normally wwaaaaaayyyyyy longer with all those reducers, actions, and amazing code bureaucracy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T06:59:47.437",
"Id": "451586",
"Score": "0",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code 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-10-30T11:48:10.677",
"Id": "451612",
"Score": "0",
"body": "No problem. I am a CodeReview newbie."
}
] |
[
{
"body": "<p>I may or may not have seen a certain movie in the cinema, but the Batman in me wants to say this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gaQ5L.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gaQ5L.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Not to mention that semicolons don't hurt either.</p>\n\n<p>Also, per @Blindman67, it seems that you are pushing complexity down to the callers. It seems to me a number of callbacks would only want to run for a given <code>key</code>, forcing callers to check the <code>key</code> value is not good design.</p>\n\n<p>For this part: </p>\n\n<blockquote>\n <p>Is there a way to prevent the check on state every single time in\n setState() and stateEmpty()?</p>\n</blockquote>\n\n<p>I would declare <code>state</code> like <code>let state = {};</code>\nThen you dont need to check in <code>setState</code>, because <code>state</code> is already an <code>Object</code>.\nYou would write <code>stateEmpty</code> like this:</p>\n\n<pre><code>export const stateEmpty = () => {\n return !Object.keys(state).length;\n}\n\nexport const getState = (key) => {\n return state[key]\n}\n</code></pre>\n\n<p>This would save you 2 lines, and avoids the akward <code>null</code> value.</p>\n\n<p>The Joker in me considers your <code>beforeSetStateCallbacks</code> and <code>afterSetStateCallbacks</code> as just two parts of the same coin. I have not tested this, but the below should be both possible and cleaner;</p>\n\n<pre><code>let state = {};\nconst batch = [(key,value)=>state[key] = value];\n\nexport const beforeSetState = (fn) => batch.unshift(fn);\nexport const afterSetState = (fn) => batch.push(fn);\n\n\nexport const setState = async (key, value) => {\n for (const f of batch){\n await f(key, value);\n }\n}\n</code></pre>\n\n<p>In this vein, this question becomes easier:</p>\n\n<blockquote>\n <p>How would you recommend to implement an \"unlisten\" function here?</p>\n</blockquote>\n\n<p>If the subscriber remembers the function they used to subscribe you could go like this, because now you dont care whether the caller listens to before or after.</p>\n\n<pre><code>export const unhook = (fn) => batch.splice(0, batch.length, ...batch.filter(f=>f!=fn));\n</code></pre>\n\n<p>The last item I want to mention is a <a href=\"https://en.wikipedia.org/wiki/Graceful_exit\" rel=\"nofollow noreferrer\">graceful exit</a>. Your code is short, because for one thing you trust that the caller will always provide a function for <code>fn</code>. Consider adding more type checks, otherwise the stack-trace will end frequently in your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:15:40.903",
"Id": "451347",
"Score": "0",
"body": "GOLDEN. I will implement every single suggestion here. Now... how do I do this? I don't want to change the question. Shall I add the updated code as a trailing update? Sorry, I am a StackOverflow guy, I don't spend enough time here at CodeReview!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:22:34.147",
"Id": "451348",
"Score": "0",
"body": "I love your suggestion for batched callback, and how it starts with one prefefined call in the middle. My only problem here is that developers will expect `beforeSetState()` calls to be run in the order they are defined, whereas with your code they will be run in reversed order. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:23:38.603",
"Id": "451350",
"Score": "0",
"body": "@Merc after your question has been answered you should NOT change your question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:25:20.953",
"Id": "451351",
"Score": "0",
"body": "About unlistening, a user could want to listen to the same function twice, and only desire to \"unlisten\" to a specific one. Redux does it by making sure that register() returns a function that will remove that registration. But... I am having trouble finding a nice, reliable way to implement that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:42:54.423",
"Id": "451353",
"Score": "0",
"body": "I need to think on the order and unhook points, they are both valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T06:46:42.590",
"Id": "451585",
"Score": "0",
"body": "I added the version with all mods applied. I think it's magical!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T07:17:56.663",
"Id": "451589",
"Score": "0",
"body": "In that case, feel free to hit the green checkmark next to the answer ;)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:04:39.070",
"Id": "231404",
"ParentId": "231378",
"Score": "3"
}
},
{
"body": "<p>After @konjin's great answer, I ended up with this wonderful code:</p>\n\n<pre><code>const state = {}\nlet beforeCallbacks = []\nlet afterCallbacks = []\nlet globalId = 0\n\nconst deleteId = (id, type) => {\n type === 'a'\n ? afterCallbacks = afterCallbacks.filter(e => e.id !== id)\n : beforeCallbacks = beforeCallbacks.filter(e => e.id !== id)\n}\n\nexport const register = (fn, type = 'a') => {\n const id = globalId++\n (type === 'a' ? afterCallbacks : beforeCallbacks).push({ fn, id })\n return () => deleteId(id, type)\n}\n\nexport const setState = async (key, value) => {\n for (const e of [...beforeCallbacks, { fn: () => { state[key] = value } }, ...afterCallbacks]) {\n const v = e.fn(key, value)\n if (v instanceof Promise) await v\n }\n}\nexport const stateEmpty = () => !Object.keys(state).length\nexport const getState = (key) => state[key]\n</code></pre>\n\n<p>I used his idea in <code>setState()</code> to create an array where <code>state[key] = value</code> is sandwiched between the before and after calls.</p>\n\n<p>I followed his advice of assigning <code>{}</code> to state, and adding curly brackets like Batman said :D </p>\n\n<p>I implemented de-registration by adding an ID to each one, rather than deleting the function, as I want to make sure I can assign the same function and de-register it without side effects.</p>\n\n<p>His answer IS the accepted answer.</p>\n\n<p>Thanks!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T11:43:36.540",
"Id": "231526",
"ParentId": "231378",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231404",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T12:47:34.920",
"Id": "231378",
"Score": "5",
"Tags": [
"javascript",
"reinventing-the-wheel",
"ecmascript-6",
"callback"
],
"Title": "Simple replacement for Redux in ES6"
}
|
231378
|
<p>I am trying to practice the Observer design pattern in Golang, here is my code. I would be pleased to receive your comments, improvements, etc.</p>
<pre><code>package observer
import (
"container/list"
"fmt"
"math/rand"
)
//interface that receive updates
type Observer interface{
Update(s *Subject)
}
// interface that manage notifying
type Subject struct{
observers *list.List
status int
}
func NewSubject() *Subject {
//this can be categorized from database etc
return &Subject{observers:new(list.List)}
}
func (s *Subject) Attach(o Observer){
s.observers.PushBack(o)
}
func (s *Subject) DeAttach(o Observer){
for obs := s.observers.Front(); obs != nil; obs = obs.Next() {
if obs.Value.(Observer) == o {
s.observers.Remove(obs)
}
}
}
func (s *Subject) notify(){
for obs := s.observers.Front(); obs != nil; obs = obs.Next() {
observer := obs.Value.(Observer)
observer.Update(s)
}
}
// some business logic function to notify
func (s *Subject) ScanData() {
// just generate random number for status
// this can be a business logic in real world to calculate or fetch status for a specific source or logic
s.status = rand.Intn(1000)
s.notify()
}
//Concrete class A for Observer
type ConcreteNotifierA struct{
}
func NewConcreteNotifierA() *ConcreteNotifierA {
return &ConcreteNotifierA{
}
}
func (a *ConcreteNotifierA) Update(s *Subject) {
if s.status > 500 {
fmt.Printf("Status is bigger than 500: %v \n", s.status)
}
}
//Concrete class B for Observer
type ConcreteNotifierB struct{
}
func NewConcreteNotifierB() *ConcreteNotifierB {
return &ConcreteNotifierB{
}
}
func (b *ConcreteNotifierB) Update(s *Subject) {
if s.status < 501 {
fmt.Printf("Status is less than 500: %v \n", s.status)
}
}
</code></pre>
<p>And here is testing:</p>
<pre><code>subject := observer.NewSubject()
concreteObserverA := observer.NewConcreteNotifierA()
concreteObserverA1 := observer.NewConcreteNotifierA()
concreteObserverB := observer.NewConcreteNotifierB()
concreteObserverB1 := observer.NewConcreteNotifierB()
subject.Attach(concreteObserverA)
subject.Attach(concreteObserverA1)
subject.Attach(concreteObserverB)
subject.Attach(concreteObserverB1)
fmt.Printf("First Scan\n")
subject.ScanData()
subject.DeAttach(concreteObserverB)
subject.DeAttach(concreteObserverA)
fmt.Printf("Second Scan\n")
subject.ScanData()
</code></pre>
<p>EDIT: Let's say the goal is on different type of "Status", different type of subscribers will be notified.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:18:30.153",
"Id": "451282",
"Score": "1",
"body": "What's that code supposed to do in practice? Elaborate please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:42:40.127",
"Id": "451284",
"Score": "0",
"body": "Let's say the goal is on different type of \"Status\", different type of subscribers will be notified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:45:08.237",
"Id": "451285",
"Score": "1",
"body": "Your code looks quite hypothetical. Please post real code here for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T14:58:47.657",
"Id": "457068",
"Score": "0",
"body": "Typo: **Detach**, not DeAttach."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T17:07:12.227",
"Id": "231383",
"Score": "1",
"Tags": [
"go",
"observer-pattern"
],
"Title": "Observer Design Pattern in Golang"
}
|
231383
|
<p>I have computed the Daubechies wavelet and scaling filters in <code>float</code>, <code>double</code>, <code>long double</code>, and <code>quad</code> precision, and now want to expose these filters in a usable API. My problem is as follows: I want to make sure that these filters are correct to every single bit, so I wrote them as hexadecimal floating point literals. Then I wanted to get them to parse in the correct format, so I need to append literals like <code>f</code>, <code>L</code>, or <code>Q</code>. But to get them to parse as the correct type, I need to duplicate them over and over, resulting in a monstrous <code>#include</code> file, given <a href="https://github.com/boostorg/math/blob/d7e4bf780b496cbd6140d06cccba3f0374ae9d78/include/boost/math/filters/daubechies.hpp" rel="nofollow noreferrer">here</a></p>
<p>The file is too big to place in the question, but here's a short sample:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef BOOST_MATH_FILTERS_DAUBECHIES_HPP
#define BOOST_MATH_FILTERS_DAUBECHIES_HPP
#include <array>
#ifdef BOOST_HAS_FLOAT128
#include <boost/multiprecision/float128.hpp>
#endif
namespace boost::math::filters {
template <typename Real, unsigned p>
constexpr std::array<Real, 2*p> daubechies_scaling_filter()
{
static_assert(sizeof(Real) <= 16, "Filter coefficients only computed up to 128 bits of precision.");
static_assert(p < 25, "Filter coefficients only implemented up to 24.");
if constexpr (p == 1) {
if constexpr (std::is_same_v<Real, float>) {
return {0x1.6a09e6p-1f, 0x1.6a09e6p-1f};
}
if constexpr (std::is_same_v<Real, double>) {
return {0x1.6a09e667f3bcdp-1, 0x1.6a09e667f3bcdp-1};
}
if constexpr (std::is_same_v<Real, long double>) {
return {0xb.504f333f9de6484p-4L, 0xb.504f333f9de6484p-4L};
}
#ifdef BOOST_HAS_FLOAT128
if constexpr (std::is_same_v<Real, boost::multiprecision::float128>) {
return {0x1.6a09e667f3bcc908b2fb1366ea95p-1Q, 0x1.6a09e667f3bcc908b2fb1366ea95p-1Q};
}
#endif
}
if constexpr (p == 2) {
if constexpr (std::is_same_v<Real, float>) {
return {0x1.ee8dd4p-2f, 0x1.ac4bdep-1f, 0x1.cb0bfp-3f, -0x1.0907dcp-3f};
}
if constexpr (std::is_same_v<Real, double>) {
return {0x1.ee8dd4748bf15p-2, 0x1.ac4bdd6e3fd71p-1, 0x1.cb0bf0b6b7109p-3, -0x1.0907dc193069p-3};
}
if constexpr (std::is_same_v<Real, long double>) {
return {0xf.746ea3a45f8a62ap-5L, 0xd.625eeb71feb8557p-4L, 0xe.585f85b5b8845bdp-6L, -0x8.483ee0c9834834cp-6L};
}
#ifdef BOOST_HAS_FLOAT128
if constexpr (std::is_same_v<Real, boost::multiprecision::float128>) {
return {0x1.ee8dd4748bf14c548b969de58fap-2Q, 0x1.ac4bdd6e3fd70aae9f48d8a63d1bp-1Q, 0x1.cb0bf0b6b7108b79b4bf11d08b16p-3Q, -0x1.0907dc1930690697b13714fd4a15p-3Q};
}
#endif
}
...
template<class Real, size_t p>
std::array<Real, 2*p> daubechies_wavelet_filter() {
std::array<Real, 2*p> g;
auto h = daubechies_scaling_filter<Real, p>();
for (size_t i = 0; i < g.size(); i += 2)
{
g[i] = h[g.size() - i - 1];
g[i+1] = -h[g.size() - i - 2];
}
return g;
}
</code></pre>
<p>Is there a way to only state the filter coefficients once, with the maximum allowed precision, and have the compiler parse it as the user's desired type, and preserve the <code>constexpr</code>?</p>
<p>Is keep the filter coefficients <code>constexpr</code> a sensible desideratum here? (I'm not even sure that I should make <code>p</code> a template parameter. . .) If so, note that the scaling filters are <code>constexpr</code>, but the wavelet filters are not. Is there a way around that?</p>
<p>C++17 solutions are acceptable; C++20 solutions are . . . less so, but if they can be shown to dramatically improve the code that's what language updates are for correct?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T23:09:59.123",
"Id": "451307",
"Score": "1",
"body": "@Emma: I already know they are correct."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T18:24:07.437",
"Id": "231386",
"Score": "1",
"Tags": [
"c++",
"mathematics",
"c++17"
],
"Title": "Daubechies wavelet and scaling filters: Is there a better way?"
}
|
231386
|
<p>Just wondering how I can go about doing this more efficiently/make it more visually appealing to the user?</p>
<pre><code> switch (this.state.selected) {
case "all":
styled = this.state.allKeywords.map(keyword =>
<div style={{display: "flex", flexDirection: "row"}}>
<Input key={Math.random} style={{height: "45px", marginBottom: "20px"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>
<Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: "45px", marginLeft: "30px"}}>Delete</Button>
</div>
);
break;
case "positive":
styled = this.state.positive.map(keyword =>
<div style={{display: "flex", flexDirection: "row"}}>
<Input key={Math.random} style={{height: "45px", marginBottom: "20px"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>
<Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: "45px", marginLeft: "30px"}}>Delete</Button>
</div>
);
break;
case "negative":
styled = this.state.negative.map(keyword =>
<div style={{display: "flex", flexDirection: "row"}}>
<Input key={Math.random} style={{height: "45px", marginBottom: "20px"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>
<Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: "45px", marginLeft: "30px"}}>Delete</Button>
</div>
);
break;
default:
console.log("No keyword list mapped");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T03:18:19.573",
"Id": "451311",
"Score": "1",
"body": "Repeated code—make it a function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T11:34:54.973",
"Id": "451334",
"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": "<p>If by this question you mean you want to prettify your code then Google \"javascript prettify\" and you will get numerous hits. For example, I picked the first one, <a href=\"https://beautifier.io/\" rel=\"nofollow noreferrer\">Online JavaScript Beautifier</a> and it did the following to your example with a few clicks. You can adjust the parameters of the prettifier to suit your needs. BTW this web site also mentions a Chrome plugin specifically aimed at prettifying code in Stack Overflow posts.</p>\n\n<pre><code>switch (this.state.selected) {\n case \"all\":\n styled = this.state.allKeywords.map(keyword =>\n <\n div style = {\n {\n display: \"flex\",\n flexDirection: \"row\"\n }\n } >\n <\n Input key = {\n Math.random\n }\n style = {\n {\n height: \"45px\",\n marginBottom: \"20px\"\n }\n }\n onClick = {\n this.onKeywordClick\n }\n value = {\n keyword\n }\n onChange = {\n this.onKeywordChange\n } > < /Input> <\n Button key = {\n Math.random\n }\n onClick = {\n () => this.deleteKeyword(keyword)\n }\n style = {\n {\n height: \"45px\",\n marginLeft: \"30px\"\n }\n } > Delete < /Button> <\n /div>\n );\n break;\n case \"positive\":\n styled = this.state.positive.map(keyword =>\n <\n div style = {\n {\n display: \"flex\",\n flexDirection: \"row\"\n }\n } >\n <\n Input key = {\n Math.random\n }\n style = {\n {\n height: \"45px\",\n marginBottom: \"20px\"\n }\n }\n onClick = {\n this.onKeywordClick\n }\n value = {\n keyword\n }\n onChange = {\n this.onKeywordChange\n } > < /Input> <\n Button key = {\n Math.random\n }\n onClick = {\n () => this.deleteKeyword(keyword)\n }\n style = {\n {\n height: \"45px\",\n marginLeft: \"30px\"\n }\n } > Delete < /Button> <\n /div>\n );\n break;\n case \"negative\":\n styled = this.state.negative.map(keyword =>\n <\n div style = {\n {\n display: \"flex\",\n flexDirection: \"row\"\n }\n } >\n <\n Input key = {\n Math.random\n }\n style = {\n {\n height: \"45px\",\n marginBottom: \"20px\"\n }\n }\n onClick = {\n this.onKeywordClick\n }\n value = {\n keyword\n }\n onChange = {\n this.onKeywordChange\n } > < /Input> <\n Button key = {\n Math.random\n }\n onClick = {\n () => this.deleteKeyword(keyword)\n }\n style = {\n {\n height: \"45px\",\n marginLeft: \"30px\"\n }\n } > Delete < /Button> <\n /div>\n );\n break;\n default:\n console.log(\"No keyword list mapped\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T04:05:37.000",
"Id": "451312",
"Score": "0",
"body": "Hey, really appreciate this and will definitely put it to use. Although, is there a more efficient way to improve what my code actually does?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T01:50:00.900",
"Id": "231392",
"ParentId": "231391",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Simple change to improve would be to extract the repeated peace in separate component:</li>\n</ol>\n\n<pre><code><div style={{display: \"flex\", flexDirection: \"row\"}}>\n <Input key={Math.random} style={{height: \"45px\", marginBottom: \"20px\"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>\n <Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: \"45px\", marginLeft: \"30px\"}}>Delete</Button>\n</div>\n</code></pre>\n\n<ol start=\"2\">\n<li>You are incorrectly using key property on your components, I suggest you read the documentation on <a href=\"http://reactjs.org/docs/lists-and-keys.html#keys\" rel=\"nofollow noreferrer\">the keys in lists in react</a>\nand see this <a href=\"https://stackoverflow.com/questions/29808636/when-giving-unique-keys-to-components-is-it-okay-to-use-math-random-for-gener\">stackoverflow question</a> on why not use Math.random() as key.</li>\n</ol>\n\n<p>You are also using <code>key={Math.random}</code> which is reference to the <code>Math.random</code> function rather than random value, though neither make sense.</p>\n\n<ol start=\"3\">\n<li>As mentioned in one of the comments and another answer, code style is much easier to maintain using automated tools. Most modern code editors support code formatting.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:33:24.820",
"Id": "231415",
"ParentId": "231391",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T23:25:35.560",
"Id": "231391",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "Check which state is activated and render the JSX accordingly"
}
|
231391
|
<pre><code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
</code></pre>
<h2>The <code>MessageBroker</code> Class</h2>
<p>Contains thread-safe structures to hold mappings of message types to handlers. Dispatches messages
to those handlers. Supports messages with and without replies.</p>
<pre><code> public class MessageBroker
{
public ConcurrentDictionary<(string name, Type message), ConcurrentBag<WeakReference<BrokeredMessageHandler>>> BrokeredMessageHandlers =
new ConcurrentDictionary<(string name, Type message), ConcurrentBag<WeakReference<BrokeredMessageHandler>>>();
public ConcurrentDictionary<(string name, Type message), ConcurrentBag<WeakReference<BrokeredMessageWithReplyHandler>>> BrokeredMessageWithReplyHandlers =
new ConcurrentDictionary<(string name, Type message), ConcurrentBag<WeakReference<BrokeredMessageWithReplyHandler>>>();
private static MessageBroker _instance;
public static MessageBroker Instance => _instance ?? (_instance = new MessageBroker());
public async Task Send(
IBrokeredMessageBase message
, Action<Guid> sent = null
, Action<Guid> complete = null
, CancellationToken cancellationToken = default)
{
var key = (message.MessageName, message.GetType());
if (BrokeredMessageHandlers.ContainsKey(key))
{
var subscribers = BrokeredMessageHandlers[key].ToImmutableList();
var tasks = new List<Task>();
subscribers.ForEach(s => tasks.Add(Task.Factory.StartNew(() =>
{
if (s.TryGetTarget(out var target) && !cancellationToken.IsCancellationRequested) target(message);
}, cancellationToken)));
if (!cancellationToken.IsCancellationRequested)
{
sent?.Invoke(message.MessageUID);
await Task.Run(() => { Task.WaitAll(tasks.ToArray(), cancellationToken); }, cancellationToken);
if (!cancellationToken.IsCancellationRequested)
{
complete?.Invoke(message.MessageUID);
}
}
}
}
public async Task SendWithReply(
BrokeredMessageWithReplyBase message
, Action<Guid> sent = null
, Action<Guid> complete = null
, CancellationToken cancellationToken = default)
{
var key = (message.MessageName, message.GetType());
if (BrokeredMessageWithReplyHandlers.ContainsKey(key))
{
var subscribers = BrokeredMessageWithReplyHandlers[key].ToImmutableList();
var tasks = new List<Task>();
subscribers.ForEach(s => tasks.Add(new Task(() =>
{
if (s.TryGetTarget(out var target)) target(message);
})));
if (!cancellationToken.IsCancellationRequested)
{
sent?.Invoke(message.MessageUID);
await Task.Run(() => { Task.WaitAll(tasks.ToArray(), cancellationToken); }, cancellationToken);
if (!cancellationToken.IsCancellationRequested)
{
complete?.Invoke(message.MessageUID);
}
}
}
}
public void AddHandler(string messageName, Type messageType, BrokeredMessageHandler brokeredMessageHandler)
{
var key = (messageName, messageType);
BrokeredMessageHandlers.TryGetValue(key, out var bag);
if (bag == null)
{
bag = new ConcurrentBag<WeakReference<BrokeredMessageHandler>>();
BrokeredMessageHandlers.TryAdd(key, bag);
}
var reference = new WeakReference<BrokeredMessageHandler>(brokeredMessageHandler);
if (!bag.Contains(reference))
{
bag.Add(reference);
}
}
public void AddHandlerWithReply(string messageName, Type messageType, BrokeredMessageWithReplyHandler brokeredMessageWithReplyHandler)
{
var key = (messageName, messageType);
BrokeredMessageWithReplyHandlers.TryGetValue(key, out var bag);
if (bag == null)
{
bag = new ConcurrentBag<WeakReference<BrokeredMessageWithReplyHandler>>();
BrokeredMessageWithReplyHandlers.TryAdd(key, bag);
}
var reference = new WeakReference<BrokeredMessageWithReplyHandler>(brokeredMessageWithReplyHandler);
if (!bag.Contains(reference))
{
bag.Add(reference);
}
}
}
</code></pre>
<h2><code>BrokeredMessageHandler</code> & <code>BrokeredMessageWithReplyHandler</code></h2>
<p>Delegates for dispatching the messages to.</p>
<pre><code> public delegate void BrokeredMessageHandler(IBrokeredMessageBase message);
public delegate void BrokeredMessageWithReplyHandler(BrokeredMessageWithReplyBase message);
</code></pre>
<h2>Messages (Without Reply)</h2>
<ul>
<li><code>IBrokeredMessageBase</code> is the base interface for all Brokered Messages</li>
<li><code>BrokeredMessageBase</code> abstract class providing basic implementation.</li>
<li><code>BrokeredMessage<TParameter></code> Generic Parameterized Brokered Message.</li>
<li><code>BrokeredMessage</code> non-Generic Parameterized Brokered Message.</li>
</ul>
<pre><code> public interface IBrokeredMessageBase
{
string MessageName { get; }
Guid MessageUID { get; }
DateTimeOffset TimestampUTC { get; }
}
public abstract class BrokeredMessageBase : IBrokeredMessageBase
{
public string MessageName { get; }
public Guid MessageUID { get; }
public DateTimeOffset TimestampUTC { get; } = DateTimeOffset.UtcNow;
protected BrokeredMessageBase(string name, Guid uid = default)
{
MessageName = name;
MessageUID = uid != default ? uid : Guid.NewGuid();
}
}
public class BrokeredMessage<TParameter> : BrokeredMessageBase
{
public TParameter Parameter { get; }
public BrokeredMessage(TParameter parameter, string name, Guid uid = default) : base(name, uid)
{
Parameter = parameter;
}
}
public class BrokeredMessage : BrokeredMessageBase
{
public object Parameter { get; }
public BrokeredMessage(object parameter, string name, Guid uid = default) : base(name, uid)
{
Parameter = parameter;
}
}
</code></pre>
<h2>Messages (With Reply)</h2>
<ul>
<li><code>BrokeredMessageWithReplyBase</code> abstract class providing basic implementation.</li>
<li><code>BrokeredMessageWithReply<TParameter></code> Generic Parameterized Brokered Message.</li>
<li><code>BrokeredMessageWithReply</code> non-Generic Parameterized Brokered Message.</li>
</ul>
<pre><code> public abstract class BrokeredMessageWithReplyBase : BrokeredMessageBase
{
public ConcurrentBag<object> Replies { get; }
protected BrokeredMessageWithReplyBase(string name, Guid uid = default) : base(name, uid)
{
Replies = new ConcurrentBag<object>();
}
}
public class BrokeredMessageWithReply<TParameter> : BrokeredMessageBase
{
public TParameter Parameter { get; }
public BrokeredMessageWithReply(TParameter parameter, string name, Guid uid = default) : base(name, uid)
{
Parameter = parameter;
}
}
public class BrokeredMessageWithReply : BrokeredMessageBase
{
public object Parameter { get; }
public BrokeredMessageWithReply(object parameter, string name, Guid uid = default) : base(name, uid)
{
Parameter = parameter;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong><code>MessageBroker</code></strong> </p>\n\n<ul>\n<li>Both public <code>BrokeredMessageHandlers</code> and <code>BrokeredMessageWithReplyHandlers</code> should be <code>readonly</code> because you don't want that someone sets them to <code>null</code> from outside of the class. </li>\n<li>For both method names <code>public async Task Send()</code> and <code>public async Task SendWithReply()</code> the suffix <code>Async</code> should be appended. See: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/async#important-info-and-advice\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/async#important-info-and-advice</a></li>\n<li><p>If you need to get a value of a <code>Dictionary<TKey, TValue></code> you shouldn't us <code>ContainsKey()</code> together with the <code>Item</code> property getter but <code>TryGetValue()</code>, because by using <code>ContainsKey()</code> in combination with the <code>Item</code> getter you are doing the check if the key exists twice.<br>\nFrom the <a href=\"https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs\" rel=\"nofollow noreferrer\">refernce source</a> </p>\n\n<pre><code>public bool ContainsKey(TKey key)\n{\n if (key == null) throw new ArgumentNullException(\"key\");\n\n TValue throwAwayValue;\n return TryGetValue(key, out throwAwayValue);\n}\n\npublic TValue this[TKey key]\n{\n get\n {\n TValue value;\n if (!TryGetValue(key, out value))\n {\n throw new KeyNotFoundException();\n }\n return value;\n }\n set\n {\n if (key == null) throw new ArgumentNullException(\"key\");\n TValue dummy;\n TryAddInternal(key, value, true, true, out dummy);\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T07:21:32.823",
"Id": "231401",
"ParentId": "231393",
"Score": "2"
}
},
{
"body": "<p>It is difficult to review something without understanding the scenario it is going to be used in. So, please regard this as just some random thoughts which may or may not be relevant:</p>\n\n<ol>\n<li>Waiting inside <code>Task.Run</code> is almost never a good idea. You consume a thread from a thread pool to do nothing. Try using an event loop if possible.</li>\n<li>In <code>SendWithReply</code> I don't see where the tasks are run. Also it looks like it copies a lot of code from <code>Send</code></li>\n<li><code>AddHandler</code> is not thread-safe. If two threads write to the same key, one might fail and never know about it</li>\n<li>Can't think of any use for the Sent callback, because by the time it is called the tasks might have already been finished</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T11:26:50.083",
"Id": "231403",
"ParentId": "231393",
"Score": "2"
}
},
{
"body": "<p>Here is the updated code based on feedback:</p>\n\n<pre><code>using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Boltron.UI.UWP.Commands\n{\n public class MessageBroker\n {\n private readonly ConcurrentDictionary<(string name, Type message), ConcurrentBag<Action<IBrokeredMessage>>> _brokeredMessageHandlers =\n new ConcurrentDictionary<(string name, Type message), ConcurrentBag<Action<IBrokeredMessage>>>();\n\n private readonly ConcurrentDictionary<(string name, Type message), ConcurrentBag<Action<IBrokeredMessageWithReply>>> _brokeredMessageWithReplyHandlers =\n new ConcurrentDictionary<(string name, Type message), ConcurrentBag<Action<IBrokeredMessageWithReply>>>();\n\n public static MessageBroker Instance { get; } = new MessageBroker();\n\n public async Task SendAsync(\n IBrokeredMessage message\n , Action<Guid> sent = null\n , Action<Guid> complete = null\n , CancellationToken cancellationToken = default)\n {\n var key = (message.MessageName, message.GetType());\n\n if (_brokeredMessageHandlers.TryGetValue(key, out var bag))\n {\n var subscribers = bag.ToImmutableList();\n\n await SendMessageAsync(message, subscribers, sent, complete, cancellationToken);\n }\n }\n\n public async Task SendWithReplyAsync(\n IBrokeredMessageWithReply message\n , Action<Guid> sent = null\n , Action<Guid> complete = null\n , CancellationToken cancellationToken = default)\n {\n var key = (message.MessageName, message.GetType());\n\n if (_brokeredMessageWithReplyHandlers.TryGetValue(key, out var bag))\n {\n var subscribers = bag.Cast<Action<IBrokeredMessage>>().ToImmutableList();\n\n await SendMessageAsync(message, subscribers, sent, complete, cancellationToken);\n }\n }\n\n private async Task SendMessageAsync(\n IBrokeredMessage message\n , ImmutableList<Action<IBrokeredMessage>> subscribers\n , Action<Guid> sent = null\n , Action<Guid> complete = null\n , CancellationToken cancellationToken = default)\n {\n var tasks = new List<Task>();\n\n subscribers.ForEach(s => tasks.Add(Task.Factory.StartNew(() =>\n {\n if (s != null && !cancellationToken.IsCancellationRequested)\n {\n s(message);\n }\n }, cancellationToken)));\n\n if (!cancellationToken.IsCancellationRequested)\n {\n sent?.Invoke(message.MessageUid);\n\n await Task.Run(\n () => Task.WaitAll(tasks.ToArray(), cancellationToken)\n , cancellationToken);\n\n if (!cancellationToken.IsCancellationRequested)\n {\n complete?.Invoke(message.MessageUid);\n }\n }\n\n }\n\n public void AddHandler(string messageName\n , Type messageType\n , Action<IBrokeredMessage> brokeredMessageHandler)\n {\n var key = (messageName, messageType);\n\n _brokeredMessageHandlers.TryGetValue(key, out var bag);\n\n if (bag == null)\n {\n bag = new ConcurrentBag<Action<IBrokeredMessage>>();\n _brokeredMessageHandlers.TryAdd(key, bag);\n }\n\n if (!bag.Contains(brokeredMessageHandler))\n {\n bag.Add(brokeredMessageHandler);\n }\n }\n\n public void AddHandlerWithReply(string messageName\n , Type messageType\n , Action<IBrokeredMessageWithReply> brokeredMessageWithReplyHandler)\n {\n var key = (messageName, messageType);\n\n _brokeredMessageWithReplyHandlers.TryGetValue(key, out var bag);\n\n if (bag == null)\n {\n bag = new ConcurrentBag<Action<IBrokeredMessageWithReply>>();\n _brokeredMessageWithReplyHandlers.TryAdd(key, bag);\n }\n\n if (!bag.Contains(brokeredMessageWithReplyHandler))\n {\n bag.Add(brokeredMessageWithReplyHandler);\n }\n }\n }\n\n public interface IBrokeredMessage\n {\n string MessageName { get; }\n Guid MessageUid { get; }\n DateTimeOffset TimestampUtc { get; }\n }\n\n public abstract class BrokeredMessageBase : IBrokeredMessage\n {\n public string MessageName { get; }\n public Guid MessageUid { get; }\n public DateTimeOffset TimestampUtc { get; } = DateTimeOffset.UtcNow;\n\n protected BrokeredMessageBase(string name, Guid uid = default)\n {\n MessageName = name;\n MessageUid = uid != default ? uid : Guid.NewGuid();\n }\n }\n\n public class BrokeredMessage<TParameter> : BrokeredMessageBase\n {\n public TParameter Parameter { get; }\n public BrokeredMessage(TParameter parameter, string name, Guid uid = default) : base(name, uid)\n {\n Parameter = parameter;\n }\n }\n\n public class BrokeredMessage : BrokeredMessageBase\n {\n public object Parameter { get; }\n public BrokeredMessage(object parameter, string name, Guid uid = default) : base(name, uid)\n {\n Parameter = parameter;\n }\n }\n\n public interface IBrokeredMessageWithReply : IBrokeredMessage\n {\n\n }\n\n public abstract class BrokeredMessageWithReplyBase<TReturn> : BrokeredMessageBase, IBrokeredMessageWithReply\n {\n private readonly object _owner;\n private ConcurrentBag<TReturn> Replies { get; }\n\n protected BrokeredMessageWithReplyBase(string name, object owner, Guid uid = default) : base(name, uid)\n {\n _owner = owner;\n Replies = new ConcurrentBag<TReturn>();\n }\n\n public void AddReply(TReturn reply)\n {\n Replies.Add(reply);\n }\n\n public IEnumerable<TReturn> GetReplies(object claimant)\n {\n if (claimant != _owner) yield break;\n\n foreach (var item in Replies)\n {\n yield return item;\n }\n }\n }\n\n public class BrokeredMessageWithReply<TParameter, TReturn> : BrokeredMessageWithReplyBase<TReturn>\n {\n public TParameter Parameter { get; }\n public BrokeredMessageWithReply(TParameter parameter, string name, Guid uid = default) : base(name, uid)\n {\n Parameter = parameter;\n }\n }\n\n public class BrokeredMessageWithReply<TReturn> : BrokeredMessageWithReplyBase<TReturn>\n {\n public object Parameter { get; }\n public BrokeredMessageWithReply(object parameter, string name, Guid uid = default) : base(name, uid)\n {\n Parameter = parameter;\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:45:11.917",
"Id": "231460",
"ParentId": "231393",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T02:23:31.810",
"Id": "231393",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Pub-Sub MessageBroker in C# for all Dotnet Platforms"
}
|
231393
|
<p>I am currently creating a website for an artist (my grandfather). My main concern with the code below is readability, as for the most part I have not worked with others on a (programming) project. I use a few external modules but hopefully their purpose is obvious/irrelevant. </p>
<p>I have been programming with javascript as a hobby for about two years. </p>
<p>Here is my code:</p>
<pre class="lang-js prettyprint-override"><code>const express = require('express')
const app = express()
const fs = require('fs')
const gzip = require('express-gzip')
const handleRequest = require('./handleRequest')
const verify = require('../Admin/login').verify
app.use(gzip)
app.use(express.json())
app.get(['/bio', '/contact', '/login', '/works', '/404', '/bug', '/edit-bio', '/edit-works'], (req, res) => verify(req.query.token).then(result => fs.readFile((req.path === '/edit-bio' || req.path === '/edit-works' ? result : true) ? ((result && req.path === '/login') ? '../../Frontend/html/edit-works.html' : `../../Frontend/html${req.path}.html`) : '../../Frontend/html/login.html', (err, data) => err ? res.status(500).end() : res.end(data))))
app.get('/', (_req, res) => fs.readFile('../../Frontend/index.html', (err, data) => err ? res.status(500).end() : res.end(data)))
app.post(/.+/, (req, res) => handleRequest[req.body.type](req.body).then(result => result.err ? res.status(500).end(JSON.stringify(result.data)) : res.end(JSON.stringify(result.data))))
app.use('/html', (_req, res) => res.status(404).redirect('/404'))
app.use(express.static('../../Frontend'))
app.use((_req, res) => (res.status(404).redirect('/404'))).listen(8080)
</code></pre>
<p>This is a simple express server that answers get requests on: <code>'/bio'</code>, <code>'/contact'</code>, <code>'/login'</code>, etc. If the request is to <code>'/edit-bio'</code> or <code>'/edit-works'</code> it verifies a jwt provided in the query string. If it receives a post request of any kind it runs a function corresponding to a <code>type</code> property in that request. It also has a simple 404 page. Finally it uses <code>express.static</code> on a <code>Frontend</code> folder containing the css, js, html, etc. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T06:47:09.680",
"Id": "451320",
"Score": "0",
"body": "What's the deal with lines of code hundreds of characters wide? That ruins the readability in many circumstances (like here). Also, usually you wouldn't manually be comparing a lot of paths in your routes. Instead, use your route definitions to focus on a specific route and then if you want to share code between routes, either use middleware or call shared functions from different route handlers. You don't typically want to see `app.get([...])` with a whole bunch of separate paths for the same route and then code inside the route handler to separate out the routes. Make different routes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T06:51:08.800",
"Id": "451321",
"Score": "0",
"body": "And, you can probably use `express.static()` in one middleware configuration for all your static routes rather than manually doing `fs.readFile()` and `res.end()` for each one separately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T23:11:33.427",
"Id": "451410",
"Score": "0",
"body": "@jfriend00 are you saying that I should use `express.static()` and then reroute the requests to the paths to the HTML file? And then replace `app.use('/html', (_req, res) => res.status(404).redirect('/404'))` with `app.use(['/html/edit-bio', '/html/edit-works'], (_req, res) => res.status(404).redirect('/404'))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:09:04.467",
"Id": "451414",
"Score": "0",
"body": "Let's just start by you should increase the readability of the `app.get(['/bio', '/contact', '/login', '/works', '/404', '/bug', '/edit-bio', '/edit-works'] ...` line of code. Even after putting it into an editor and breaking it into multiple lines, it still isn't obvious to me what that line does except that it's got multiple checks for various paths which means you aren't taking advantage of the simplicity of using separate route declarations for separate paths. And, I can't imagine how one would add three more routes to it without a pretty good change of breaking something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:09:18.263",
"Id": "451415",
"Score": "0",
"body": "Maybe if I have a lot more patience sometime in the future, I'll finally figure out what that line is supposed to do an rewrite it into separate routes or figure out what can just be done with `express.static()`. But, the MAIN point is that that line is not easily readable. Probably several different approaches to simplify it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:11:20.290",
"Id": "451416",
"Score": "0",
"body": "To simplify that line, I'd need to know what `verify()` does? Does it reject? Does it send a response under any conditions? What is the result for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:37:18.923",
"Id": "451417",
"Score": "0",
"body": "`verify()` is a function that verifies a json web token. It will either return true or false depending on whether or not the token is valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:51:19.917",
"Id": "451418",
"Score": "0",
"body": "So, at least separate into different route definitions the paths that care about calling `verify()` from the paths that don't. And, I don't see why you can't use `express.static()` for these routes: `['/bio', '/contact', '/login', '/works', '/404', '/bug'],`. They don't appear to have any special processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:52:43.553",
"Id": "451419",
"Score": "0",
"body": "@jfriend00 alright, I will do that."
}
] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li><p>Rewrite the line of code <code>app.get(['/bio', '/contact', '/login', '/works', '/404', '/bug', '/edit-bio', '/edit-works'] ...</code> to be readable and maintainable and debuggable. It should likely be broken into at least two separate routes.</p></li>\n<li><p>Separate into different route definitions the paths that care about calling <code>verify()</code> and the ones that don't.</p></li>\n<li><p>Use express.static for routes that don't appear to have any special processing such as <code>['/bio', '/contact', '/login', '/works', '/404', '/bug']</code>.</p></li>\n<li><p>Use <code>res.sendFile()</code> instead of repeating this <code>err ? res.status(500).end() : res.end(data)</code> over and over again.</p></li>\n<li><p>Put your verify logic into a middleware format so it can easily be attached to any route.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:57:04.350",
"Id": "231434",
"ParentId": "231394",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231434",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T02:39:47.473",
"Id": "231394",
"Score": "1",
"Tags": [
"javascript",
"server",
"express.js"
],
"Title": "Express server for an artists website"
}
|
231394
|
<p>I wrote simple code that let users log in, see what items are available in "shop", and make a purchase if he/she has enough coins.</p>
<p>Because the code uses csv file, if you want to test the code, you will need to create one. Run following </p>
<pre><code>import csv
#Path to the folder + file name
file_path = input()
#Each sublist contains following elements:
#[username, password, coins, item1,item2,item3,......]
some_users = [
['User1','VeryStrongPassword123','999' ,*['Sword','Shield']],
['Bob' ,'123456' ,'1223',*[]],
['asdf1','12jknsdf' ,'0' ,*[]]]
#It must be an csv file.
with open(file_path,'w') as file:
csv_writer = csv.writer(file)
for row in some_users:
csv_writer.writerow(row)
</code></pre>
<p>Code itself</p>
<pre><code>import os
import csv
import pandas as pd
#Note that it must be the csv file you've just created
file_path = input()
ITEMS_DATA ={'Item': 'Price',
'Sword': 100,
'Shield': 510,
'Horse': 1200,
'Big e': 99999999}
class CSV():
def __init__(self,path):
self.path = path
def read(self):
with open(self.path) as file:
data = list(csv.reader(file))
return data
def write(self,new_data):
with open(self.path,'w') as file:
csv_writer = csv.writer(file)
for row in new_data:
csv_writer.writerow(row)
class Shop:
def __init__(self, ID):
self.ID = ID
self.username, \
self.password, \
self.coins, \
self.my_items = retrieve_user_data(ID)
self.coins = int(self.coins)
def update_data(self):
csv_file = CSV(file_path)
all_data = csv_file.read()
user_data = all_data[self.ID]
user_data_updated = [user_data[0],user_data[1],self.coins] + self.my_items
all_data[self.ID] = user_data_updated
csv_file.write(all_data)
return True
def show_all_items(self):
body = ''
for item in ITEMS_DATA:
body += f'{item:10} {ITEMS_DATA[item]} \n'
print(body)
def purchase(self,item):
if (item not in ITEMS_DATA or item == "Item"):
return "Item not found"
else:
item_cost = ITEMS_DATA[item]
if self.coins < item_cost:
return "Not enough coins"
else:
verify_purchase = input(f"You will spend {item_cost} coins. Want to proceed? Y/N \n")
if verify_purchase.lower() == 'y':
self.coins -= item_cost
self.my_items.append(item)
self.update_data()
def create_user(username,password,coins,items):
csv_file = CSV(file_path)
data = csv_file.read()
data.append([username,password,coins,*items])
csv_file.write(data)
return True
def retrieve_user_data(ID):
users_csv = CSV(file_path)
row = users_csv.read()[ID]
username,password,coins = row[:3]
items = row[3:]
return (username, password, coins, items)
def login():
users_csv = CSV(file_path)
users_data = users_csv.read()
all_usernames = [x[0] for x in users_data]
#
login = input("Username: ")
password = input("Password: ")
attempt = 0
while True:
if login in all_usernames:
user_ID = all_usernames.index(login)
if password == users_data[user_ID][1]:
return (login,password,user_ID)
else:
attempt += 1
if attempt == 3:
return False
print("Incorrect username or password. Try one more time: ")
login = input("Username: ")
password = input("Password: ")
else:
attempt += 1
if attempt == 3:
return False
print("Incorrect username or password. Try one more time: ")
login = input("Username: ")
password = input("Password: ")
if __name__ == '__main__':
login_attempt = login()
if login_attempt != False:
user_ID = login_attempt[-1]
instance_variable = Shop(user_ID)
else:
print("Log-in failed.")
</code></pre>
<p>What can be improved?</p>
<p>Written in Python 3.6.5</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T05:01:53.130",
"Id": "451314",
"Score": "0",
"body": "Is this an exercise in CSV handling or an exercise in shop building? We can work with either, but the answers could be hugely different based on your goal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T05:16:21.423",
"Id": "451317",
"Score": "0",
"body": "@Mast it's the latter. So if you have any suggestions about how to handle data without using CSV, I would be glad to hear them. I used CSV because it's the first thing that came to my mind, but I suppose there are better options available."
}
] |
[
{
"body": "<p>I'll be keeping a bit general with this. Over the whole, looks good. That means I won't be doing a line-by-line, but instead lifting out the points grabbing my attention.</p>\n\n<h3><code>if __name__ == \"__main__\":</code></h3>\n\n<p>You should <a href=\"https://stackoverflow.com/a/419185/4331885\">guard</a> your code. It's a good thing that you already have one, but not all your code is inside it. For example, there's a rogue <code>input()</code> statement above ITEMS_DATA. Just do that inside the guard as well, and feed the result to any functions that need it. </p>\n\n<h3>Naming</h3>\n\n<p>You have a <code>Shop</code> class. What data does this contain? It's attributes set in <code>__init__()</code> are: ID, username, password, coins, my_items. These aren't things about the shop, these are actually properties of the player buying the items. </p>\n\n<p>The actual shop's items are all in ITEM_DATA, which is the correctly named global. </p>\n\n<p>So if you see me refer to a <code>Player.purchase()</code> method later, you'll know what I'm referring to ;)</p>\n\n<h3><code>print()</code>ing in a class method</h3>\n\n<p>is generally a bad idea. Instead, return a string which can then be printed. Examples of methods that should really be doing this are <code>show_all_items()</code>, which really should be a function <code>get_all_items()</code> which returns a list for consumption, or <code>render_all_items()</code> which returns a string you can then print from outside. </p>\n\n<p>Same issue but different in <code>purchase()</code>, which calls <code>input()</code>. A class' methods shouldn't be about control flow, they should only handle the class' data and it's primary purpose. A pseudocode example could be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def purchase(self, item):\n if not item_exists() or not can_purchase():\n return False\n self.add_item(item)\n self.coins -= item_cost\n# Calling code:\nitem = input(\"What do you want to buy?\")\nif person.purchase(item):\n print(f\"Bought a {item}!\")\nelse:\n print(f\"Oh noes! Failed to buy {item}!\")\n</code></pre>\n\n<p>If you want to have some excersize with Exceptions instead, you could also raise a InsufficientMoneyError or ItemDoesNotError exception, and catch those in your calling code, using them to print the correct problem. But I'm at risk of veering off-topic here, and if you want a howto, ask at StackOverflow. Link it in a comment and I'll happily type it out.</p>\n\n<h3>Login security</h3>\n\n<p>I'm going to assume you're not planning on using this login system for \"real\" purposes. A long diatribe on login security would also be offtopic, I think. Just be aware that this sort of system should not go beyond private toys like this, and even then it might be worth it to factor it out a bit clearer so you can replace it with a real system if the need ever arises.</p>\n\n<h3>Generator Expressions</h3>\n\n<p>You've already used a list comprehension for all_usernames, but you aren't using this tool to it's full potential yet. <code>show_all_items()</code> comes to mind. If we were to make this a function that returns a single string, it could look like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef all_items() -> str:\n return \"\\n\".join(f\"{key: <10}:{value}\" for key, value in ITEMS_DATA.items())\n</code></pre>\n\n<p>The formatting string \"{key: <10}\" right-fills the key to length 10 with spaces. If you want both keys and values of a dict, you should use <code>dict.items()</code> to get both instead of indexing into it - it's faster, but more important it's more readable. Then we set up a generator expression - the big brother of the list comprehension - and feed that to a <code>str.join()</code> which glues them together with a newlines between every line. Then it returns the one big string, so you can just call <code>print(shop.all_items())</code> if you want to.</p>\n\n<p>Also, note the <a href=\"https://stackoverflow.com/q/136097/4331885\"><code>@staticmethod</code></a> decorator. You're not using any of the class' variables. So we don't need access. You could of course split it off, but if you feel the functionality is tied to the class in a close way, <code>@staticmethod</code> is the way to go.</p>\n\n<h3>Annotations</h3>\n\n<p>This is never <em>required</em> for Python, but it's a good habit to get into. Most importantly, it makes you think about what your functions do, and what you functions should return. Smart IDE's can also warn you about feeding in the wrong values to a function, or expecting the wrong return values. </p>\n\n<p>A minor example is in the <code>all_items()</code> method I showed upwards a bit - it shows that you should expect a string as a return value. Another would be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Union\n# ...Other Code...\ndef purchase(self, item:str) -> Union[str, None]:\n</code></pre>\n\n<p>Which shows that this function either returns a string, or None. And this begs the question - why are we returning different things? Perhaps we should refactor this function to either return strings only, or None only?</p>\n\n<p>And the answer is of course, yes we should. I'll leave that decision to you - there's no \"better practice\" which forces you to use either. My personal choice would be what I did a bit upwards, and return a bool indicating success or failure of the purchase.</p>\n\n<p>(Note for other reviewers: Yes, I could have used Optional here. But semantically, my not very humble opinion is that that should be restricted to arguments. Sue me. )</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T11:33:52.380",
"Id": "451333",
"Score": "0",
"body": "Thanks for the review! Unfortunately, I didn't get one thing: what does @staticmethod do? Seems like even if I don't use it, I still call functions from the class without instantiating it. And one more question: Would you advise to use annotations for every function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T11:36:07.447",
"Id": "451335",
"Score": "0",
"body": "`@staticmethod` technically only removes the need to have a `self` argument in the function list. More important is that is shows to any programmer reading your code that the method does not depend on any data from the object it's a method of. As always when a concept is new, [docs](https://docs.python.org/3/library/functions.html#staticmethod) are helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T11:49:32.853",
"Id": "451337",
"Score": "0",
"body": "Why should `Optional` be restricted to arguments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:40:55.827",
"Id": "451343",
"Score": "0",
"body": "@trentcl IMO, because you can refuse to give an argument with a default value of None, but even if you have a bare return, None IS still returned. You cannot refuse to return anything the way you can refuse to supply a value that has a default. |||| Now please understand that I don't advocate for language changes or anything, but to me, it makes more sense, which makes it more readable to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:56:09.690",
"Id": "451345",
"Score": "0",
"body": "I'm confused. I didn't think `Optional` had anything to do with default arguments? And in fact it is easily possible to refuse to return; `while True: pass` is a a trivial example. Anyway, shouldn't it be `Union[str, NoneType]` if the actual value is `None`? I'm still learning how type annotations work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:04:04.403",
"Id": "451346",
"Score": "1",
"body": "@trentcl None is a special case for type annotations, and it has the same effect as NoneType when used. For any X, Optional[X] is syntactically identical to Union[X, None]. So yes, Optional technically has nothing to do with default arguments, but all arguments with default values could literally be considered \"optional\". Also see [PEP484](https://www.python.org/dev/peps/pep-0484/) and [PEP526](https://www.python.org/dev/peps/pep-0484/) for more about the how and why. Note that not using Optional for return values is my personal choice only, and not a broader practice as far as I know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:23:13.450",
"Id": "451349",
"Score": "0",
"body": "Thanks, that clears things up. I disagree with your choice, since if I came across it in the wild it would confuse me (as it just did), but as long as I'm not reviewing your code, I can let it go ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T14:56:57.650",
"Id": "451355",
"Score": "0",
"body": "@Nelver I added a link about `@staticmethod` to the relevant section. It points to a stackoverflow question which explains a lot about it: https://stackoverflow.com/q/136097/4331885"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:08:12.363",
"Id": "451357",
"Score": "0",
"body": "@Gloweye, Thanks! And one more question: Would you advise to use annotations for every function? Or to put it differently, are there any guidelines on how and where to use annotations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:13:31.073",
"Id": "451358",
"Score": "0",
"body": "Bigger projects would state that in their own style guide. I'd say it's a good habit to get into for everything over 100 SLOC (Source Lines Of Code). There's no real consensus about it AFAIK aside from \"They're Useful.\" But I emphasize that I haven't done any research on that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T03:18:52.070",
"Id": "451422",
"Score": "2",
"body": "@Nelver My habit has been: all function parameters/return types should be fully annotated, as should anything else whose type may be ambiguous given the context. If I look at code and have a moment where I can't tell what types are involved, I'll add an annotation for reference. I wouldn't annotate literally every variable though. At some point the annotations become noise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:21:17.940",
"Id": "451424",
"Score": "1",
"body": "@Carcigenicate This is what I've been thinking about too. Annotations must be helpful in a lot of cases, but seems like it doesn't make sense to use them when it is obvious from the context what the type of variable must be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:25:04.960",
"Id": "451426",
"Score": "2",
"body": "@Nelver Ya. The type system is only helpful until it becomes bulky and in your way. Just appreciate the fact that Python doesn't force static typing, but also don't disregard the benefits of having known types at certain times."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T09:20:56.213",
"Id": "231402",
"ParentId": "231395",
"Score": "5"
}
},
{
"body": "<p>Your <code>Shop</code> constructor kind of threw me off guard when I read it:</p>\n\n<pre><code>def __init__(self, ID):\n self.ID = ID\n self.username, \\\n self.password, \\\n self.coins, \\\n self.my_items = retrieve_user_data(ID)\n</code></pre>\n\n<p>I find this to be very confusing to read. It isn't obvious what's going on until you get to the bottom and realize that it's a tuple deconstruction. I'd probably use an intermediate object to make it read cleaner. I'd also add type annotations:</p>\n\n<pre><code>def __init__(self, ID: str):\n self.ID: str = ID # Really, this should be lowercase, but that shadows the built-in unfortunately.\n\n username, password, raw_coins, items = retrieve_user_data(ID)\n\n self.username: str = username\n self.password: str = password\n self.coins: int = int(raw_coins)\n self.my_items: str = items\n</code></pre>\n\n<p>It makes it a little longer, but I think it reads much better.</p>\n\n<hr>\n\n<p>I think <code>purchase</code> can be improved quite a bit as well. The main thing that I see wrong with it is how you're handling errors. Returning a string message is messy. If the caller wants to know what went wrong (and handle it programmatically), they need to match the string against known message which is both slower, and more error prone than other methods.</p>\n\n<p>To fix these issues, I'd decide if I needed to handle multiple different errors, or just one error. If I only had one error, I'd change your function to return a <code>bool</code> to indicate success. You have two possible errors though that may need to be handled differently. I think the cleanest solution would be to have an enum of <code>PurchaseTransactionOutcome</code>s that lets the caller know what happened:</p>\n\n<pre><code>from enum import Enum\n\nclass PurchaseTransactionOutcome(Enum):\n ITEM_NOT_FOUND = 0\n INSUFFICIENT_COINS = 1\n CANCELLED_BY_USER = 2\n SUCCESS = 3\n</code></pre>\n\n<p>The benefits of this are it'll be faster (although that's not likely an issue in most cases), and it's more self documenting. If the user sees that the method returns a <code>PurchaseTransactionOutcome</code>, they can easily check to see what all of the possible outcomes are that they'll need to handle. It also prevents typos. If you typed the string wrong in either the method or the calling code, any checks against a certain outcome would fail. Enums can't lead to silent typos though. <code>PurchaseTransactionOutcome.INSUFICIENT_COINS</code> would cause a error before the code even runs. </p>\n\n<p>And to handle the nesting, I'd just switch to <code>elifs</code>. After making the above changes, I'd write this method closer to:</p>\n\n<pre><code>def purchase(self, item) -> PurchaseTransactionOutcome:\n if (item not in ITEMS_DATA or item == \"Item\"):\n return PurchaseTransactionOutcome.ITEM_NOT_FOUND\n\n else:\n item_cost = ITEMS_DATA[item]\n if self.coins < item_cost:\n return PurchaseTransactionOutcome.INSUFFICIENT_COINS\n\n else:\n verify_purchase = input(f\"You will spend {item_cost} coins. Want to proceed? Y/N \\n\")\n if verify_purchase.lower() == 'y':\n self.coins -= item_cost\n self.my_items.append(item)\n self.update_data()\n return PurchaseTransactionOutcome.SUCCESS\n\n else:\n return PurchaseTransactionOutcome.CANCELLED_BY_USER\n</code></pre>\n\n<p>Yes, for your case here, this is gross overkill. It is something to keep in mind though once you start writing more \"real\" code.</p>\n\n<p>Now to check for success, you can write:</p>\n\n<pre><code>result = user.purchase(\"sword\")\n\nif result != PurchaseTransactionOutcome.SUCCESS:\n . . . # Figure out what error and handle it\n</code></pre>\n\n<hr>\n\n<p>In <code>ITEMS_DATA</code>, for some reason you're storing header names inside the \"database\". This is forcing you to do weird things like <code>... or item == \"Item\"</code> checks. I'm guessing you're doing this to help <code>show_all_items</code>. I would take the header names out and just have <code>show_all_items</code> handle that:</p>\n\n<pre><code>ITEMS_DATA = {'Sword': 100,\n 'Shield': 510,\n 'Horse': 1200,\n 'Big e': 99999999}\n\ndef show_all_items(self):\n body = f'{\"Name\":10} Price\\n'\n for item_name, price in ITEMS_DATA.items():\n body += f'{item_name:10} {price} \\n'\n print(body)\n</code></pre>\n\n<p>Or to avoid duplication, you can add the headers right before the data is iterated over:</p>\n\n<pre><code>def show_all_items(self):\n body = ''\n for item_name, price in [[\"Name\", \"Price\"]] + list(ITEMS_DATA.items()):\n body += f'{item_name:10} {price} \\n'\n print(body)\n</code></pre>\n\n<p>I agree with @Gloweye though, all these methods shouldn't be printing. Ideally, all the data a function needs should be taken in as parameters, and all the data that a function produces should be simply returned. <em>Eventually</em> you need to call <code>input</code> and <code>print</code> <em>somewhere</em>, but be choosy where that somewhere is. Calling functions like <code>print</code> and <code>input</code> in arbitrary spots will make it more difficult to adapt to changed later because you've baked into your code exactly how the program is able to take and produce data. If you switch to a full UI later, you're going to have to go around and change every function that calls <code>print</code> and <code>input</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:18:21.763",
"Id": "451423",
"Score": "0",
"body": "Thanks for you review! May I ask you why you used `Enum` when creating `PurchaseTransactionOutcome`? I just tried to create the same class without using Enum, and I don't observe any difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:30:36.543",
"Id": "451427",
"Score": "0",
"body": "And one more: suppose that instead of class we would use something like this `PurchaseTransactionOutcome = {'ITEM_NOT_FOUND': 0,\n 'INSUFFICIENT_COINS': 1,\n 'CANCELLED_BY_USER': 2,\n 'SUCCESS': 3}`. Why would that be a bad idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:33:26.617",
"Id": "451428",
"Score": "0",
"body": "@Nelver An enum represents a closed set of possible states. It is entirely possible to *mostly* emulate an enum using loose variables and still get many of the benefits. Inheriting from `enum` is just a shortcut that gives you some free functionality. You can more easily test if a member is a part of an enum, and you get some formatting help when stringifying your enum. It's not necessary, but it can be helpful. If you read over the docs for `Enum`, you can see all that is adds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:34:36.057",
"Id": "451429",
"Score": "0",
"body": "@Nelver And it wouldn't be a bad idea; that's actually how I emulate enumerations when I'm writing Clojure. It works fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:42:33.853",
"Id": "451430",
"Score": "1",
"body": "@Nelver Sorry, I should also add, using a dictionary is fine, but it doesn't give you advance warning of typos. If you type an enum wrong, you'll get warnings from your IDE before your code is even run. If you use a dictionary and type a key wrong though, you'll get a key error at runtime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:50:42.247",
"Id": "451431",
"Score": "0",
"body": "@Carcigenate, so at the end of the day, class would be a better choice, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:53:48.633",
"Id": "451432",
"Score": "0",
"body": "@Nelver If the language supports enums, they're usually the better choice if you're trying to represent a small static set of possible options. Java for example has a built-in `enum` keyword to create enumerations. They're an important concept to be familiar with."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T23:00:55.107",
"Id": "231428",
"ParentId": "231395",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231402",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T02:42:49.620",
"Id": "231395",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"game"
],
"Title": "Hypothetical in-game shop: Python"
}
|
231395
|
<p>I implemented a simple solution to the <a href="https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem" rel="nofollow noreferrer">Producer–consumer problem
</a> that I'd love for you to take a look at.</p>
<p>The producer simply adds random numbers to a queue and the consumer (from a separate thread) pops numbers off the queue and prints them. I'd specifically like feedback on the concurrency aspects of this implementation. Thanks!</p>
<pre class="lang-py prettyprint-override"><code>from collections import deque
import random
import threading
TIMES = 100
class SafeQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = deque([])
self.remaining_space = threading.Semaphore(capacity)
self.fill_count = threading.Semaphore(0)
def append(self, item):
self.remaining_space.acquire()
self.queue.append(item)
self.fill_count.release()
def consume(self):
self.fill_count.acquire()
item = self.queue.popleft()
self.remaining_space.release()
return item
class Producer:
def __init__(self, queue, times=TIMES):
self.queue = queue
self.times = times
def run(self):
for _ in range(self.times):
self.queue.append(random.randint(0, 100))
class Consumer:
def __init__(self, queue, times=TIMES):
self.queue = queue
self.times = times
def run(self):
for _ in range(self.times):
print(self.queue.consume())
def main():
queue = SafeQueue(10)
producer = Producer(queue)
producer_thread = threading.Thread(target=producer.run)
consumer = Consumer(queue)
consumer_thread = threading.Thread(target=consumer.run)
producer_thread.start()
consumer_thread.start()
producer_thread.join()
consumer_thread.join()
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T09:10:33.053",
"Id": "451326",
"Score": "0",
"body": "I dont do much multi-thread processing but from how your code reads it is clean and efficient"
}
] |
[
{
"body": "<p>Actually, the initial <em>producer-consumer</em> scheme is over-complicated and has the following issues:</p>\n\n<p><strong><em>Using 2 separate <code>threading.Semaphore</code> objects</em></strong>:<br>\nOne of them is used for <em>producer</em> (<code>remaining_space</code>), another - for <em>consumer</em> (<code>fill_count</code>). <br>Though they won't be convenient here (as I'll describe below), but for your future potential cases, a better naming would be <code>self.producer_counter</code> and <code>self.consumer_counter</code>.<br>What those 2 semaphors (as internal counters) do is just emulating <strong><em>limitation</em></strong> of the capacity of a resource (the resource is <code>deque</code> in our case)\n<br>How it starts and flows:</p>\n\n<p>On running the producer starts appending random items in a loop of <code>100</code> iterations:</p>\n\n<pre><code> ...\n for _ in range(self.times):\n self.queue.append(random.randint(0, 100))\n</code></pre>\n\n<p>on each iteration the <code>producer</code> thread will acquire <code>self.remaining_space.acquire()</code> decrementing the internal counter. When producer's counter is zero (<code>0</code>) the <code>producer</code> thread will <strong>block</strong> until the <code>consumer</code> thread calls <code>self.remaining_space.release()</code> thus increasing the producer's counter by <code>1</code> and letting the <code>producer</code> thread to proceed.<br>Such a \"dragging\" of <code>acquire/release</code> in multiple places can be just replaced with well-known <a href=\"https://docs.python.org/3/library/queue.html#queue.Queue\" rel=\"nofollow noreferrer\"><strong><code>queue.Queue</code></strong></a>, which is FIFO queue that already uses <code>deque</code> under the hood and already provides the needed <em>locking</em> mechanism and <em>timeout</em> logic.</p>\n\n<blockquote>\n <p>The <code>queue</code> module implements multi-producer, multi-consumer queues.\n It is especially useful in threaded programming when information must\n be exchanged safely between multiple threads. The <code>Queue</code> class in\n this module implements all the required locking semantics.</p>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n<pre><code>class queue.Queue(maxsize=0)\n</code></pre>\n \n <p>Constructor for a FIFO queue. <code>maxsize</code> is an integer that sets the upperbound limit on the number of items that can be placed in the\n queue. Insertion will block once this size has been reached, until\n queue items are consumed. If <code>maxsize</code> is less than or equal to zero,\n the queue size is infinite.</p>\n</blockquote>\n\n<p>So <code>maxsize</code> already gives us a <em>limited</em> <em>capacity</em>.</p>\n\n<p><strong><em>Namings:</em></strong><br>\nA better names for a numeric constants in our new scheme would be:</p>\n\n<pre><code>MAX_QSIZE = 10 # max queue size\nBUF_SIZE = 100 # total number of iterations/items to process\n</code></pre>\n\n<p><strong><em>\"Tricky\" passing of <code>TIMES</code> constant:</em></strong><br>\nIt's not good to pass total number of processed items to <code>Consumer</code> constructor:</p>\n\n<pre><code>class Consumer:\n def __init__(self, queue, times=TIMES):\n ...\n</code></pre>\n\n<p>that allows compromising and specifying <em>improper</em> number of items to process.<br>Consider the following case:</p>\n\n<pre><code>TIMES = 100\n...\n producer = Producer(queue)\n producer_thread = threading.Thread(target=producer.run)\n consumer = Consumer(queue, times=50)\n consumer_thread = threading.Thread(target=consumer.run)\n</code></pre>\n\n<p>this will point the <code>consumer</code> to consume less items than the <code>queue</code> contains, eventually having the queue with dangled items.<br>If you run that case you'll have the pipeline blocked/hanged. <br>To avoid that we need to ensure the <code>consumer</code> has gotten and processed all items in the queue:</p>\n\n<pre><code>class Consumer:\n def __init__(self, queue):\n self.queue = queue\n\n def run(self):\n while not self.queue.empty():\n item = self.queue.get()\n self.queue.task_done()\n print(item)\n</code></pre>\n\n<p>To enrich the queue communication we can incorporate <a href=\"https://docs.python.org/3/library/queue.html#queue.Queue.task_done\" rel=\"nofollow noreferrer\"><code>queue.task_done()</code></a> and <a href=\"https://docs.python.org/3/library/queue.html#queue.Queue.join\" rel=\"nofollow noreferrer\"><code>queue.join()</code></a> (the final version will incorporate them).</p>\n\n<p><em>The final concise version:</em></p>\n\n<pre><code>from queue import Queue\nimport random\nimport threading\n\nMAX_QSIZE = 10 # max queue size\nBUF_SIZE = 100 # total number of iterations/items to process\n\n\nclass Producer:\n def __init__(self, queue, buf_size=BUF_SIZE):\n self.queue = queue\n self.buf_size = buf_size\n\n def run(self):\n for _ in range(self.buf_size):\n self.queue.put(random.randint(0, 100))\n\n\nclass Consumer:\n def __init__(self, queue):\n self.queue = queue\n\n def run(self):\n while not self.queue.empty():\n item = self.queue.get()\n self.queue.task_done()\n print(item)\n\n\ndef main():\n q = Queue(maxsize=MAX_QSIZE)\n\n producer = Producer(q)\n producer_thread = threading.Thread(target=producer.run)\n\n consumer = Consumer(q)\n consumer_thread = threading.Thread(target=consumer.run)\n\n producer_thread.start()\n consumer_thread.start()\n\n producer_thread.join()\n consumer_thread.join()\n q.join()\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T18:19:03.510",
"Id": "513046",
"Score": "0",
"body": "There's an issue with this code. If producer thread takes a little time to put data into the consumer's queue, there's a chance that consumer will see queue empty and will exit for e.g. if you add this line `time.sleep(1)` before `self.queue.put(random.randint(0, 100))` the program stays at q.join() and never completes. May be we need to synchronize the two threads using an external object e.g. SynchronizationContext"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:06:39.510",
"Id": "231405",
"ParentId": "231397",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T03:17:18.960",
"Id": "231397",
"Score": "3",
"Tags": [
"python",
"multithreading",
"thread-safety",
"concurrency",
"producer-consumer"
],
"Title": "Simple Producer-consumer implementation in Python"
}
|
231397
|
<p>I'm working with one environment which allows me to execute node.js code <strong>from single file without installing additional modules</strong>. My task is to write simple ssl socket client which will send protobuf message, receive response in same format and decode it.</p>
<p>What I developed in this code example:</p>
<ol>
<li>protobuf decoder/encoder (I've implemented only types I'll use);</li>
<li>ssl socket class;</li>
</ol>
<p>I'm very much a newbie in Node.js (6 hours experience :D), so I need you to point me weak parts of this code and share with me best practices.</p>
<pre><code>const tls = require("tls");
const HOST = "example.com";
const PORT = 12345;
const ProtoTypes = Object.freeze({"Varint": 0, "_64bit": 1, "LengthDelimited": 2, "_32bit": 5});
class ProtoField {
constructor (type, tag, value=null) {
if (isNaN(tag) || tag < 0)
throw new Error("Invalid tag");
this.type = type;
this.tag = tag;
this.value = value;
}
encodePrefix() {
return VarintField.encode((this.tag << 3) | this.type);
}
static decodePrefix(stream, position=0) {
var decoded_prefix = VarintField.decode(stream, position);
return {
type: decoded_prefix.value & 7,
tag: decoded_prefix.value >> 3,
length: decoded_prefix.length
}
}
encode() {
var prefix = this.encodePrefix();
return Buffer.concat([prefix, this.constructor.encode(this.value)]);
}
decode(stream, position=0) {
var decoded = this.constructor.decode(stream, position);
this.value = decoded.value;
return decoded.length;
}
}
class VarintField extends ProtoField {
constructor(tag, value=null) {
if (value != null && isNaN(value))
throw new Error("Invalid value");
super(ProtoTypes.Varint, tag, value);
}
static encode(value) {
var number = value, buf = [];
for (;;) {
var toWrite = number & 0x7F;
number >>= 7;
if (number != 0)
buf.push(toWrite | 0x80);
else {
buf.push(toWrite);
break;
}
}
return Buffer.from(buf);
}
static decode(stream, position=0) {
var number = 0, bytes_read = 0;
for (var shift = 0; position + bytes_read < stream.length; bytes_read++, shift += 7) {
var b = stream[position + bytes_read];
number |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
bytes_read += 1;
break;
}
}
return {
value: number,
length: bytes_read
}
}
}
class BytesField extends ProtoField {
constructor(tag, value=null) {
if (value != null && !Buffer.isBuffer(value))
throw new Error("Invalid value");
super(ProtoTypes.LengthDelimited, tag, value);
}
static encode(value) {
return Buffer.concat([VarintField.encode(value.length), Buffer.from(value)]);
}
static decode(stream, position=0) {
var length = VarintField.decode(stream, position);
return {
value: stream.slice(position + length.length, position + length.length + length.value),
length: length.length + length.value
}
}
}
class StringField extends ProtoField {
constructor(tag, value=null) {
if (value != null && String(value) !== value)
throw new Error("Invalid value");
super(ProtoTypes.LengthDelimited, tag, value);
}
static encode(value) {
return Buffer.concat([VarintField.encode(value.length), Buffer.from(value, "utf-8")]);
}
static decode(stream, position=0) {
var length = VarintField.decode(stream, position);
return {
value: stream.slice(position + length.length, position + length.length + length.value).toString("utf-8"),
length: length.length + length.value
}
}
}
class _32bitField {
static decode(stream, position=0) {
return {value: null, length: 4};
}
}
class _64bitField {
static decode(stream, position=0) {
return {value: null, length: 8};
}
}
const ProtoTypesDefaultClasses = Object.freeze({
[ProtoTypes.Varint]: VarintField,
[ProtoTypes.LengthDelimited]: BytesField,
[ProtoTypes._32bit]: _32bitField,
[ProtoTypes._64bit]: _64bitField
});
class Message {
constructor() {
this.fields = [];
}
addField(field) {
this.fields[field.tag] = field;
return field;
}
encode() {
var buffers = [];
this.fields.forEach(function(field) {
if (field.value != null)
buffers.push(field.encode());
});
return Buffer.concat(buffers);
}
decode(stream, position=0, length=0) {
var bytes_read = 0, length = length > 0 ? length : stream.length - position;
for (; bytes_read < length;) {
var prefix = ProtoField.decodePrefix(stream, position + bytes_read);
if (this.fields[prefix.tag] != undefined)
bytes_read += this.fields[prefix.tag].decode(stream, position + bytes_read + prefix.length) + prefix.length;
else
bytes_read += ProtoTypesDefaultClasses[prefix.type].decode(stream, position + bytes_read + prefix.length).length + prefix.length;
}
return bytes_read;
}
}
class EmbeddedMessageField extends ProtoField {
constructor(tag, value) {
if (!(value instanceof Message))
throw new Error("Invalid value");
super(ProtoTypes.LengthDelimited, tag, value);
}
static encode(value) {
return BytesField.encode(value.encode());
}
decode(stream, position=0) {
var length = VarintField.decode(stream, position);
return length.length + this.value.decode(stream, position + length .length, length.value)
}
}
class ExampleEmbededMessage extends Message {
constructor(f1, f2, f3) {
super();
this.e_field1 = this.addField(new BytesField(1, f1));
this.e_field2 = this.addField(new VarintField(2, f2));
this.e_field3 = this.addField(new StringField(4, f3));
}
}
class ExampleRequestMessage extends Message {
constructor(f0, f1, f2, f3) {
super();
this.field1 = this.addField(new StringField(1, f0));
this.embedded = this.addField(new EmbeddedMessageField(2, new ExampleEmbededMessage(f1, f2, f3)));
this.constant_field = this.addField(new StringField(3, "constant"));
}
}
class ExampleResponseMessage extends Message {
constructor() {
super();
this.resp_field1 = this.addField(new StringField(1));
this.resp_field2 = this.addField(new VarintField(2));
this.resp_field15 = this.addField(new StringField(15));
}
}
class Packet {
constructor(id, message) {
this.id = id;
this.message = message;
}
encode() {
return Buffer.concat([Buffer.from([this.id]), this.message.encode()]);
}
decode(stream, position=0) {
if (stream.length == 0)
return 0;
this.id = stream[position];
return this.message.decode(stream, position + 1) + 1;
}
}
class TLSClient {
constructor(host, port) {
this.host = host;
this.port = port;
this.options = {rejectUnauthorized: false};
this.init()
}
init() {
var client = this;
this.socket = tls.connect(client.port, client.host, client.options);
}
send(packet) {
var client = this;
return new Promise((resolve, reject) => {
var encoded_packet = packet.encode();
var length = Buffer.alloc(4);
length.writeUInt32LE(encoded_packet.length);
client.socket.write(Buffer.concat([length, encoded_packet]));
client.socket.on("data", (data) => {
resolve(data);
client.socket.destroy();
});
client.socket.on("error", (err) => {
reject(err);
});
});
}
}
var f0 = "string1", f1 = Buffer.from([0, 1, 2, 3, 4, 5]), f2 = 54321, f3 = "string2";
var request_packet = new Packet(13, new ExampleRequestMessage(f0, f1, f2, f3));
var response_packet = new Packet(13, new ExampleResponseMessage());
var sock = new TLSClient(HOST, PORT);
sock.send(request_packet)
.then((data) => {
response_packet.decode(data, 4);
if (response_packet.resp_field2.value > 0)
console.log("Great!");
else
console.log("Zero.");
})
.catch((err) => {
console.log(err);
});
</code></pre>
<hr />
<p>So, after some time passed I see no answers. I think, I should ask more concrete questions:</p>
<ol>
<li>Is <code>Object.freeze()</code> the normal way to implement enum logic in JavaScript?</li>
<li>Is it okay to give same names for method and static method?</li>
<li>Is <code>instance.constructor.static_method()</code> the normal way to access to a static method?</li>
<li>Is the way i use <code>Promise</code> correct?</li>
<li>Is naming style I used for classes, variables, constants and methods correct?</li>
<li>Are there any logical mistakes in OOP?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T18:47:46.257",
"Id": "452048",
"Score": "2",
"body": "Welcome! I am looking forward to the review of this."
}
] |
[
{
"body": "<h1>Overall Remarks</h1>\n<p>I must admit that this code makes use of more bitwise operators than I normally see in JavaScript. Nonetheless it looks to be sophisticated. There is a lot of code so the remarks here may not be comprehensive but I’ll cover what I can.</p>\n<h1>Question Responses</h1>\n<blockquote>\n<ol>\n<li>Is <code>Object.freeze()</code> the normal way to implement enum logic in JavaScript?</li>\n</ol>\n</blockquote>\n<p>That seems to be the common convention. Note that "freeze is shallow"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#Freezing_arrays\" rel=\"nofollow noreferrer\">1</a></sup> so if there were nested objects then it would likely by obligatory to freeze those as well. Refer to answers to <a href=\"https://stackoverflow.com/q/287903/1575353\">this Stack Overflow question: <em>What is the preferred syntax for defining enums in JavaScript?</em></a>. For even more light reading take a glance at <a href=\"https://stijndewitt.com/2014/01/26/enums-in-javascript/\" rel=\"nofollow noreferrer\">this article</a> posted by one of the users who supplied an answer to that aforementioned SO question.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Is it okay to give same names for method and static method?</li>\n</ol>\n</blockquote>\n<p>While it was closed as off-topic <a href=\"https://stackoverflow.com/q/47443124/1575353\">that question was asked on Stack Overflow</a> as well.</p>\n<blockquote>\n<ol start=\"3\">\n<li>Is <code>instance.constructor.static_method()</code> the normal way to access to a static method?</li>\n</ol>\n</blockquote>\n<p>I don’t want to sound like a broken record but <a href=\"https://stackoverflow.com/q/28627908/1575353\">there’s a SO question for that</a>. That was works unless the goal is to allow an override static method to be used in a sub-class.</p>\n<blockquote>\n<ol start=\"4\">\n<li>Is the way i use Promise correct?</li>\n</ol>\n</blockquote>\n<p>I am not sure if it is “correct” but as far as I can tell that seems to match typical usage I have seen.</p>\n<blockquote>\n<ol start=\"5\">\n<li>Is naming style I used for classes, variables, constants and methods correct?</li>\n</ol>\n</blockquote>\n<p>Again I'm not sure what "correct" is but we can say it is <em>idiomatic</em> - it appears to follow standard conventions (e.g. style guides like <a href=\"https://github.com/airbnb/javascript#naming-conventions\" rel=\"nofollow noreferrer\">AirBnB</a>, <a href=\"https://google.github.io/styleguide/jsguide.html#naming\" rel=\"nofollow noreferrer\">Google</a>, etc.)</p>\n<h1>Suggestions</h1>\n<h2>Variable declaration keywords</h2>\n<p>There are quite a few lines that use keyword <code>var</code>.</p>\n<blockquote>\n<pre><code>var number = 0, bytes_read = 0;\n</code></pre>\n</blockquote>\n<blockquote>\n<pre><code>var toWrite = number & 0x7F;\n</code></pre>\n</blockquote>\n<p>Many argue that <a href=\"https://softwareengineering.stackexchange.com/q/278652/244085\"><code>const</code> and <code>let</code> should be used instead of <code>var</code></a> in ES6 for multiple reasons - e.g. block scoping, unintentional re-assignment with <code>const</code>, etc.</p>\n<h2>Binding context to <code>this</code></h2>\n<p>In <code>TLSClient::send()</code> there is this first line:</p>\n<blockquote>\n<pre><code>var client = this;\n</code></pre>\n</blockquote>\n<p>that appears to be used within the promise callback - e.g.:</p>\n<blockquote>\n<pre><code>client.socket.write(Buffer.concat([length, encoded_packet]));\n</code></pre>\n</blockquote>\n<p>But with an arrow function the context is the same... so there is no need to assign the outer context. If it wasn't using an arrow function, the same could be achieved with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a>.</p>\n<h3>Extra lambda functions</h3>\n<p>In <code>TLSClient::send()</code> there is this declaration:</p>\n<blockquote>\n<pre><code>client.socket.on("error", (err) => {\n reject(err);\n});\n</code></pre>\n</blockquote>\n<p>This could be simplified to:</p>\n<pre><code>this.socket.on("error", reject);\n</code></pre>\n<p>because the arguments would get passed directly to the callback.</p>\n<h3>Bloated <code>for</code> loop</h3>\n<p>In <code>Message::decode()</code> there is a loop started like this:</p>\n<blockquote>\n<pre><code>for (; bytes_read < length;) {\n</code></pre>\n</blockquote>\n<p>It could simple be a <code>while</code> loop:</p>\n<pre><code>while (bytes_read < length) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T19:14:02.430",
"Id": "490432",
"Score": "0",
"body": "You did the great job. A I said I've never used js seriously before, so I really appreciate that you linked already answered questions with great explanation for such as newbies as I am. Thank you very much, will try to find time on weekends and add to question upgraded version. **P.S.** *(offtopic)* Surprisingly, this code is pretty stable and working without any problems for very long time :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T20:07:43.557",
"Id": "490437",
"Score": "0",
"body": "Great! Please consider posting a new question (linking back to this one as reference) instead of adding the upgraded version. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T13:42:06.230",
"Id": "250039",
"ParentId": "231398",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250039",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T03:59:46.607",
"Id": "231398",
"Score": "6",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"ssl",
"protocol-buffers"
],
"Title": "Node.JS Protobuf socket client with TLS support"
}
|
231398
|
<p>I have made a multithreaded command runner that works, just wanted to share the code and see if you guys can see any pitfalls. Comments are not part of actual code</p>
<pre><code>protected async Task<bool> PollQueue(CancellationToken cancellationToken)
{
async Task<Batch> SyncQueueTask(CancellationToken token)
{
await WaitForQueue(token);
return null;
}
var queue = new Queue<Batch>();
var runners = new Dictionary<Guid, Task<Batch>>();
Task<Batch> syncTask = null;
var cancelSyncTask = new CancellationTokenSource();
bool QueueWasReleased() => syncTask == null;
do
{
//Do not spawn new work if application is closing down, but let ongoing work have a chance to complete
if (!cancellationToken.IsCancellationRequested)
{
var slots = Environment.ProcessorCount - runners.Count;
//Poll SQL queue if slots are available and we have gotten a signal that work is is available
if (QueueWasReleased())
{
using (var scope = _serviceProvider.CreateScope())
{
var batch = (await scope.ServiceProvider.GetService<ICommandRepository>()
.ListByAsync(CommandState.Pending))
.Where(c => !runners.ContainsKey(c.BatchId))
.GroupBy(c => c.BatchId)
.Select(grp => new Batch {Id = grp.Key, Commands = grp.ToList()});
queue = new Queue<Batch>(batch);
}
}
//Start new work
var tempQueue = queue;
Enumerable
.Range(0, Math.Min(slots, queue.Count))
.ForEach(i =>
{
var batch = tempQueue.Dequeue();
var runner = Task.Run(async () =>
{
await batch
.Commands
.Select(ExecuteCommand)
.WaitAll(cancellationToken);
return batch;
}, CancellationToken.None);
runners[batch.Id] = runner;
});
}
if (runners.Count == 0) break;
//Create a sync task thats only purpose is to release await if new work is available. This is to that long running work does not starve queue
if (syncTask == null)
syncTask = SyncQueueTask(cancelSyncTask.Token);
//Wait for next completed work or that new work are avialable on queue
var completed = await Task.WhenAny(runners.Values.Concat(syncTask));
if (completed == syncTask)
syncTask = null;
else
runners.Remove(completed.Result.Id);
} while (true);
//Cleanup if we are waiting
if (syncTask != null)
cancelSyncTask.Cancel();
return false;
}
</code></pre>
<p>WaitForQueue is just a semaphoreslim. (With an extensionmethod that swallows cancelation exceptions)</p>
<pre><code>private Task WaitForQueue(CancellationToken token)
{
return _queueSync.SilentWaitAsync(Delay, token);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:12:24.973",
"Id": "231406",
"Score": "1",
"Tags": [
"c#",
"async-await"
],
"Title": "Async scheduler that executes commands multitthreaded"
}
|
231406
|
<p>This a fairly basic script I made for use in some other projects, nothing too complex or sophisticated and obviously lacking in some features (Password/Username encryption, Missing file contingencies etc.).</p>
<p>It loads a text file (formatted as <code>USERNAME, PASSWORD\nUSERNAME, PASSWORD\n</code>) into a 2D array, then checks the inputs against it, until 2 separate logins are used. </p>
<hr>
<p>I'm what I'd consider intermediate in terms of python competency, but there are always things to be improved upon: any suggestions? I tend to use something similar to this for all projects that require a login, so any improvements or areas to look into, no matter how minor, would be greatly appreciated.</p>
<hr>
<pre><code>def login():
player_count, details = 0, [[data.strip() for data in line.split(",")] for line in open("username_password.txt", "r").read().splitlines()]
while player_count != 2:
username, password = input("USERNAME"), input("PASSWORD")
for data in details:
if username == data[0] and password == data[1]:
print("LOGIN CORRECT")
details.pop(details.index(data))
player_count += 1
break
else:
print("INCORRECT")
main()
def main():
print("LOGGED IN\nMAIN")
login()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T14:58:02.060",
"Id": "451356",
"Score": "0",
"body": "Could your file contain repeated/duplicated username or password?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:36:39.417",
"Id": "451367",
"Score": "0",
"body": "Hypothetically yes, thereby bypassing the preventatives in place to stop the same user logging in twice, however when creating the loggins I always have measures to stop such an occurance."
}
] |
[
{
"body": "<p>Here's a small suggestion -</p>\n<p>You could make use of the -</p>\n<h1><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == "__main__":</code></a> guard</h1>\n<p>Like this -</p>\n<pre><code>def login():\n player_count, details = 0, [[data.strip() for data in line.split(",")] for line in open("username_password.txt", "r").read().splitlines()]\n while player_count != 2:\n username, password = input("USERNAME"), input("PASSWORD")\n for data in details:\n if username == data[0] and password == data[1]:\n print("LOGIN CORRECT")\n details.pop(details.index(data))\n player_count += 1\n break\n else:\n print("INCORRECT")\n main()\n\ndef main():\n print("LOGGED IN\\nMAIN")\n\nif __name__ == "__main__":\n login()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:30:00.633",
"Id": "451365",
"Score": "0",
"body": "Thanks for the suggestion. Have yet to look into any guarding or the like, but will look into it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T14:29:25.990",
"Id": "231410",
"ParentId": "231408",
"Score": "2"
}
},
{
"body": "<p>I would split off <code>player_count = 0</code> to a different line. Multiple assignments on one line is perfectly fine for simple assignments (like <code>a, b = 1, 2</code>), but a double list comprehension doesn't qualify for \"simple\".</p>\n\n<h3>Readability Counts</h3>\n\n<p>In general, Readability is far more important than conciseness. In fact, the reason concise code is often better is <em>because</em> it's more readable. </p>\n\n<p>Normally, I'd be <strong>very</strong> careful with double list assignments for that reason. However, in this specific case, I think making it a single line is a good call. It's not overly long nor complex. </p>\n\n<h3>Performance</h3>\n\n<p>For pure python, I don't think you can really improve your performance even more. You won't get any issues until your password file grows into the MB's, and if that's a problem, you shouldn't be using a file with plaintext passwords anyway, since you'll be running your software in a production environment. </p>\n\n<p>Instead, you'd be hashing and salting your passwords and storing them in a database, which is coincidentally also the best way to improve your performance if you get datasets that large.</p>\n\n<p>However, as long as your username and password are requested from the user by means of the input() function, you won't have an issue. </p>\n\n<h3>dict.pop()</h3>\n\n<p>This function removes the value from the list. However, you don't seem to be actually <em>doing</em> anything with that value, and you're also discarding the list. So I'd just drop that line. </p>\n\n<p>The only thing I can imagine you fix it would be to stop player2 from using the same credentials as player1. However, you don't save player references anyway. If you want to stop the same credentials from being used twice, I'd recommend to instead save references to the players for later, and then check that a player hasn't already been logged in as another player.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:34:52.160",
"Id": "451366",
"Score": "0",
"body": "Thanks for the suggetions, will revise the topics nessessary for the larger files ill probably encounter at some point. However in my experience, the dict.pop() removes the element from the list in so preventing the user from using the same login again, The code was also pulled from a project that uses the popped element to later refer to in a \"current user\" sort of way. Thanks for the suggestions, appreciate the help massively!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:00:39.383",
"Id": "451436",
"Score": "0",
"body": "Hm, CodeReview is really for code you've written yourself, you know. But yes, that's what you could use it for in that way."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T14:54:52.477",
"Id": "231411",
"ParentId": "231408",
"Score": "3"
}
},
{
"body": "<p>Advises for optimization:</p>\n\n<ul>\n<li><p><code>open(\"username_password.txt\", \"r\").read()</code>. This could be called as \"negligent treatment\" of the file object. The good and robust way is to always close the file object/resource after usage/consumption.<br>We have a convenient feature called context managers (<code>with</code> statement) for <em>\"automated\"</em> graceful closing of used resource:</p>\n\n<pre><code>with open('filename') as f:\n content = f.read()\n</code></pre></li>\n<li><code>details = [[...]]</code>. Instead of manually stripping and storing the file contents as list of lists, the more flexible way is using <a href=\"https://docs.python.org/3/library/csv.html#csv.reader\" rel=\"nofollow noreferrer\"><code>csv.reader</code></a> object which allows strip of surrounding whitespaces (<code>skipinitialspace=True</code> option) and recognize delimiters.</li>\n<li><p>considering that your file represents pairs of <code>USERNAME, PASSWORD</code>, in scope of application we usually expect the usernames to be unique. Therefore having a <code>dict</code> indexed with usernames and passwords as respective values would be an optimized and more performant way - giving us a quick search by <em>usernames</em> (Python <code>dict</code> is a special case of <code>hashtable</code> data structure).<br>Besides, it's really not good to remove items from the a <code>list</code> in-place while it's iterated (<code>for data in details: if ... details.pop(details.index(data))</code>), it'll lead to unexpected results. Yes, you have a \"circuit breaker\" <code>break</code> for that, but still it's better to not get used to <em>fragile</em> approaches. </p>\n\n<pre><code>with open(\"username_password.txt\") as f:\n creds = {u: p for u, p in csv.reader(f, skipinitialspace=True)}\n</code></pre></li>\n<li><p><a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>dict.get()</code></a> call allows to flexibly combine check for username/password:</p>\n\n<pre><code>if creds.get(username) == password:\n ...\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>The final optimized version:</p>\n\n<pre><code>import csv\n\ndef login():\n player_count = 0\n with open(\"username_password.txt\") as f:\n creds = {u: p for u, p in csv.reader(f, skipinitialspace=True)}\n\n while player_count != 2:\n username, password = input(\"USERNAME\"), input(\"PASSWORD\")\n if creds.get(username) == password:\n print(\"LOGIN CORRECT\")\n player_count += 1\n creds.pop(username)\n else:\n print(\"LOGIN INCORRECT\")\n main()\n\n\ndef main():\n print(\"LOGGED IN\\nMAIN\")\n\n\nlogin()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T09:55:54.660",
"Id": "231449",
"ParentId": "231408",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>I tend to use something similar to this for all projects that require a login</p>\n</blockquote>\n\n<p>Then it's time to stop using self-rolled unencrypted authentication. It's fine as a one-off proof-of-concept, but as you've described, that's not how it's actually being used.</p>\n\n<p>Read through <a href=\"https://stackoverflow.com/questions/7014953/i-need-to-securely-store-a-username-and-password-in-python-what-are-my-options\">https://stackoverflow.com/questions/7014953/i-need-to-securely-store-a-username-and-password-in-python-what-are-my-options</a> - specifically, consider using something like <code>keyring</code>. Not only will it be more secure - it will also simplify your code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:42:02.470",
"Id": "231459",
"ParentId": "231408",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231411",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:11:53.423",
"Id": "231408",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Login Script Utilising List Comprehension"
}
|
231408
|
<p><strong>Problem:</strong> We read a complex json-file which grants us a <em>tree</em> in terms of a python "dict of dicts". We're then requested to retrieve a <em>specific path</em> from the tree, represented by a list of elements. The list (i.e. the path) may have any, arbitrary length.</p>
<p><strong>Simple Example:</strong></p>
<pre><code># The dict-tree:
d = {"a":{"1":{"aa":"a2", "aaa":"a3"}},
"b":{"2":{"bb":"b2", "bbb":"b3"}},
"c":{"3":{"cc":"c2", "ccc":"c3"}},
"d":{"4":{"dd":"d2", "ddd":"d3"}},
"e":{"5":{"ee":"e2", "eee":"e3"}}
}
# The path ..
p = ["b", "2", "bb"] # --> "b2"
</code></pre>
<p><strong>Solution (to be improved):</strong>
Now, a naive solution could be to simply <code>return d[p[0]][p[1]][p[2]]</code>. However this obviously fails for any path-length not equal to three. Thus, I wrote two functions as shown below,</p>
<pre><code># Recursive approach
def get_val_from_path_1(d, p):
if len(p)>1 and p[0] in d:
return get_val_from_path_1(d[p[0]], p[1:])
if p[0] in d:
return d[p[0]]
return None
# Iterative approach
def get_val_from_path_2(d, p):
tmp = d
for s in p:
if not s in tmp:
return None
tmp = tmp[s]
return tmp
</code></pre>
<p>A (very) simple time-consumption test can be run on my <a href="https://repl.it/@dahle/arbitrary-path-in-complex-dict" rel="nofollow noreferrer">repl.it</a>, which suggests that the iterative approach (no.2) is significantly faster than the recursive (no.1).</p>
<p>Preferably, I would really like a simpler approach, without any need of loops, however, any suggestions that improves performance, readability and/or code-line-usage are most appreciated.</p>
<p><strong>EDIT:</strong> The question was intended for Python-3.x. I do not edit the label, because it is discussed in the comments of the below answer(s).</p>
|
[] |
[
{
"body": "<p>Thematically, I would say recursive is the way to go. Especially if you ever find yourself writing a language that does tail-call optimization well, it's superior. (Python sadly doesn't. It involves replacing the top frame on the stack with a new frame, which stops you from getting...StackOverflow. Well, to be 100% accurate, Python will toss a RecursionError in your face before that happens, but it's a fitting thought.)</p>\n\n<p>I would however, also recommend using python *args notation and slicing to parse it a tad more easily:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_value_by_path(container, *args):\n if not args:\n return container\n return get_value_by_path(container[args[0]], *args[1:])\n\nvalue = get_value_by_path(d, \"b\", \"2\", \"bb\")\n# \"b2\"\nvalue = get_value_by_path(d, \"b\", \"2\")\n# {\"bb\":\"b2\", \"bbb\":\"b3\"}\nvalue = get_value_by_path(d, \"b\")\n# {\"2\":{\"bb\":\"b2\", \"bbb\":\"b3\"}}\n</code></pre>\n\n<p>This has the advantage that it will also work for lists, if you just give indices, whereas an <code>in</code> check like you have would stop that. If there's a wrong index/key somewhere, this way will throw a KeyError, exactly like all builtin indexing operations. </p>\n\n<p>If you care more about SLOC (Source Lines of Code) than readability, you could use the 1liner:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def ugly_get_value_by_path(container, *args):\n return ugly_get_value_by_path(container[args[0]], *args[1:]) if args else container\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:01:44.713",
"Id": "451507",
"Score": "2",
"body": "I agree with AJNeufeld that *any* recursive solution has (sometimes) serious caveats in Python. But I ultimately agree more with you: this problem is fundamentally recursive, and an iterative solution won’t be as direct, intuitive and elegant as a recursive one. At best it’ll be a good approximation. Slicing *is* a real performance issue (regardless of paradigm), but a recursive solution can solve that just as well as an iterative solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:59:56.290",
"Id": "451600",
"Score": "0",
"body": "Regarding the slicing, I was assuming this isn't that performance critical. A more performance-friendly implementation could build a simple tuple and then pass it along with an index."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:11:16.103",
"Id": "231414",
"ParentId": "231409",
"Score": "3"
}
},
{
"body": "<h2>Recursive Approach Review</h2>\n\n<p>In this method you are performing too many look-ups.</p>\n\n<p>First, you are looking up the 0th value of <code>p</code> two or three times. List indexing does take time, so it may be faster to store <code>p[0]</code> in a local variable, to avoid repeatedly indexing into the list. </p>\n\n<p>Second, you are performing a dictionary looking ups two or three times. While dictionary look-ups are fast, ideally <span class=\"math-container\">\\$O(1)\\$</span> in time, they do take time. <code>p[0] in d</code> is a dictionary lookup without retrieving the looked up value; <code>d[p[0]]</code> is a dictionary lookup that retrieves the value.</p>\n\n<p>The first and second if statements do effectively the same things. They check <code>p[0] in d</code>, and if true, they retrieve <code>d[p[0]]</code>. We can extract this common functionality, perform it once, and then, depending on <code>len(p)</code>, perform the recursion. Additionally, we'll use <code>dict.get(p[0], None)</code> to perform a single dictionary lookup, using the value from a single list index operation:</p>\n\n<pre><code>def get_val_from_path_1(d, p):\n d = d.get(p[0], None)\n if d is not None and len(p) > 1:\n return get_val_from_path_1(d, p[1:])\n return d\n</code></pre>\n\n<p>Note: I used <code>d is not None</code>, instead of simply testing if <code>d</code> is \"truthy\", so that if a subkey is requested of a \"falsy\" value (<code>0</code>, <code>False</code>, <code>\"\"</code>), the dictionary lookup will happen in the recursive call, and an exception will be raised similar to the original code.</p>\n\n<p><strong>EDIT</strong>: As mentioned by RootTwo in the comments, it is \"safer\" to use a sentinel object, in case <code>None</code> is an actual value contained in the JSON object. Although if <code>None</code> values are contained in the JSON object, it is ambiguous as to whether the key does not exist, or exists with the value <code>None</code>:</p>\n\n<pre><code>def get_val_from_path_1(d, p):\n sentinel = object()\n d = d.get(p[0], sentinel)\n if d == sentinel:\n return None\n if len(p) > 1:\n return get_val_from_path_1(d, p[1:])\n return d\n</code></pre>\n\n<h2>Iterative Approach Review</h2>\n\n<p>This code begins with <code>tmp = d</code>, which is odd as <code>d</code> is never used in the remainder of the code. The temporary variable can be removed.</p>\n\n<p>Similar to the Recursive Approach, you are using a double dictionary lookup. <code>s in tmp</code> followed by <code>tmp[s]</code>. Again, using <code>tmp.get(s, None)</code> would perform the dictionary lookup once, and return <code>None</code> if the key was not present.</p>\n\n<pre><code>def get_val_from_path_2(d, p):\n for s in p:\n d = d.get(s, None)\n if d is None:\n break\n return d\n</code></pre>\n\n<p><strong>EDIT</strong>: A sentinel can be used here as well, with the same ambiguity disclaimer:</p>\n\n<pre><code>def get_val_from_path_2(d, p):\n sentinel = object()\n for s in p:\n d = d.get(s, sentinel)\n if d is sentinel:\n return None\n return d\n</code></pre>\n\n<h2>Which approach is better?</h2>\n\n<p><strong>EDIT</strong>: <em>Clarifications added</em> at based on comments by Konrad.</p>\n\n<p>Gloweye attempts to make the case that \"<em><a href=\"https://codereview.stackexchange.com/a/231414/100620\">recursive is the way to go</a></em>\". I disagree.</p>\n\n<p>First off, Python does not do tail call optimization. If it did, it would close the performance gap with the iterative approach, but <em>with the current recursive implementation,</em> the iterative method would still win.</p>\n\n<p>In each recursive call, the <code>p[1:]</code> is being passed to the <code>p</code> argument. This is building a brand-new list, and copying the elements to the new list. With <code>n</code> items in the original list, <code>n-1</code> elements are copied the first time, <code>n-2</code> are copied the second, <code>n-3</code> the third, and so on, making this an <span class=\"math-container\">\\$O(n^2)\\$</span> time algorithm.</p>\n\n<p>Gloweye's approach is a constant factor worse, since <code>*args[1:]</code> in addition to constructing the list slice must \"splat\" the items into the argument list, which then gets unsplatted back to <code>args</code> tuple in the next call. I should stress it is not that much worse; it is still only <span class=\"math-container\">\\$O(n^2)\\$</span>.</p>\n\n<p><em>Both Gloweye's and the current recursive approach, passing <code>p[1:]</code> as the argument in the recursive call, can be corrected from <span class=\"math-container\">\\$O(n^2)\\$</span> to <span class=\"math-container\">\\$O(n)\\$</span> by replacing the list slicing with an iterator. Since the recursive argument has changed from a list to an iterator, a second function would be needed to implement this change.</em></p>\n\n<p>If tail call optimization was present, and the list was not being repeatedly sliced and recreated each step, such as by using an iterator to walk down the list of keys, then things would be <em>better (as in <span class=\"math-container\">\\$O(n)\\$</span>)</em>. Tail call optimization works by updating the arguments for the next call, and jumping to the top of the function, which turns the recursion into a simple loop.</p>\n\n<p>So why not just use a loop?</p>\n\n<p>One last optimization is to stop checking for the existence of the keys (or even a <code>None</code> default <em>or sentinel</em> value); these checks slow the loop down. Instead, unconditionally lookup and retrieve the values. Rely on Python's blazingly fast exception handling to efficiently recover from non-existent keys.</p>\n\n<p>Also, use meaningful variable names. <code>d</code> and <code>p</code> are far too obscure.</p>\n\n<p>Finally, use <code>\"\"\"docstrings\"\"\"</code> to document how to use the function.</p>\n\n<pre><code>def get_val_from_path(json_object, key_path):\n \"\"\"\n Retrieve a value from a JSON object, using a key list to\n navigate through the JSON object tree.\n\n Parameters:\n json_object (JSON): An object return from json.loads()\n key_path (Iterable[str]): A list of keys forming the key path.\n\n Returns:\n The value found at the given key path, or `None` if\n any of the keys in the path is not found.\n \"\"\"\n\n try:\n for key in key_path:\n json_object = json_object[key]\n\n return json_object\n\n except KeyError:\n return None\n</code></pre>\n\n<hr>\n\n<p>Optionally, use Gloweye's <code>*args</code> method signature for slightly friendlier calls, without the <code>[]</code> noise.</p>\n\n<pre><code>def get_val_from_path(json_object, *key_path):\n ...\n\nget_val_from_path(d, \"b\", \"2\", \"bb\") # --> \"b2\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T18:19:05.700",
"Id": "451382",
"Score": "1",
"body": "From a static typing POV you may want `key_path (List[str]):` to be `key_path (Iterable[str]):`. It may still not work with `Iterator`s or `Generator`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T19:05:46.987",
"Id": "451393",
"Score": "0",
"body": "Python has suggested using alternate forms for typing for a while. This can be seen in how generic PEP 3107 is. It's normally best not to assume much when it comes to typing, as [PyCharm](https://www.jetbrains.com/help/pycharm/type-syntax-for-docstrings.html) likely would see the typing in the docstring and I would think Sphinx and a custom middleware would also likely see it, to name two. If you want standard Python 2.7 compatibility then you can use [type comments](https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:21:59.300",
"Id": "451425",
"Score": "5",
"body": "It might be safer to use a sentinel object instead of `None` in the call to `d.get()`. In case `None` is a possible value in the nested dictionaries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:50:25.667",
"Id": "451446",
"Score": "0",
"body": "Just for the record: I'm writing **Python 3.6**. I apologize for not tagging the post correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:55:05.500",
"Id": "451447",
"Score": "0",
"body": "When I wrote my functions I considered using the `try-except` approach, but I was not aware that it was that efficient. Tested it now, and it beats all the other approaches. I originally discarded the idea without testing because I naively thought Python's exception handling was slow, without even trying to look it up.. Well that was an appropriate slap-in-the-face-learned-lesson. Thank you all for your efforts!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:05:36.757",
"Id": "451457",
"Score": "1",
"body": "Eh, that's a pretty reasonable argument against my recursive preference. I mostly just assumed that the performance wasn't that important - my own experience with this type of \"deep\" indexing never got beyond ~10 depth, and it'll be fast regardless. +1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T13:47:37.130",
"Id": "451485",
"Score": "2",
"body": "@magnus: For the record, Python's exception handling is slow(er than using e.g. `dict.get` or `in`). But Python's `try...except` clause is really fast (almost negligible) if there is *no* exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:03:49.100",
"Id": "451489",
"Score": "0",
"body": "The efficiency gain comes from a) not looking before you leap (`if s in d`), which takes time, and b) not needing to test & branch on the return values (`if d is None`), which also takes time. Performed in a loop, those costs add up. The exception handling removes that logic from the loop, which results in the speed-up."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T17:48:08.080",
"Id": "231420",
"ParentId": "231409",
"Score": "21"
}
},
{
"body": "<p>Use a library.</p>\n\n<p>In particular, <a href=\"https://glom.readthedocs.io/en/latest/\" rel=\"noreferrer\"><code>glom</code></a> does an admirable job of this, and is actively developed.</p>\n\n<pre><code>>>> d = {\"a\":{\"1\":{\"aa\":\"a2\", \"aaa\":\"a3\"}},\n... \"b\":{\"2\":{\"bb\":\"b2\", \"bbb\":\"b3\"}},\n... \"c\":{\"3\":{\"cc\":\"c2\", \"ccc\":\"c3\"}},\n... \"d\":{\"4\":{\"dd\":\"d2\", \"ddd\":\"d3\"}},\n... \"e\":{\"5\":{\"ee\":\"e2\", \"eee\":\"e3\"}}\n... }\n>>> import glom\n>>> glom.glom(d, 'b.2.bb')\n'b2'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T22:35:53.823",
"Id": "231427",
"ParentId": "231409",
"Score": "12"
}
},
{
"body": "<p>The simplest approach I can think of is to use a <code>reduce</code> and let it handle the boring stuff for us:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import reduce\n\ndef get_value_by_path(container, path):\n return reduce(dict.__getitem__, path, container)\n\nget_value_by_path(d, [\"d\", \"4\", \"ddd\"])\n# 'd3'\n</code></pre>\n\n<p>As for performance, I tested it on your repl.it link and it seems to run in about 2 seconds with your test data. So maybe not the fastest approach, but not the slowest either, and the least complex one IMO.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T09:01:48.690",
"Id": "231448",
"ParentId": "231409",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "231420",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T13:54:29.053",
"Id": "231409",
"Score": "12",
"Tags": [
"python",
"tree",
"comparative-review",
"hash-map"
],
"Title": "Extraction of value from a dict-tree, given a path of arbitrary length"
}
|
231409
|
<p>I'm working on a custom puppeteer script which converts dynamic generated HTML to an A4 PDF.
This script converts HTML to a near perfect A4 PDF file, the only issue I have is speed. Document conversion is anywhere between 1-10 minutes.</p>
<p>I have tracked the slowness to the part where we calculate how much vertical space needs to be added to the last page
in order to have a full page. If we don't do this the background we have will be clipped.</p>
<p>Next up the relevant code, which is called as followed;</p>
<pre><code>node convert.js "{\"url\":\"file://$(pwd)/generated.html\",\"options\":{\"path\":\"$(pwd)/generated.pdf\"}}"
</code></pre>
<pre><code>async function addPadding(page) {
await page.emulateMedia('print');
await page.evaluate(
_ => {
let container = document.querySelector('#padding-container');
if (container)
container.style.height = '1145px'
}
);
return Promise.resolve()
}
function getPageAmount(buffer) {
let index = buffer.indexOf('/Count ');
let string = buffer.slice(index + '/Count '.length, index + '/Count '.length + 32).toString();
return ~~string.trim().split(/\n|\/|\[|\>/)[0]
}
</code></pre>
<p><code>convert.js</code></p>
<pre><code>(async _ => {
const browser = await puppeteer.launch({
headless: true,
args: [
isDocker ? '--no-sandbox' : ''
],
defaultViewport: {
width: 724,
height: 1145 * 32
}
});
const page = await browser.newPage();
await page.emulateMedia('print');
await page.goto(request.url, { waitUntil: 'networkidle0' });
await page.setViewport({ width: 724, height: 1145 });
let buffer = await render(page);
let originalPages = getPageAmount(buffer);
let maxPasses = 3;
let passes = 0;
await addPadding(page);
buffer = await render(page);
while(getPageAmount(buffer) !== originalPages && passes < maxPasses) {
await page.evaluate(
_ => {
let paddingContainer = document.querySelector('#padding-container');
let value = ~~paddingContainer.style.height.replace('px', '');
paddingContainer.style.height = `${value / 2}px`
}
);
buffer = await render(page);
if (getPageAmount(buffer) === originalPages) {
while (getPageAmount(buffer) === originalPages) {
await page.evaluate(
_ => {
let paddingContainer = document.querySelector('#padding-container');
let value = ~~paddingContainer.style.height.replace('px', '');
paddingContainer.style.height = `${value * 1.5}px`
}
);
buffer = await render(page)
}
}
passes++
}
while(getPageAmount(buffer) !== originalPages) {
await page.evaluate(
_ => {
let paddingContainer = document.querySelector('#padding-container');
let value = ~~paddingContainer.style.height.replace('px', '');
paddingContainer.style.height = `${value - 1}px`
}
);
buffer = await render(page)
}
if (request.options.path)
fs.writeFileSync(request.options.path, buffer);
browser.close()
})();
</code></pre>
<p>I really would appreciate any feedback/help on this.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T20:00:20.797",
"Id": "451399",
"Score": "0",
"body": "You bounce between \"I\" & \"we\" a bit in that description. Is this your code, or a collaborative effort? There are also no comments describing what happens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:47:51.423",
"Id": "451445",
"Score": "0",
"body": "@t145 it's a collaborative effort. Initial work was done by a freelancer, I'm now tasked with finding out if it can be optimized"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:19:43.760",
"Id": "451495",
"Score": "0",
"body": "If you're willing to work in Python somehow, there's this library for just that: https://pypi.org/project/pdfkit/ As for pure JS, a simple search yields some promising results: https://duckduckgo.com/?q=javascript+html+to+pdf&t=ffab&ia=web For each ex there's not an excess usage of while loops, so that's likely your performance sink."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:47:13.967",
"Id": "451512",
"Score": "0",
"body": "@T145 I have no problem with Python, will try that out. However, I don't expect a better outcome than my current approach. Since I'm now controlling a headless chrome instance to create the pdf."
}
] |
[
{
"body": "<p>Ways to optimize:</p>\n\n<p><strong><em>Nested loops</em></strong></p>\n\n<p>You got nested <code>while</code> loops in <code>convert.js</code> script and that requires a particular attention.<br>The outer <code>while</code> loop contains the construction:</p>\n\n<pre><code>...\nif (getPageAmount(buffer) === originalPages) {\n while (getPageAmount(buffer) === originalPages) {\n...\n</code></pre>\n\n<p>where <code>if</code> conditional redundantly checks the condition <code>getPageAmount(buffer) === originalPages</code> whereas the underling <code>while</code> loop would check the same condition by itself. Therefore, remove the redundant <code>if</code> \"wrapper\".</p>\n\n<hr>\n\n<p><strong><code>getPageAmount</code></strong> <strong><em>function</em></strong></p>\n\n<p>Deserves a separate attention (frequently invoked function).</p>\n\n<ul>\n<li><p><code>'/Count '</code>. Many-times hardcoded search string <code>'/Count '</code> begs for extracting into a variable</p>\n\n<pre><code>let searchStr = '/Count ';\n</code></pre></li>\n<li><p><code>index + '/Count '.length</code>. Duplicated expression points to a starting offset for input buffer slicing. <br>Worth to be a variable:</p>\n\n<pre><code>let pos = buffer.indexOf(searchStr);\nlet startOffset = pos + searchStr.length;\nlet str = buffer.slice(startOffset, startOffset + 32).toString();\n</code></pre></li>\n<li><p><em>splitting a string by pattern and get the 1st chunk</em> (<code>~~string.trim().split(/\\n|\\/|\\[|\\>/)[0]</code>). <br>What it does is splitting the input string by regex pattern <code>/\\n|\\/|\\[|\\>/</code> into array of substrings. <br>Though it creates a new array of strings/chunks in memory - whereas we only need the <strong><em>1st leftmost</em></strong> chunk <code>.[0]</code>.<br>Instead, a much more efficient way is to just find the position of the 1st occurrence of the pattern and slice the input string to that point.<br>That's achievable with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search\" rel=\"nofollow noreferrer\"><code>String.search</code></a> + <code>String.slice</code> combination and will go <strong><em>smashingly</em></strong> faster compared to the initial approach.<br>\nEventually the optimized function would look as:</p>\n\n<pre><code>function getPageAmount(buffer) {\n let searchStr = '/Count ',\n pos = buffer.indexOf(searchStr),\n startOffset = pos + searchStr.length;\n let str = buffer.slice(startOffset, startOffset + 32).toString();\n return ~~str.trim().slice(0, str.search(/[\\n\\/\\[\\>]/))\n}\n</code></pre></li>\n</ul>\n\n<p><strong><em>DOM</strong> tree scanning</em></p>\n\n<p>The \"hero\" of this section is <code>document.querySelector('#padding-container')</code> which appears in many places within <code>while</code> loops and queries the current <code>document</code> for a specific tag/element.<br>\nSuch DOM queries become an expensive operations if used frequently, moreover - in massive traversals. Depending on markup complexity and \"amount\" of traversal such repetative queries may make the processing +50% slower.<br>The solution here is to extract the reference to an element into a top-level variable and reference it in all needed places. </p>\n\n<pre><code># top-level variables\n...\nlet passes = 0;\nlet paddingContainer = document.querySelector('#padding-container');\n</code></pre>\n\n<p><strong><em>Extracting</strong> \"padding container\" height</em></p>\n\n<p>Expression <code>~~paddingContainer.style.height.replace('px', '')</code> is duplicated in many places and is candidate for <em>Extract function</em> technique.<br>Could be even defined as unified function for getting <code>height</code> for the element passed as parameter:</p>\n\n<pre><code>function getElHeight(el):\n return ~~el.style.height.replace('px', '')\n\n...\n\n ...\n _ => {\n let padding_height = getElHeight(paddingContainer);\n paddingContainer.style.height = `${padding_height * 1.5}px`\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:27:44.663",
"Id": "231563",
"ParentId": "231412",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231563",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:09:03.490",
"Id": "231412",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Covert html to pdf, calculate the vertical space to the end of the last page faster"
}
|
231412
|
<p>I'll have to move a large network directory with many sub-directories and thousands of files. A number of users work on these files on a daily basis. OS is windows.</p>
<p>The move itself (copy and delete) I'll do using <code>robocopy</code>.</p>
<p>Before starting the batch process of moving, I would like to check for locked files. In case some files or folders are locked, I won't bother starting the process.</p>
<p><code>robocopy</code> has a dry run switch, but that doesn't check for locked files which would lead to an unsuccessful run.</p>
<p>I quickly came up with something like the below, in Python:</p>
<pre><code>import os
is_locked=list()
for root, dirnames, filenames in os.walk('path/to/directory'):
for filename in filenames:
full_filename = os.path.join(root, filename)
try:
pf = open(full_filename, 'a')
pf.close()
except PermissionError:
is_locked.append(full_filename)
</code></pre>
<p>Your opinion whether this is a good or bad way of doing it? Any general comment?
Performance, etc?</p>
<p>Is it harmless to be opening these files?</p>
<p>--- edit ---</p>
<p>Summary of the most relevant comments:</p>
<ul>
<li>Break the loop when first locked file is found.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T21:54:50.770",
"Id": "451406",
"Score": "0",
"body": "What protocol does the network mount use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T21:56:04.410",
"Id": "451407",
"Score": "0",
"body": "Also, do you care whether your method changes the file timestamp? You probably should.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T08:51:54.637",
"Id": "451451",
"Score": "0",
"body": "This is a rather... significant change in code and functionality, which [isn't really the point of Code Review](https://codereview.meta.stackexchange.com/q/1763/180641). I don't know how best to proceed though..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:30:49.000",
"Id": "451460",
"Score": "3",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:33:13.353",
"Id": "451461",
"Score": "0",
"body": "This question [is being discussed on meta](https://codereview.meta.stackexchange.com/q/9381/37660)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:21:29.297",
"Id": "451463",
"Score": "0",
"body": "Interesting discussion. I'm happy to comply, just need clearer guidelines. Since some comments pointed in the direction that the \"complete and working code\" rule was being broken, it was updated, then it clashed against the rule \"don't edit code\". ?=) Strangely, as it seems, this discussion took more importance and priority than the question itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T08:36:06.740",
"Id": "451957",
"Score": "0",
"body": "Bug: only `PermissionError` exception is being checked. Need to handle other like `FIleNotFound` (walk takes some time to populate the list before being able to iterate through it)"
}
] |
[
{
"body": "<h3>Bugs:</h3>\n\n<ul>\n<li>After building your list, you throw it away without printing anything (and if not, please supply all your code)</li>\n</ul>\n\n<h3>Minor:</h3>\n\n<ul>\n<li><a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> >>> os. It leads to much better readable code, and less boilerplate.</li>\n<li><code>is_locked=list()</code> should be: <code>is_locked = []</code> Note spaces and the literal.</li>\n<li><code>pf.close()</code> isn't a reliable statement. Instead, consider using something like <code>with open(full_filename) as pf: pass</code></li>\n<li><code>\"path/to/directory\"</code> is a magic variable. Make it a global constant instead.</li>\n<li>Use a <code>if __name__ == \"__main__\":</code> guard. Always.</li>\n</ul>\n\n<h3>Are you going to manually unlock all the files?</h3>\n\n<p>If not, you can just break after the first error and inform the user.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T13:45:01.023",
"Id": "451483",
"Score": "1",
"body": "Nearly the entire of your answer is useless with regard to the actual code. This is why I made my comment. Also you shouldn't rely on your reasoning with regard to `pf.close()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T13:55:17.743",
"Id": "451486",
"Score": "0",
"body": "You should not rely on the file being closed, even *with* the `close`. Because the exception will be raised before that line of code is reached. Only `with` can save you from that (or in this case putting the closing into a `finally` block)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T13:56:11.690",
"Id": "451487",
"Score": "1",
"body": "Sorry, I don't remember who posted what comment earlier. But I'll update my answer to the `with` style, which is better indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:48:44.320",
"Id": "451518",
"Score": "0",
"body": "@Graipher I don't believe your are correct there, note how [`mgr = (EXPR)` from PEP 343 is the same as `pf = open(...)`](https://www.python.org/dev/peps/pep-0343/#specification-the-with-statement), meaning that a `with` would do nothing that `.close` doesn't, in this instance. It may, however, ensure a file is closed if an error is raised between the creation and closure of the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:08:35.150",
"Id": "451523",
"Score": "0",
"body": "@Peilonrayz: But you never reach the `close`, if the `open` raises an exception. However the `with` statement of course has internally a `finally: file.close()` statement in the `__exit__` method (or something equivalent), which ensures the file is closed even if an exception is raised. The file being closed in basically all cases with a `with`, but not otherwise, was the entire point of my comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:25:31.847",
"Id": "451525",
"Score": "0",
"body": "@Graipher No it doesn't, did you look at my link? `mgr = (EXPR)` is clearly outside ___both___ `try` statements. What you're suggesting is impossible, as you have no file to close on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:45:47.300",
"Id": "451529",
"Score": "0",
"body": "@Peilonrayz I did, but I did not see what you are getting at. Do you mean that either the `open` succeeds, in which case the file will be closed by `close`, or the `open` call fails, in which case there is no file to close and it is not caught by the `with` either because it never gets that far? If that is the case, there are situations where the `with` is still needed to ensure the file is closed, basically all situations where something external triggers an exception between the (succesfull) `open` and `close` call, like a badly-timed Ctrl+C for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T17:57:15.187",
"Id": "451531",
"Score": "1",
"body": "@Graipher When \"the `open` raises an exception\" then `with` and `.close` are the same - neither the `with` or the `.close` are reached. Yes, I already mentioned that in my first comment - \"It may, however, ensure a file is closed if an error is raised between the creation and closure of the file.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:06:50.403",
"Id": "451594",
"Score": "0",
"body": "@Gloweye: please consider editing your bug. It is a code fragment. The later handling of the list `is_locked` is irrelevant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:10:34.130",
"Id": "451595",
"Score": "0",
"body": "From the Code Review [ask] page, it is required to be complete code. That makes me assume that the code I read is complete, in which case it's an appropriate statement."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:52:40.340",
"Id": "231416",
"ParentId": "231413",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T15:09:50.880",
"Id": "231413",
"Score": "3",
"Tags": [
"python"
],
"Title": "Recursive check for locked files"
}
|
231413
|
<p>I'm just starting in Go.</p>
<p>Please review the below code, and let me know what I can improve in this code.</p>
<pre><code>//BubbleSort takes an []int {7,5,6,9,8} and returns {5,6,7,8,9}
func BubbleSort(arr []int) []int {
keepRunning := true
for keepRunning {
keepRunning = false
for i := 0; i < len(arr)-1; i++ {
a := arr[i]
b := arr[i+1]
if a > b {
arr[i], arr[i+1] = b, a
keepRunning = true
}
}
}
return arr
}
</code></pre>
<p>//edit
In this case, I'm doing return simply cause I want to return a new copy, and not modify the original.</p>
<p>But I recently as well learned about GO's GC tricolor pattern.
Which will discard the variable until there are no connections left.</p>
<p>So I guess I will need to use the original variable and pass it around and let the code modify the original Slice itself.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:57:52.813",
"Id": "451368",
"Score": "0",
"body": "Do you have any reason to reimplement a slow sort instead of using a decent one already in the language? (this is true regardless of the language in question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T17:19:32.650",
"Id": "451370",
"Score": "4",
"body": "@Nyos im just using it as means of learning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T18:08:19.013",
"Id": "451376",
"Score": "0",
"body": "@Nyos as well not sure why ```\nsort.Slice(elements, func(a, b int) bool {\n return a < b\n })\n``` does not work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T13:00:22.843",
"Id": "451468",
"Score": "0",
"body": "@STEEL: `sort.Slice(elements, func(a, b int) bool { return a < b })` does not work because your `less` function is wrong. See [sort func Slice](https://golang.org/pkg/sort/#Slice): `func Slice(slice interface{}, less func(i, j int) bool)`. For example, https://play.golang.org/p/uP5_XZHWqb8."
}
] |
[
{
"body": "<p>As you only modify value position within the slice and not modify its headers, you do not need to return a slice.</p>\n\n<pre><code>//BubbleSort takes an []int {7,5,6,9,8} and returns {5,6,7,8,9}\nfunc BubbleSort(arr []int) {\n keepRunning := true\n for keepRunning {\n keepRunning = false\n for i := 0; i < len(arr)-1; i++ {\n a := arr[i]\n b := arr[i+1]\n if a > b {\n arr[i], arr[i+1] = b, a\n keepRunning = true\n }\n }\n }\n}\n</code></pre>\n\n<p><a href=\"https://play.golang.org/p/d6wrZ0DYIuG\" rel=\"nofollow noreferrer\">https://play.golang.org/p/d6wrZ0DYIuG</a></p>\n\n<p>that is because slice headers are passed by value, but slice backing array is a pointer. Thus modifying value index does not require to pass around the headers, unlike <code>append</code>.</p>\n\n<p>you could try to figure out how to implement it using a more agnostic API. </p>\n\n<p>IE something like <code>BubbleSort(arr []interface{})</code> </p>\n\n<p>then benchmark it against a standard <code>sort.Slice(interface{})</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T18:04:56.093",
"Id": "451373",
"Score": "0",
"body": "In this case, I actually want to return and a new copy of Slice to avoid mutation. And any way to remove the `keepRunning ` bool, any way kind like Python generator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T18:06:56.257",
"Id": "451375",
"Score": "0",
"body": "in such case i believe it is better to provide the allocation-less implementation version of the algorithm and let the user create a slice and copy the data to it before the sort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T18:11:55.847",
"Id": "451379",
"Score": "0",
"body": "idk what is a python generator. you don t want to prevent mutation by copy, it is slow. the keeprunning variable has little incidence. the size of the slice and the selected sort algorithm are more meaningful. The standard library provides efficient sort implementations that uses a lot of CS to provide the best."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T17:51:37.593",
"Id": "231421",
"ParentId": "231418",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>let me know what I can improve in this code.</p>\n</blockquote>\n\n<hr>\n\n<p>For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.</p>\n\n<p>Writing code is a process of stepwise refinement.</p>\n\n<p>Here's your code. Consider it as a first draft.</p>\n\n<pre><code>func BubbleSort(arr []int) []int {\n keepRunning := true\n for keepRunning {\n keepRunning = false\n for i := 0; i < len(arr)-1; i++ {\n a := arr[i]\n b := arr[i+1]\n if a > b {\n arr[i], arr[i+1] = b, a\n keepRunning = true\n }\n }\n }\n return arr\n}\n</code></pre>\n\n<p>Simplify the code. Express the do ... until construct directly. Remove unnecessary variables. Remove the redundant return value. And so on.</p>\n\n<pre><code>func BubbleSort(a []int) {\n for {\n swap := false\n for i := 1; i < len(a); i++ {\n if a[i-1] > a[i] {\n a[i-1], a[i] = a[i], a[i-1]\n swap = true\n }\n }\n if !swap {\n return\n }\n }\n}\n</code></pre>\n\n<p>Optimize the code. Each pass sorts at least one element to the top.</p>\n\n<pre><code>func BubbleSort(a []int) {\n for i := len(a); i > 0; i-- {\n swap := false\n for j := 1; j < i; j++ {\n if a[j-1] > a[j] {\n a[j-1], a[j] = a[j], a[j-1]\n swap = true\n }\n }\n if !swap {\n return\n }\n }\n}\n</code></pre>\n\n<p>Seek further optimizations. Elements from and above the last swap are sorted.</p>\n\n<pre><code>func BubbleSort(a []int) {\n for i := len(a); i > 1; {\n swap := 0\n for j := 1; j < i; j++ {\n if a[j-1] > a[j] {\n a[j-1], a[j] = a[j], a[j-1]\n swap = j\n }\n }\n i = swap\n }\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/jpoUO5nsJEo\" rel=\"nofollow noreferrer\">https://play.golang.org/p/jpoUO5nsJEo</a></p>\n\n<p>Output:</p>\n\n<pre><code>[7 5 6 9 8]\n[5 6 7 8 9]\n</code></pre>\n\n<p>Write tests using the Go testing package.</p>\n\n<p>Run benchmarks using the Go testing package.</p>\n\n<hr>\n\n<blockquote>\n <p>Comment: I was wondering if I could remove the keepRunning bool\n somehow. and in the above case the swap variable – STEEL</p>\n</blockquote>\n\n<hr>\n\n<p>The swap state variable is used to end the sort as soon as possible. It is not necessary.</p>\n\n<p>For example,</p>\n\n<pre><code>func BubbleSort(a []int) {\n for i := 1; i < len(a); i++ {\n for j := len(a) - 1; j >= i; j-- {\n if a[j-1] > a[j] {\n a[j-1], a[j] = a[j], a[j-1]\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:15:48.800",
"Id": "451509",
"Score": "0",
"body": "Thanks, @peterSO I have edited my OG post. I was wondering if I could remove the `keepRunning` bool somehow. and in the above case the `swap` variable"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T05:09:46.920",
"Id": "231439",
"ParentId": "231418",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "231439",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:25:32.660",
"Id": "231418",
"Score": "3",
"Tags": [
"beginner",
"sorting",
"go"
],
"Title": "Simple BubbleSort in GoLang"
}
|
231418
|
<p>I took a crack at solving the problem of finding the averages of all subarrays of length k. Here is what I came up with. I would greatly appreciate your feedback on my code. </p>
<pre><code>#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
vector<double> findSuseqAverages(size_t k, const vector<int>& nums) {
vector<double> res (nums.size() - k + 1);
auto left_it = nums.begin();
auto right_it = next(left_it, k);
double curr_sum = accumulate(left_it, right_it, 0);
size_t res_index = 0;
res.at(res_index) = curr_sum / k;
while (right_it != nums.end()) {
curr_sum += *right_it - *left_it;
res.at(++res_index) = curr_sum / k;
++right_it;
++left_it;
}
return res;
}
int main() {
vector<int> nums {-1, 0, 1};
size_t k = 2;
vector<double> averages = findSuseqAverages(k, nums);
for (const auto& a: averages) cout << a << " ";
cout << "\n\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T19:46:31.737",
"Id": "451398",
"Score": "0",
"body": "Please be aware that editing the question after it has been answered may not be allowed if it invalidates the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T20:09:12.067",
"Id": "451400",
"Score": "0",
"body": "Refer to https://codereview.stackexchange.com/help/someone-answers and the \"What should I NOT do\" header, which expands upon pacmaninbw's comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T20:14:59.593",
"Id": "451401",
"Score": "0",
"body": "Sorry about that. I am new here. Just removed the \"using namespace std\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T21:02:33.097",
"Id": "451402",
"Score": "0",
"body": "You should also check whether k is at most the length of the array. What is the desired behavior for invalid input?"
}
] |
[
{
"body": "<p>Generally the code is well written, there are only a few items that need commenting on.</p>\n<h2>Avoid Using Namespace <code>std</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier <code>cout</code> you may override within your own classes. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Use Braces Around Single Statements in Program Flow</h2>\n<p>Primarily for maintenance reasons it is a good habit to create code blocks within if statements, else clauses and within loops. Many bugs have been created during maintenance when one or more statements was added to an if statement or a loop.</p>\n<p>From this code:</p>\n<pre><code> for (const auto& a: averages) cout << a << " ";\n</code></pre>\n<p>Would be better as</p>\n<pre><code> for (const auto& a: averages) {\n std::cout << a << " ";\n }\n</code></pre>\n<p>Then if someone needs to add a statement to the for loop at some point it is quite simple.</p>\n<h2>This Code Could Be Simplified</h2>\n<pre><code> vector<double> res (nums.size() - k + 1);\n ...\n\n size_t res_index = 0;\n res.at(res_index) = curr_sum / k;\n\n while (right_it != nums.end()) { \n ...\n res.at(++res_index) = curr_sum / k; \n ... \n }\n</code></pre>\n<p>It's not clear why it was necessary to initialize the <code>res</code> vector to the proper size in the previous code. Since vectors are variable sized they don't need to be initialized with a size.</p>\n<pre><code> std::vector<double> res;\n ...\n\n res.push_back(curr_sum / k);\n\n while (right_it != nums.end()) { \n ...\n res.push_back(curr_sum / k); \n ... \n }\n</code></pre>\n<p>removes one variable and achieves the same result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T19:07:27.967",
"Id": "451395",
"Score": "1",
"body": "There is an efficiency gain by initializing `res` to the proper length. It can avoid multiple reallocs and move copies, especially useful when the length of the input data becomes very large ... often seen in these types of problems seen on programming challenge sites."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T19:13:37.340",
"Id": "451396",
"Score": "0",
"body": "@AJNeufeld then wouldn't an iterator be better than using an index?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T19:19:41.247",
"Id": "451397",
"Score": "2",
"body": "[`std::vector::reserve(...)`](https://en.cppreference.com/w/cpp/container/vector/reserve) & `push_back()` would be best."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T18:57:40.827",
"Id": "231425",
"ParentId": "231419",
"Score": "3"
}
},
{
"body": "<h1>Don't <code>using namespace std;</code></h1>\n<p>Ever.</p>\n<h1>Check that <code>k</code> is reasonable</h1>\n<p>If <code>k</code> is greater than the number of elements, we overflow <code>std::size_t</code> when computing the size of our results array. We should detect this case, and return an empty vector.</p>\n<p>Also, if <code>k</code> is zero, then the call is meaningless - return early or throw an exception in that case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:51:49.200",
"Id": "231466",
"ParentId": "231419",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T17:11:23.107",
"Id": "231419",
"Score": "3",
"Tags": [
"c++",
"array",
"stl"
],
"Title": "Average of subarrays of length k in C++"
}
|
231419
|
<p>Users can have a Cookie called <code>lang</code> that contains either the value "default=1" (English) or "default=2" (French). This cookie is used to determine their preferred language. I have a function that needs to take the cookie and return the language has an Enum. If the cookie doesn't exist, I want to return English. I cannot change the cookie value.</p>
<p>Language enum:</p>
<pre><code> Public Enum Language
Undefined = 0
English = 1
French = 2
End Enum
</code></pre>
<p>Function:</p>
<pre><code> Public Function GetLangFromCookie() As Language
If HttpContext.Current.Request.Cookies.Get("lang") IsNot Nothing Then
Dim langCookie = HttpContext.Current.Request.Cookies.Get("lang").Value
Return If(langCookie(langCookie.Length - 1) = "1", Language.English, Language.French)
End If
Return Language.English
End Function
</code></pre>
<p>I feel like this is not efficient and not secure but I don't know how to improve it. Any suggestions?</p>
|
[] |
[
{
"body": "<ul>\n<li>You query <code>HttpContext.Current.Request.Cookies.Get(\"lang\")</code> twice. Access it once and store it in a variable. </li>\n<li>You will get a problem if in the future you have to support more than 9 languages. Instead of accessing the last char from <code>langCookie</code> you should <code>Split()</code> <code>langCookie</code> by <code>=</code> and take the second array element. You can then use <code>[Enum].TryParse()</code> to get the enum. </li>\n<li>Some horizontal spacing (new lines) would help to easier read the code. </li>\n</ul>\n\n<p>Your code could look like so </p>\n\n<pre><code>Public Function GetLangFromCookie() As Language\n\n Dim langCookie = HttpContext.Current.Request.Cookies.Get(\"lang\")\n\n If langCookie Is Nothing Then\n Return Language.English\n Else\n Return GetLanguage(langCookie.Value)\n End If\n\nEnd Function\n\nPrivate Function GetLanguage(languageCookieValue As String) As Language\n\n Dim splittetCookieValue As String() = languageCookieValue.Split(New String() {\"=\"}, StringSplitOptions.RemoveEmptyEntries)\n\n Dim languageIdentifier As String = splittetCookieValue.LastOrDefault()\n\n Dim foundLanguage As Language\n\n ' We don't care about the success of the TryParse() call\n [Enum].TryParse(Of Language)(languageIdentifier, foundLanguage)\n\n ' because foundLanguage will be 0 if it doesn't succeed and will be checked here\n Return If(foundLanguage = Language.Undefined, Language.English, foundLanguage)\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T05:53:17.757",
"Id": "231441",
"ParentId": "231426",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231441",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T19:48:20.167",
"Id": "231426",
"Score": "2",
"Tags": [
"vb.net",
"enum"
],
"Title": "Cookie value to enum"
}
|
231426
|
<p>I'm currently working on a procedural generated terrain. </p>
<p>I've written the Chunk script, and it works great. When I generate a few chunks in Unity, it runs alright, but it could definitely run better!!! Currently I am not instantiating new chunks at runtime, but when I do, it starts lagging. </p>
<p>I've been looking at multithreading as a solution, but I think it's early in the process to begin win that.</p>
<p>Any suggestions??? Anything can help.</p>
<p>Thanks in advance.</p>
<pre><code>namespace NTerrain
{
public class Chunk
{
public float _chunkTileSize;
public Vector3[] _chunkVertices;
public Vector3 _chunkPosition { get; }
public int[] _chunkTriangles;
public Mesh _chunkMesh;
public MeshFilter _chunkMeshFilter;
public MeshRenderer _chunkMeshRenderer;
public GameObject _chunkObject;
public LOD _chunkLOD;
public ChunkType _chunkType;
public Chunk(LOD chunkLOD, ChunkType chunkType, Vector3 chunkPosition) {
_chunkLOD = chunkLOD;
_chunkType = chunkType;
_chunkPosition = chunkPosition;
_chunkObject = new GameObject();
_chunkObject.transform.position = _chunkPosition;
_chunkMeshFilter = _chunkObject.AddComponent<MeshFilter>();
_chunkMeshRenderer = _chunkObject.AddComponent<MeshRenderer>();
UpdateChunk(LOD.High);
}
public void UpdateChunk(LOD levelOfDetail)
{
_chunkLOD = levelOfDetail;
int squareCount = new int();
switch (_chunkLOD)
{
case LOD.Low:
squareCount = 4;
break;
case LOD.Normal:
squareCount = 8;
break;
case LOD.High:
squareCount = 16;
break;
}
UpdateMesh(squareCount);
}
void UpdateMesh(int levelOfDetail)
{
if (_chunkMesh != null)
{
_chunkMesh.Clear();
_chunkVertices = null;
_chunkTriangles = null;
}
else {
_chunkMesh = new Mesh();
}
_chunkTileSize = 16 / levelOfDetail;
_chunkVertices = new Vector3[levelOfDetail * levelOfDetail * 6];
int vertexCount = 0;
float fixedPos = (-1) * (_chunkTileSize * levelOfDetail) / 2;
for (int y = 0; y < levelOfDetail; y++){
for (int x = 0; x < levelOfDetail; x++){
float xChunkTileSize = x * _chunkTileSize;
float yChunkTileSize = y * _chunkTileSize;
_chunkVertices[vertexCount] = new Vector3(fixedPos + xChunkTileSize, 0, fixedPos + yChunkTileSize);
_chunkVertices[vertexCount + 1] = new Vector3(fixedPos + xChunkTileSize, 0, fixedPos + yChunkTileSize + _chunkTileSize);
_chunkVertices[vertexCount + 2] = new Vector3(fixedPos + xChunkTileSize + _chunkTileSize, 0, fixedPos + yChunkTileSize + _chunkTileSize);
_chunkVertices[vertexCount + 3] = new Vector3(fixedPos + xChunkTileSize, 0, fixedPos + yChunkTileSize);
_chunkVertices[vertexCount + 4] = new Vector3(fixedPos + xChunkTileSize + _chunkTileSize, 0, fixedPos + yChunkTileSize + _chunkTileSize);
_chunkVertices[vertexCount + 5] = new Vector3(fixedPos + xChunkTileSize + _chunkTileSize, 0, fixedPos + yChunkTileSize);
vertexCount += 6;
}
}
_chunkTriangles = new int[levelOfDetail * levelOfDetail * 6];
for (int i = 0; i < _chunkTriangles.Length; i++) {
_chunkTriangles[i] = i;
}
_chunkMesh.vertices = _chunkVertices;
_chunkMesh.triangles = _chunkTriangles;
_chunkMesh.RecalculateNormals();
_chunkObject.GetComponent<MeshFilter>().mesh = _chunkMesh;
}
}
public enum LOD
{
Low,
Normal,
High
}
public enum ChunkType
{
Forest,
Desert,
Arctic
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T23:04:29.587",
"Id": "231429",
"Score": "3",
"Tags": [
"c#",
"performance",
"unity3d"
],
"Title": "Procedural Generation"
}
|
231429
|
<p>I want to compare two solutions to the following question from Cracking The Coding Interview by Gayle Laakman McDowell : </p>
<blockquote>
<p><strong>1.7 Rotate Matrix</strong> - Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image
by 90 degrees. Can you do this in place?</p>
</blockquote>
<p>We will be assuming we have a square matrix to rotate by 90 degrees clockwise like so: </p>
<pre><code>input:
1 2 3
4 5 6
7 8 9
result:
7 4 1
8 5 2
9 6 3
</code></pre>
<p>The book suggests an unusual "layer" method that works its way from the outer edge of the matrix towards the inside</p>
<ul>
<li><a href="https://www.youtube.com/watch?v=aClxtDcdpsQ" rel="nofollow noreferrer">Video explanation by McDowell</a> </li>
<li><a href="https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2001.%20Arrays%20and%20Strings/Q1_07_Rotate_Matrix/Question.java" rel="nofollow noreferrer">McDowell solution code on
Github</a></li>
</ul>
<p>A much more intuitive way to solve this seems to be a matrix transpose, followed by a mirror about the vertical axis. This solution is more intuitive because it uses known mathematical matrix operations - the transposition and the reflection. Aside from this being more obvious and easier to read for who have dealt with matrices in the past, it is also more useful because these individual mathematical operations could be saved for other purposes. </p>
<p>Is there any issue with the following code ? More specifically, what are the pros and cons versus the original McDowell solution ?</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<vector<int>> matrixT;
class Solution {
public:
bool static rotateMatrix(matrixT &mtx){
if (mtx.size() != mtx[0].size() || mtx.size() == 0) return false;
int N = mtx.size();
//transpose matrix
for (int n = 0 ; n<= N-2; n++)
for(int m= n+1 ; m<= N-1; m++)
swap(mtx[n][m], mtx[m][n]);
//vertical mirror
for (int n = 0; n < N; n ++)
for (int m=0; m<N/2 ;m++)
swap(mtx[n][m], mtx[n][N-1-m]);
return true;
}
void static printMatrix(matrixT mtx){
for(int m = 0; m < mtx.size(); m++) {
for(int n = 0; n < mtx.size(); n++)
cout << mtx[m][n] << " ";
cout << endl;
}
}
};
int main() {
cout << "input: " << endl;
matrixT mtx = {{1,2,3},
{4,5,6},
{7,8,9}};
Solution::printMatrix (mtx);
Solution::rotateMatrix (mtx);
cout << "result: " << endl;
Solution::printMatrix (mtx);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:27:20.197",
"Id": "451499",
"Score": "0",
"body": "I've removed [tag:comparative-review] as you only provide one program (the one you've linked to is out of scope, as it's not your code to post)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:40:34.123",
"Id": "451501",
"Score": "0",
"body": "@TobySpeight I've seen your comment and added the other solution to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:42:10.137",
"Id": "451503",
"Score": "0",
"body": "I don't think you're entitled to post that code - did you write it yourself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:46:22.257",
"Id": "451505",
"Score": "1",
"body": "Please be aware that editing questions after they have been answered is discouraged by the community. Please see this help topic https://codereview.stackexchange.com/help/someone-answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T18:16:33.797",
"Id": "451533",
"Score": "1",
"body": "Why would you even move the elements in the matrix? That seems like a very inefficient way of implementing this. I would rather define an interface the converts input coordinates into actual coordinates of the underlying data structure. That way you don't move anything. Then you can have several deferent translations applied to the data and only actually move the data if you want to save it at some point into the new position."
}
] |
[
{
"body": "<p>Keep in mind that the primary focus of this web site is to review your working code and provide suggestions on how to improve the code. Questions about which way is better or worse may be based on opinion and that is off-topic for most of the stack exchange websites.</p>\n<p>In answer to your question, it could be a possible optimization that reduces the number of steps, but that isn't clear. You may be missing the point of the interview, which is that you should explain as clearly as possible to the interviewer(s) what you are doing at each step so they understand your problem solving techniques. Please note that the video code looked more like C rather than C++, but could have also been other languages.</p>\n<h2>Avoid Using Namespace <code>std</code></h2>\n<p>If you are coding professionally you should get out of the habit of using the <code>using namespace std;</code> statement. In an interview you definitely don't want to use this statement because it is unprofessional. The concept of Name Spaces was invented to specifically solve certain problems such as collision of duplicate function names from core code and library code. This <a href=\"//stackoverflow.com/q/1452721\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Use Code Blocks in Flow Control Rather Than Single Statements</h2>\n<p>Professional coders generally put code blocks or complex statements into if statements, else clauses or loop bodies. The reason for this is to enhance the maintainability of the code. To many bugs have been introduced into code by trying to add one statement to an if statement, else clause or loop. A code maintainer may forget to add the necessary braces so putting them in from the beginning is better. It also makes the code more readable and easier to understand to begin with.</p>\n<p>So code like</p>\n<pre><code> int N = mtx.size();\n for (int n = 0 ; n<= N-2; n++)\n for(int m= n+1 ; m<= N-1; m++)\n swap(mtx[n][m], mtx[m][n]);\n</code></pre>\n<p>is better written as</p>\n<pre><code> size_t N = mtx.size();\n for (size_t n = 0 ; n <= N-2; n++)\n {\n for(size_t m= n + 1 ; m <= N-1; m++)\n {\n std::swap(mtx[n][m], mtx[m][n]);\n }\n }\n</code></pre>\n<p>Obviously a maintainer of the code can figure out where to add a statement here.</p>\n<h2>Horizontal Spacing</h2>\n<p>It is common to leave spaces between operator and variable. The horizontal spacing in this code is inconsistent.</p>\n<h2>Prefer <code>std::size_t</code> Over <code>int</code> For Loop Control Variables That Index through C++ Container Classes</h2>\n<p>While the code in the example from this question will compile and run properly there may be warning messages if the strictest level of compiler switch is used. <code>std::vector.size()</code> returns <code>std::size_t</code> which is unsigned, rather than signed. If the strictest level of switches are used a the following loop might yield the warning message <code>type mismatch</code>.</p>\n<pre><code> for (int n = 0 ; n <= mtx.size() - 2; n++)\n {\n for(int m= n + 1 ; m <= mtx.size() - 1; m++)\n {\n std::swap(mtx[n][m], mtx[m][n]);\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T05:04:08.983",
"Id": "451433",
"Score": "1",
"body": "As for your first paragraph: we have [tag:comparative-review]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T01:07:21.310",
"Id": "231435",
"ParentId": "231431",
"Score": "2"
}
},
{
"body": "<p>I would use a virtual view onto the underlying data.</p>\n\n<p>A view simply converts the coordinates from the user specified value into actual data coordinates. No need to actually move any data.</p>\n\n<pre><code>typedef vector<vector<int>> matrixT; \nclass View\n{\n public:\n virtual ~View();\n virtual int& get(int x, int y) = 0\n};\n\nclass IdentityView: public View\n{\n matrixT& data;\n public:\n IdentityView(matrixT& data): data(data) {}\n virtual int& get(int x, int y) override {return data[x][y];}\n};\nclass Rotation90ClockWise: public View\n{\n View& parent;\n public:\n IdentityView(View& data): data(data) {}\n virtual int& get(int x, int y) override\n {\n int actualY = x;\n int actualX = maxX - y - 1;\n return view.get(actualX, actualY);\n }\n};\n// etc lots of transpositions like mirroring rotations can be defined.\n// Apply multiple transitions without doing any moving. Once you have\n// the correct transformation then copy to a destination\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T18:27:50.910",
"Id": "231484",
"ParentId": "231431",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231484",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T23:08:22.330",
"Id": "231431",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"comparative-review",
"matrix"
],
"Title": "Rotate a matrix, using transposition and reflection"
}
|
231431
|
<p>I'm writing a decryption algorithm using GA with crossover and mutation. My performance is (very) poor, often stagnating early or converging to the incorrect solution. I just want some other people to look at my crossover and mutation methods to see if something is amiss.</p>
<p>Note: <code>crossRate</code> and <code>mutatRate</code> are the crossover and mutation rates respectively and are within the range of <code>[0.00, 1.00]</code>. <code>options</code> is a string of valid genes.</p>
<pre class="lang-java prettyprint-override"><code>/**
* method to perform crossover on chromosome
* @param m - the first parent
* @param f - the second parent
* @return - a crossovered chromosome string
*/
private String crossChromosome(String m, String f) {
StringBuilder chrString = new StringBuilder();
// if crossover procs
if (rnd.nextInt(100) < crossRate*100) {
/**
* to avoid full reduplication of chromosome
* set the bound to 2..len-2 otherwise you could
* get duplication of parent, bypassing crossover entirely
*/
int crossPoint = rnd.nextInt(m.length()-2)+2;
// when 2P is used, need a second pivot
int nextCrossPoint = rnd.nextInt(m.length()-crossPoint)+crossPoint;
boolean condition;
for (int i = 0; i < f.length(); i++) { // for each gene
if (crType == 1) {
/**
* if one point crossover, find one point
* in the chromosome where genes before that
* point are from parent1 and after, from parent2
*/
condition = (i < crossPoint);
} else {
/**
* if two point, however, find two pivot points
* and go F,M,F based on the pivot points
*/
condition = (i < crossPoint || i >= nextCrossPoint);
}
if (condition) {
chrString.append(f.charAt(i));
} else {
chrString.append(m.charAt(i));
}
}
} else {
// if no crossover is happening, random parent is used
return (rnd.nextInt(2) == 1) ? f : m;
}
// return the crossovered chromosome
return chrString.toString();
}
/**
* method to mutate a chromosome with random genes
* @param k - the input chromosome
* @return - the mutated chromosome
*/
private String mutateChromosome(String k) {
StringBuilder chrString = new StringBuilder();
for (int i = 0; i < k.length(); i++) { // for each gene
// if mutation procs
if (rnd.nextInt(100) < mutatRate*100) {
// assign a random gene as mutation
chrString.append(options.charAt(rnd.nextInt(27)));
} else {
// otherwise, use verbatim
chrString.append(k.charAt(i));
}
}
return chrString.toString();
}
</code></pre>
<p>There's option of 1-point and 2-point crossover in there.</p>
|
[] |
[
{
"body": "<p>I rewrote parts of your code obtaining an equivalent version with the focus of relying on <code>char</code> arrays instead of <code>String</code> objects to obtain a simpler code. I noticed you use the number 100 in both methods you posted, it could be preferrable declaring a const value like below:</p>\n\n<pre><code>private static final int BOUND = 100;\n</code></pre>\n\n<p>Your method <code>crossChromosome</code> is structured like the code below:</p>\n\n<blockquote>\n<pre><code>private String crossChromosome(String m, String f) {\n if (rnd.nextInt(100) < crossRate*100) { \n //here the body\n }\n else { return (rnd.nextInt(2) == 1) ? f : m; }\n return chrString.toString();\n}\n</code></pre>\n</blockquote>\n\n<p>You can directly put the else body at the beginning of the method with the negation of the condition like the code below:</p>\n\n<pre><code>private String crossChromosome(String m, String f) {\n if (rnd.nextInt(BOUND) >= crossRate * BOUND) {\n return (rnd.nextInt(2) == 1) ? f : m;\n }\n\n //here the instructions of the body of your case\n\n return chrString.toString();\n}\n</code></pre>\n\n<p>You can use <code>char</code> arrays instead of <code>String</code> objects avoiding calls of <code>String</code> methods like the code below:</p>\n\n<pre><code>char[] mArr = m.toCharArray();\nchar[] fArr = f.toCharArray();\nfinal int mLength = mArr.length;\nfinal int fLength = fArr.length;\nfinal int crossPoint = rnd.nextInt(mLength - 2) + 2;\nfinal int nextCrossPoint = rnd.nextInt(mLength - crossPoint) + crossPoint;\n</code></pre>\n\n<p>You can rewrite the loop of your method like below:</p>\n\n<pre><code>StringBuilder chrString = new StringBuilder();\n\nfor (int i = 0; i < fLength; i++) { \n boolean condition = (i < crossPoint);\n\n if (crType != 1 && !condition) {\n condition = (i >= nextCrossPoint);\n }\n char ch = condition ? fArr[i] : mArr[i];\n chrString.append(ch);\n}\n\nreturn chrString.toString();\n</code></pre>\n\n<p>Below the code of your method <code>crossChromosome</code>:</p>\n\n<pre><code>private String crossChromosome(String m, String f) {\n if (rnd.nextInt(BOUND) >= crossRate * BOUND) {\n return (rnd.nextInt(2) == 1) ? f : m;\n }\n\n char[] mArr = m.toCharArray();\n char[] fArr = f.toCharArray();\n final int mLength = mArr.length;\n final int fLength = fArr.length;\n final int crossPoint = rnd.nextInt(mLength - 2) + 2;\n final int nextCrossPoint = rnd.nextInt(mLength - crossPoint) + crossPoint;\n\n StringBuilder chrString = new StringBuilder();\n\n for (int i = 0; i < fLength; i++) { \n boolean condition = (i < crossPoint);\n\n if (crType != 1 && !condition) {\n condition = (i >= nextCrossPoint);\n }\n char ch = condition ? fArr[i] : mArr[i];\n chrString.append(ch);\n }\n\n return chrString.toString();\n}\n</code></pre>\n\n<p>I put <code>condition</code> inside the loop and used the ternary operator.\nSame suggestions for the method <code>mutateChromosome</code>, below my version:</p>\n\n<pre><code>private String mutateChromosome(String k) {\n final int mutatRateMulBound = mutatRate * BOUND;\n char[] kArr = k.toCharArray();\n\n StringBuilder chrString = new StringBuilder();\n\n for (char c : kArr) { \n boolean condition = rnd.nextInt(BOUND) < mutatRateMulBound;\n char ch = condition ? options.charAt(rnd.nextInt(27)) : c;\n chrString.append(ch);\n }\n\n return chrString.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:04:18.520",
"Id": "231457",
"ParentId": "231432",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "231457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T00:28:03.850",
"Id": "231432",
"Score": "2",
"Tags": [
"java",
"genetic-algorithm"
],
"Title": "Crossover and Mutation functions for Genetic Algorithm"
}
|
231432
|
<p>I'm facing the problem of needing to instantiate lots of cars, and I'd like to recycle the cars no longer used. </p>
<p>Each one of my car types, which define how each car should be created, are treated as singletons and there will never be two instances of the same type. I could program this in the example, but lets just assume that they are perfectly managed to only ever have one instance. </p>
<p>Each Car Type is both the definition of how to create the car and also the factory / dispenser for creating new Car instances with that type.</p>
<p>To explain more on why I wish each type to be it's own 'Dispenser', is for the recycling aspect. I expect to be creating lots of cars and also recycling them, so I'd like to keep GC to a minimum. So each type which was already created to the type's requirements can be recycled when it's done being used. Of course I'll be sanitizing the car when it's recycled (Remove the pieces of doritos from inbetween the seats etc').</p>
<p>So there can be one Toyota factory, which is passed to any number of Toyota Car Types. These in turn define the different specifications for the Toyota Car.</p>
<p>The types are essentially taking over the responsibility of customizing the car based on the type once it is out of the factory</p>
<p>You may ask, what's the purpose of the factories in this design, since I could just call new ToyotaCar without using a factory at all.</p>
<p>I wanted to keep the factories since they can be used to track / manage ALL cars of a certain type. </p>
<p>Like for example if I wanted to have the MazdaFactory display a list of all the cars that were created in it and break a random one's breaks. </p>
<p>Does this design break SOLID principles? </p>
<p>Am I overthinking and there's a much simpler approach?</p>
<pre class="lang-cs prettyprint-override"><code>
public interface IDispenser<T>
{
T Dispense();
void Recycle(T t);
}
public class Car{
}
public abstract class CarFactory<T> where T : Car, new()
{
public abstract T newCar();
}
public class DefaultCarFactory<T> : CarFactory<T> where T : Car, new()
{
public override T newCar(){
return new T();
}
}
public abstract class CarType<T> : IDispenser<T> where T : Car, new()
{
protected CarFactory<T> carFactory;
protected Queue<T> recycledCars;
// Each car type has to have a country origin
public String countryOrigin = null;
public CarType()
{
carFactory = new DefaultCarFactory<T>();
recycledCars = new Queue<T>();
}
public CarType(CarFactory<T> carFactory)
{
this.carFactory = carFactory;
recycledCars = new Queue<T>();
}
public abstract T Dispense();
public abstract void Recycle(T t);
}
// Toyota
public class ToyotaCar : Car{}
public class ToyotaCarFactory : CarFactory<ToyotaCar>
{
public override ToyotaCar newCar()
{
return new ToyotaCar();
}
}
public class ToyotaCarType : CarType<ToyotaCar>
{
public String toyotaOrnamentMaterial;
public ToyotaCarType(ToyotaCarFactory toyotaCarFactory, String countryOrigin) : base(toyotaCarFactory)
{
this.countryOrigin = countryOrigin;
}
public override ToyotaCar Dispense()
{
if (recycledCars.Count > 0)
return recycledCars.Dequeue();
ToyotaCar newToyotaCar = carFactory.newCar();
// newToyotaCar.create hood ornament from the material
return newToyotaCar;
}
public override void Recycle(ToyotaCar toyotaCar)
{
recycledCars.Enqueue(toyotaCar);
}
}
// Mazda
public class MazdaCar : Car{}
public class MazdaCarFactory : CarFactory<MazdaCar>
{
public override MazdaCar newCar()
{
return new MazdaCar();
}
}
public class MazdaCarType : CarType<MazdaCar>
{
public MazdaCarType(MazdaCarFactory mazdaCarFactory, String countryOrigin) : base(mazdaCarFactory)
{
this.countryOrigin = countryOrigin;
}
public override MazdaCar Dispense()
{
return carFactory.newCar();
}
public override void Recycle(MazdaCar mazdaCar)
{
recycledCars.Enqueue(mazdaCar);
}
}
public class VariableWheeledMazdaCarType : MazdaCarType
{
public int numberOfWheels = 0;
public VariableWheeledMazdaCarType(MazdaCarFactory mazdaCarFactory, String countryOrigin, int numberOfWheels) : base(mazdaCarFactory, countryOrigin)
{
this.numberOfWheels = numberOfWheels;
}
public override MazdaCar Dispense()
{
if (recycledCars.Count > 0)
return recycledCars.Dequeue();
MazdaCar newMazdaCar = carFactory.newCar();
// Set specific behaviour based on the number of wheels
// newMazdaCar.turnRadius = w/e
return newMazdaCar;
}
}
// A default factory made car, if some type doesn't want to specify a factory that creates it.
public class DefaultMazdaCarType : CarType<MazdaCar>
{
public override MazdaCar Dispense()
{
if (recycledCars.Count > 0)
return recycledCars.Dequeue();
MazdaCar newCar = carFactory.newCar();
return newCar;
}
public override void Recycle(MazdaCar mazdaCar)
{
recycledCars.Enqueue(mazdaCar);
}
}
public class main
{
public static T InstantiateFromType<T>(CarType<T> carType) where T : Car, new()
{
T car = carType.Dispense();
return car;
}
public static void Main()
{
// Mazda
MazdaCarFactory mazdaCarFactory = new MazdaCarFactory();
VariableWheeledMazdaCarType threeWheeledMazdaCarType = new VariableWheeledMazdaCarType(mazdaCarFactory, "Japan", 3);
// Create a three wheeled mazda car
MazdaCar threeWheeledMazdaCar = InstantiateFromType<MazdaCar>(threeWheeledMazdaCarType);
MazdaCarType mazdaCarType = new MazdaCarType(mazdaCarFactory, "Japan");
// Create a default mazda car
MazdaCar defaultMazdaCar = InstantiateFromType<MazdaCar>(mazdaCarType);
// Toyota
ToyotaCarFactory toyotaCarFactory = new ToyotaCarFactory();
ToyotaCarType toyotaCarType = new ToyotaCarType(toyotaCarFactory, "Japan");
// Create a default toyota car
ToyotaCar defaultToyotaCar = InstantiateFromType<ToyotaCar>(toyotaCarType);
ToyotaCar anotherDefaultToyotaCar = toyotaCarType.Dispense();
// Create a car that uses the default factory
DefaultMazdaCarType defaultFactoryCarType = new DefaultMazdaCarType();
MazdaCar defaultFactoryMade = defaultFactoryCarType.Dispense();
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T18:00:25.293",
"Id": "451532",
"Score": "0",
"body": "I think I'll end up going for something a bit simpler which will be mix in object pools in a factory pattern."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T01:21:19.367",
"Id": "231436",
"Score": "1",
"Tags": [
"c#",
"polymorphism"
],
"Title": "Generic car instantiating pattern to minimize GC"
}
|
231436
|
<p>I would like to speed up the following code in R. This is a loop to define new individuals (column <code>newID</code>) when the variable <code>change</code> is equal to 1. Any idea on how to improve the loop will be greatly appreciated. </p>
<p>Here is the code: </p>
<pre><code>## Build the data frame
dat <- expand.grid(x = 1:1000, ID = as.character(seq(0, 4000, 1)))
dat$change <- 0
dat[which(dat$x == 1), c("change")] <- 1
dat[which(dat$x == 300), c("change")] <- 1
dat[which(dat$x == 700), c("change")] <- 1
dat[1, c("change")] <- 0
## Add a column "newID"
dat$newID <- NA
index <- c(1, which(dat$change == 1), nrow(dat))
j <- 1
i <- 1
system.time(while (j < length(index)){
print(paste(j, "/", length(index), sep = " "))
i <- ifelse((j > 1) && (dat[index[j], c("ID")] != dat[index[j - 1], c("ID")]), 1, i)
## print(i)
if(j == length(index) - 1){
dat[seq(index[j], index[j + 1], by = 1), c("newID")] <- paste("Ind ", dat[index[j], c("ID")], "|", i, sep="")
} else{
dat[seq(index[j], index[j + 1] - 1, by = 1), c("newID")] <- paste("Ind ", dat[index[j], c("ID")], "|", i, sep="")
}
j <- j + 1
i <- i + 1
})
## summary(dat)
</code></pre>
<p>Here is an example:</p>
<p>The input data frame has 3 columns. In particular, <code>ID</code> is the ID number of each individual and <code>change</code> takes the value of 1 when the individual is renewed. </p>
<pre><code> x ID change
1 1 0 0
2 2 0 0
3 3 0 0
4 4 0 0
5 5 0 1
6 6 0 0
7 7 0 1
8 8 0 0
9 9 0 0
10 10 0 0
11 1 1 1
12 2 1 0
13 3 1 0
14 4 1 0
15 5 1 1
16 6 1 0
17 7 1 1
18 8 1 0
19 9 1 0
20 10 1 0
21 1 2 1
22 2 2 0
23 3 2 0
24 4 2 0
25 5 2 1
26 6 2 0
27 7 2 1
28 8 2 0
29 9 2 0
30 10 2 0
</code></pre>
<p>The variable <code>newID</code> is created as follows:
When <code>change</code> is equal to 1, <code>newID</code> takes the old ID number and the increment value. Thus, in the example, the expected result is:</p>
<pre><code> x ID change newID
1 1 0 0 Ind 0|1
2 2 0 0 Ind 0|1
3 3 0 0 Ind 0|1
4 4 0 0 Ind 0|1
5 5 0 1 Ind 0|2
6 6 0 0 Ind 0|2
7 7 0 1 Ind 0|3
8 8 0 0 Ind 0|3
9 9 0 0 Ind 0|3
10 10 0 0 Ind 0|3
11 1 1 1 Ind 1|1
12 2 1 0 Ind 1|1
13 3 1 0 Ind 1|1
14 4 1 0 Ind 1|1
15 5 1 1 Ind 1|2
16 6 1 0 Ind 1|2
17 7 1 1 Ind 1|3
18 8 1 0 Ind 1|3
19 9 1 0 Ind 1|3
20 10 1 0 Ind 1|3
21 1 2 1 Ind 2|1
22 2 2 0 Ind 2|1
23 3 2 0 Ind 2|1
24 4 2 0 Ind 2|1
25 5 2 1 Ind 2|2
26 6 2 0 Ind 2|2
27 7 2 1 Ind 2|3
28 8 2 0 Ind 2|3
29 9 2 0 Ind 2|3
30 10 2 0 Ind 2|3
</code></pre>
|
[] |
[
{
"body": "<h2>Do not use explicit loops unless you absolutely have to</h2>\n\n<p>Many functions in R are vectorized and your code will be much faster if you leverage this instead of writing your own loops.</p>\n\n<p>For example, you can compute the first part of your <code>newID</code> with a single <code>paste()</code> call:</p>\n\n<pre><code>dat$newID <- paste(\"Ind\", dat$ID)\n</code></pre>\n\n<pre><code> x ID change newID\n1 1 0 0 Ind 0\n2 2 0 0 Ind 0\n3 3 0 0 Ind 0\n4 4 0 0 Ind 0\n5 5 0 1 Ind 0\n6 6 0 0 Ind 0\n7 7 0 1 Ind 0\n8 8 0 0 Ind 0\n9 9 0 0 Ind 0\n10 10 0 0 Ind 0\n11 1 1 1 Ind 1\n12 2 1 0 Ind 1\n13 3 1 0 Ind 1\n14 4 1 0 Ind 1\n15 5 1 1 Ind 1\n16 6 1 0 Ind 1\n17 7 1 1 Ind 1\n18 8 1 0 Ind 1\n19 9 1 0 Ind 1\n...\n</code></pre>\n\n<h2>The second part of your <code>newID</code> is simply the cumulative sum of <code>change</code></h2>\n\n<p>The most tricky part here is to reset the counter each time the <code>ID</code> changes. A way to do this is to use the function <code>by</code>, which will execute a given function on a group of rows depending on the values of a grouping variable (here <code>ID</code>):</p>\n\n<pre><code>by(dat, dat$ID, function(x) {\n cumsum(x$change)\n})\n</code></pre>\n\n<pre><code>dat$ID: 0\n [1] 0 0 0 0 1 1 2 2 2 2\n--------------------------------------------------------------------------------------------- \ndat$ID: 1\n [1] 1 1 1 1 2 2 3 3 3 3\n--------------------------------------------------------------------------------------------- \ndat$ID: 2\n [1] 1 1 1 1 2 2 3 3 3 3\n</code></pre>\n\n<p>The two issues here are:</p>\n\n<ul>\n<li><code>by</code> returns a list so we have to use <code>unlist()</code> before trying to put the result in a data.frame column</li>\n</ul>\n\n<pre><code>dat$newID <- unlist(by(dat, dat$ID, function(x) {\n cumsum(x$change)\n}))\n</code></pre>\n\n<ul>\n<li>because <code>change</code> doesn't start with 1, the values for the first <code>ID</code> are shifted by one. We can fix this by changing the first value manually.</li>\n</ul>\n\n<h2>Put everything together</h2>\n\n<pre><code>dat$change[1] <- 1\n\ndat$newID <- unlist(by(dat, dat$ID, function(x) {\n cumsum(x$change)\n}))\n\ndat$newID <- paste0(\"Ind \", dat$ID, \"|\", dat$newID)\n</code></pre>\n\n<p>And you get exactly the output you were asking for, without any explicit <code>for</code> loops!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T08:55:57.200",
"Id": "231516",
"ParentId": "231438",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T04:42:49.617",
"Id": "231438",
"Score": "2",
"Tags": [
"performance",
"r"
],
"Title": "Speed up a while loop that conditionally creates a new variable in R"
}
|
231438
|
<p>I have been learning C++ for 3 months now. I decided to make something by myself, so I've made this little integer-based TIC TAC TOE console game.</p>
<p>I need some advice
on how to improve my code for better structure and and better readability.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <stdlib.h>
using namespace std;
int arr[9]={0,1,2,3,4,5,6,7,8}; //Global values of the GAME BOARD for Every move solt
void gameboard(int x); // function for taking the turn of the player and OVERWRITE the player's value i.e [69 for player 1 or 96 for player 2] to the GLOBAL gameboard array as a slot ie [ arr[turn value of the player] ]
void turn(int *player); // function for checking and validating player's move and pass that to to the game board function
void check_win(int player); // function for checking if a player has own or the game has drawn
void initial_board(); //function for printig the initial GAME BOARD before any players turn
void game_over(); //function for endgame condition
int main(int argc, char** argv) {
int a=10,b=11; // player 1 == 69 and player 2 == 96
initial_board(); // printing the initail GAME BOARD for all the empty slots availabe for turn
while(true){ //initiating an infinite loop untill a player has own the game or the game has drawn
turn(&a); // executing the function for PLAYER 1's TURN [69]
turn(&b); // executing the function for PLAYER 2's TURN [96]
}
return 0;
}
void gameboard(int x,int player){ // pass cohice as x and p as player
system("cls");
cout<<" TIC TAC TOE\t\n\n";
cout<<" Player 1: 10 -- Player 2: 11\n\n";
arr[x]=player; // overwrite the element of the array that is the turn input or choice to the player value[example: if (choice is 1 and player valuse is 69) then arr[1]=69 ]
for(int i=0;i<9;i++){ // display the game board
if(i%3==0&&i!=0){ // formatting condition
cout<<"\n";
cout<<"\n";
}
cout<<" | "<<arr[i]<<" | "; // formatting
}
cout<<"\n";
check_win(player); // finally check for win and draw conditions and exit if any of them satisfies
}
void turn(int *player){ // [*player] pass by ref for either player 1 [69] or player 2 [96],,though it can be using pass by valuse as well
int choice,p; // input choice variable for turn and p variable for player value and passing that to the game_board function
p= *player; // pass the value of player ie 69 or 96 to p variable
cout<<"\n"<<" "<<p<<" it is your Turn!!";
cin>>choice; // input turn as choice
if(choice > 8){ // validate if choice is over 8 or not
do{
cout<<"Out of range: Try again-->";
cin>>choice;
}while(choice > 8); // end validation and go for next validation
}
for(int i=0; i<9; i++) // iterate the global slot array
{
if(arr[choice]==10||arr[choice]==11) // check if the turn or choice already exist as player values ie[69 or 96] in the global array
{
do{ // if so then,retake the move because taht is already preasant in the board
cout<<"invalid move!!";
cout<<"place your turn!!";
cin>>choice; // input turn as choice(if choice is under 8) again until it does not exists in the global GAMEVOARD array as player value
if(choice > 8){ //another check for choice over 8. if so,then repeaat input untill its under 8 and doesnt exists in the global gameboard array as player value
do{
cout<<"Out of range: Try again-->";
cin>>choice;
}while(choice > 8);
}
}while(arr[choice]==10||arr[choice]==11);
break; // if all the validation condition satisfies then breakout of the loop nad the input[choice] as final value
}
}
gameboard(choice,p); // pass the final turn input ie choice to the gameboard function and pass the player value as p
}
/// Need to modify win conditions later ////
void check_win(int player){ //pass the player value as player
if(arr[1]+arr[2]+arr[0]==3*10||arr[1]+arr[2]+arr[0]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[3]+arr[4]+arr[5]==3*10||arr[3]+arr[4]+arr[5]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[6]+arr[7]+arr[8]==3*10||arr[6]+arr[7]+arr[8]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[0]+arr[4]+arr[8]==3*10||arr[0]+arr[4]+arr[8]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[2]+arr[4]+arr[6]==3*10||arr[2]+arr[4]+arr[6]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[0]+arr[3]+arr[6]==3*10||arr[0]+arr[3]+arr[6]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[1]+arr[4]+arr[7]==3*10||arr[1]+arr[7]+arr[7]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[2]+arr[5]+arr[8]==3*10||arr[2]+arr[5]+arr[8]==3*11){ //win condition outputs the winner player's name for all
cout<<"\n\n\n"<<" player "<<player<<" has won the game.Congratulations!!!"<<endl;
game_over();
}else if(arr[0] != 0 && arr[1] != 1 && arr[2] != 2 && arr[3] != 3 && arr[4] != 4 && arr[5] != 5 && arr[6] != 6 && arr[7] != 7 && arr[8] != 8){
cout<<"\n\n\n THE GEME IS DRAWN!!!!!!"; // draw condition
game_over();
}
}
void initial_board(){
cout<<" TIC TAC TOE\t\n\n";
cout<<" Player 1: 10 -- Player 2: 11\n\n";
for(int i=0;i<9;i++){ // iterating the global array to show all the slots
if(i%3==0&&i!=0){ // formatting the slots
cout<<"\n";
cout<<"\n";
}
cout<<" | "<<arr[i]<<" | "; // printing the slot values as slots
}
cout<<"\n"; //formatting
}
void game_over(){ // function for ending the game
cout<<" \n\n :The Game is over:\n\n";
system("pause");
exit(1);
}
/*
#########################################
######### END OF PROJECT #########
#########################################
*/
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:32:26.680",
"Id": "451465",
"Score": "2",
"body": "Welcome to Code Review! Can you include an example session of the game?"
}
] |
[
{
"body": "<p>This is not bad for a programmer as new to C++ as you have said you are. Keep up the good work! With that said, here are some ideas on how you might be able to improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. It's not necessarily wrong to use it, but you should be aware of when not to (as when writing code that will be in a header).</p>\n\n<h2>Don't use <code>system(\"cls\")</code></h2>\n\n<p>There are two reasons not to use <code>system(\"cls\")</code> or <code>system(\"pause\")</code>. The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely <strong>must</strong> care about. Specifically, if some program is defined and named <code>cls</code> or <code>pause</code>, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions <code>cls()</code> and <code>pause()</code> and then modify your code to call those functions instead of <code>system</code>. Then rewrite the contents of those functions to do what you want using C++. </p>\n\n<h2>Use the appropriate <code>#include</code>s</h2>\n\n<p>This code has <code>#include <stdlib.h></code> but in a C++ program that should actually be <code><cstdlib></code> which puts the various declarations into the <code>std::</code> namespace rather than in the global namespace. However in this case, if you follow the immediately previous suggestion, the code will use nothing from that and so the <code>#include</code> can simply be eliminated.</p>\n\n<h2>Use whitespace to improve readability</h2>\n\n<p>Lines like this:</p>\n\n<pre><code>}while(arr[choice]==10||arr[choice]==11);\n</code></pre>\n\n<p>become much easier to read with a little bit of whitespace:</p>\n\n<pre><code>} while (arr[choice] == 10 || arr[choice] == 11);\n</code></pre>\n\n<h2>Use constant string concatenation</h2>\n\n<p>This code currently has a number of instances that look like this:</p>\n\n<pre><code>cout<<\"invalid move!!\";\ncout<<\"place your turn!!\";\n</code></pre>\n\n<p>This calls the <code><<</code> operator twice. Instead, you could write this:</p>\n\n<pre><code>std::cout << \"invalid move!!\\n\"\n \"place your turn!!\";\n</code></pre>\n\n<p>This only calls <code><<</code> once. The compiler automatically concatenates the string literals together.</p>\n\n<h2>Consider using standard length lines</h2>\n\n<p>The comments in the code are very long and some lines are over 200 characters. Neither of these things are necessarily wrong, but they are different from the usual convention which is to make sure that lines are no more than around 80 characters long. Some use 132 characters as a limit. Both of these stem from historical limitations of standard printers and displays, and while those are history, the convention is still widely used.</p>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error. The global variable <code>arr</code> (which is not a good name, by the way) could instead be wrapped in an object to make it easy to differentiate between read access and an update and to keep the state of the game consistent and accurate.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The <code>checkwin()</code> function includes large portions of repeated code. Instead of repeating code, it's generally better to make common code into a function.</p>\n\n<h2>Omit unused variables</h2>\n\n<p>Because <code>argc</code> and <code>argv</code> are unused, you could use the alternative form of <code>main</code>:</p>\n\n<pre><code>int main ()\n</code></pre>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>This code has a number of inscrutable \"magic numbers,\" that is, unnamed constants such as 3, 10, 11, etc. Generally it's better to avoid that and give such constants meaningful names. That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of \"3\" and then trying to determine if this <em>particular</em> 3 is relevant to the desired change or if it is some other constant that happens to have the same value.</p>\n\n<h2>Use longer, more meaningful names</h2>\n\n<p>Names like <code>p</code> and <code>a</code> and <code>b</code> and <code>arr</code> are not very descriptive. Better names help the reader of the code understand what is happening and why.</p>\n\n<h2>Don't mislead with comments</h2>\n\n<p>The code currently contains this peculiar line:</p>\n\n<pre><code>int a = 10, b = 11; // player 1 == 69 and player 2 == 96\n</code></pre>\n\n<p>The comments and the code contradict each other. If the variables were given better names, you could simply eliminate the comment:</p>\n\n<pre><code>int player1 = 10;\nint player2 = 11;\n</code></pre>\n\n<h2>Declare each variable on its own line</h2>\n\n<p>Declaring each variable on its own line avoids certain kinds of errors and leaves more room for a meaningful comment, if needed. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es10-declare-one-name-only-per-declaration\" rel=\"noreferrer\">ES.10</a></p>\n\n<h2>Use rational return values</h2>\n\n<p>All of your functions return <code>void</code> and half take no parameters. This is highly suspect. For example, it would make more sense to have <code>turn</code> return a <code>bool</code> value to indicate that the player who just played has won the game. See the next suggestion.</p>\n\n<h2>Declare the loop exit condition at the top</h2>\n\n<p>The <code>main</code> routine has this seemingly endless loop:</p>\n\n<pre><code>while (true) {\n turn(&a);\n turn(&b);\n}\n</code></pre>\n\n<p>However the comment indicates that it's not <em>really</em> an infinite loop, but that the game ends when either one player wins or the game is a tie. It would be better to make that explicit <em>in the code itself</em> rather than just in the comment.</p>\n\n<pre><code>while ((!turn(&a) && !tie()) && (!turn(&b) && !tie()))\n{ /* keep playing until game end */ }\n</code></pre>\n\n<p>This uses <em>short-circuit</em> evaluation, which means that, in the case of an <code>&&</code> expression, if the first condition is not true, the second one won't be evaluated. In this case, we assume that <code>turn</code> returns <code>true</code> if that player has just won and that a new function <code>tie</code> returns true if the game is a tie.</p>\n\n<h2>Separate input, output and calculation</h2>\n\n<p>To the degree practical it's usually good practice to separate input, output and calculation for programs like this. By putting them in separate functions, it isolates the particular I/O for your platform (which is likely to be unique to that platform or operating system) from the logic of the game (which does not depend on the underlying OS). </p>\n\n<h2>Have you run a spell check on comments?</h2>\n\n<p>If you run a spell check on your comments, you'll find a number of things such as \"GAMEVOARD\" instead of \"GAMEBOARD\" and \"nad\" instead of \"and\". Also in the case of a tie, the user is informed that \"THE GEME IS OVER\" (instead of the \"GAME\"). It's worth the extra step to eliminate spelling errors, especially in user-visible strings.</p>\n\n<h2>Think of the user</h2>\n\n<p>The game seems to work and follow the usual conventions for the game, but the use of <code>10</code> and <code>11</code> is a bit strange for users. Consider using instead the typical text characters <code>X</code> and <code>O</code>. There is some indication that perhaps you tried to do that. A hint in that regard: if you keep letters in the game array instead of <code>int</code> values, you may find it easier to manage.</p>\n\n<h2>Don't pass raw pointers</h2>\n\n<p>The <code>turn()</code> function is passed a pointer to the <code>player</code> value which is not a good idea. Modern C++ makes very little use of raw pointers. Instead, it would make more sense to do it as was done for the <code>check_win()</code> code and simply pass by value since what's being passed is not a gigantic structure (that would take time and memory to copy) but just an <code>int</code> which likely fits in a machine register.</p>\n\n<h2>Eliminate <code>return 0</code></h2>\n\n<p>You don't need to explicitly provide a <code>return 0;</code> at the end of main -- it's created implicitly by the compiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:47:33.630",
"Id": "451517",
"Score": "1",
"body": "Related to line length, while some programming books or teachers put comments after a line of code in practice it is much more common to have your comment on the line above"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T20:27:38.183",
"Id": "451546",
"Score": "1",
"body": "wow, for a beginner, those tips are golden"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T06:37:37.733",
"Id": "451583",
"Score": "0",
"body": "Thank you for pointing out the mistakes and for the tips. I will keep these in mind for next projects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T12:28:12.183",
"Id": "451775",
"Score": "0",
"body": "\"Use whitespace to improve readability \" - think about reading a book, are all the words clumped together,or are they spaced, so the eye can more easily distinguish the words?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:07:45.907",
"Id": "231464",
"ParentId": "231442",
"Score": "32"
}
},
{
"body": "<p>There's a typo in this line:</p>\n\n<blockquote>\n<pre><code>}else if(arr[1]+arr[4]+arr[7]==3*10||arr[1]+arr[7]+arr[7]==3*11){ //win condition outputs the winner player's name for all\n</code></pre>\n</blockquote>\n\n<p>I think that the second <code>7</code> was intended to be <code>4</code>.</p>\n\n<p>That's the kind of thing that tends to happen when you repeat large blocks of similar code. And most readers won't spot that.</p>\n\n<p>What you should do is identify the patterns in your groups:</p>\n\n<ul>\n<li>Horizontal lines start at 0, 3 or 6, with step size of 1</li>\n<li>Vertical lines start at 0, 1 or 2, with step size of 3</li>\n<li>Leading diagonal starts at 0, with step size of 4</li>\n<li>Trailing diagonal starts at 2, with step size of 2</li>\n</ul>\n\n<p>With that observation, it should be easy to replace those lines with simple function calls. That will make your code easier to write and to review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T06:37:49.683",
"Id": "451584",
"Score": "0",
"body": "Thank you for pointing out the mistakes and for the tips. I will keep these in mind for next projects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:09:55.327",
"Id": "231468",
"ParentId": "231442",
"Score": "10"
}
},
{
"body": "<p>Your conditions testing for victory have a bug, due to your choice of data structure.</p>\n\n<p>In the array <code>arr</code>, a number from 0 to 8 represents an empty space, and a number 10 or 11 represents \"X\" or \"O\". (This is what I infer from your code; it would have been helpful to document it using a comment where the array is declared.)</p>\n\n<p>It follows that the condition <code>arr[6] + arr[7] + arr[8] == 3*10</code> is true when the first player has played in cells 6, 7 and 8. However, because 11 + 11 + 8 = 30, it is <em>also</em> true when the second player has played in cells 6 and 7, and cell 8 remains empty. The same applies for other win conditions involving cell 8.</p>\n\n<p>This bug could be fixed by using different numbers to represent the players' moves. I would suggest using 1, -1 and 0 to represent \"X\", \"O\" and \"empty\" respectively. There is no need for different empty cells to be represented in the data structure by different numbers; if you want to <em>print</em> the board with numbers in the empty cells, then the code to achieve that belongs in the function which prints the board.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:38:20.027",
"Id": "451670",
"Score": "0",
"body": "Welcome to Code Review. Good job spotting that bug!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T16:23:26.973",
"Id": "451681",
"Score": "0",
"body": "Thank you for pointing this out. I didn't notice this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:03:19.457",
"Id": "231549",
"ParentId": "231442",
"Score": "2"
}
},
{
"body": "<p>You asked about structure and readability, so this answer will mostly be about that, and I will not include much code, only concepts.</p>\n\n<p>First off, your console app is really more \"C\" than \"C++\" - it is <em>procedural</em>, rather than <em>object-oriented</em>, so you're not really using the <strong>++</strong> here. There's nothing really wrong with that, unless you want to learn object-oriented programming. Generally when someone says \"I'm learning C++\" we will want to see them doing object-oriented stuff, otherwise they would say they are learning C.</p>\n\n<p>Tic-tac-toe lends itself very nicely to beginning object-oriented concepts, and there are many design patterns which could be used to implement a Tic-tac-toe game! It is a very good choice of game for learning these ideas.</p>\n\n<p>Example design pattern - MVC (model-view-controller) - <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller</a></p>\n\n<p>Most computer programs need to create a logical \"model\" of some \"thing\" in the real world, in this case it is a game board for Tic-tac-toe. In your app, you are using an array of numbers for this. In a C++ app, we would use a <strong>class</strong> that represents a game board, and is responsible for things like storing the current board state, determining if a player's attempted move is legal, determining if the game has been won, the size of the board(!) and other things like that. These \"things\" can be divided into \"data\" and \"actions\" - which will become your member variables and methods, respectively. This class would become your MODEL in the MVC pattern.</p>\n\n<p>In order to display things on the screen, you would need a class that handles that sort of thing, which would become your VIEW in the MVC pattern. This class would handle the specifics of whatever output device you are using, and you could even have multiple views that display the same MODEL, so you could draw different graphics on a phone, than you would on a web browser, or you could even create a physical game board if you were using Arduino for example. All of those different views could use the exact same MODEL class described above. The view could also create various user interface elements that work for the output it is creating - for example, the phone view could respond to screen touches, while the Arduino view would respond to button presses.</p>\n\n<p>In order to \"glue\" your model and view together, that is where the CONTROLLER comes in. The controller is responsible for taking data from the model and passing it to the view, or taking data from the view/user and passing it to the model. In this way, your view doesn't need to contain any game logic, and your model doesn't need any display or user interface logic, making BOTH objects way more useful.</p>\n\n<p>There is already an example of this on the site: <a href=\"https://codereview.stackexchange.com/questions/71756/tic-tac-toe-in-mvc\">Tic Tac Toe in MVC</a></p>\n\n<p>It is in Java, but it is very similar to C++, so it should be readable to you.</p>\n\n<p>The MVC pattern is a natural result of applying the \"Single Responsibility Principle\" which can be applied at many levels from the application down to the individual blocks of code. Every class should have a single responsibility (such as \"manage the game board data\"), but so also should every function within each class. So, you wouldn't have a class that handled the model and the view, and you wouldn't have a function that, for example, enters the players move AND checks if they won. You would have two separate functions. This makes your code both more readable and more useful. (For example, because in the first 2 moves, the controller doesn't need to check for a winner, and for larger boards, this number becomes even larger, providing a possible performance improvement at the beginning of the game.)</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Single_responsibility_principle</a></p>\n\n<p>I hope that is helpful. I know I'm suggesting completely re-working the whole thing, but if you want to create well structured and readable <strong>C++</strong>, we need to be doing objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T17:24:43.183",
"Id": "231561",
"ParentId": "231442",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:07:30.433",
"Id": "231442",
"Score": "13",
"Tags": [
"c++",
"beginner",
"tic-tac-toe"
],
"Title": "Tic Tac Toe console program"
}
|
231442
|
<p>I have a code that turns all comments size to autosize, however as I have quite a few cells with comments, this code runs a little slow, to the point where it will become non responsive for awhile.</p>
<pre><code>Sub AutoSizeComments()
Dim c as range, ws as worksheet
Set ws = ActiveSheet
'Loop through each comment on worksheet
For Each c In ws.Cells.SpecialCells(xlCellTypeComments)
c.Comment.Shape.TextFrame.AutoSize = True
Next c
End Sub
</code></pre>
<p>After some research online, I still could not find a way to make this faster. As I am new to VBA coding, I am not sure if there is any way to make this code run faster. Thanks for helping and if this is the fastest way, let me know too. Thank you all.</p>
|
[] |
[
{
"body": "<p>as I research more and tried different ways, I have found that I can use the application.screenupdating way to make my whole program run faster and since this question have been unanswered for quite awhile, I will mark this as my answer once a week has past since I asked this question. however I will still be checking to see if there is any better answers posted here till then. Thank you all!</p>\n\n<pre><code>Sub AutoSizeComments()\n Dim c as range, ws as worksheet\n\n Application.ScreenUpdating = False\n Set ws = ActiveSheet\n 'Loop through each comment on worksheet\n For Each c In ws.Cells.SpecialCells(xlCellTypeComments)\n c.Comment.Shape.TextFrame.AutoSize = True\n Next c\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T05:40:50.383",
"Id": "231814",
"ParentId": "231443",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "231814",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:08:38.253",
"Id": "231443",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Changing all comments' size in range to autosize"
}
|
231443
|
<p>I have the structure Corporation/Company/Facility/Storage and only Storage could be part of Facility, and Facility could be part of Company, and Company part of Corporation. <strong>My main problem is for the code to work I need to add the Corporation to itself.</strong></p>
<pre><code>public class BusinessEntityData
{
public Guid ID { get; set; }
public Guid ParentID { get; set; }
public string Title { get; set; }
public string Number { get; set; }
public int Type { get; set; }
}
public static class Context
{
public static List<BusinessEntityData> BusinessEntityList { get; set; } = new List<BusinessEntityData>();
}
</code></pre>
<p>This is how the data entity looks like and the context is for static list which I'm using for testing.</p>
<pre><code>public interface IBusinessEntity
{
string Title { get; set; }
string Number { get; set; }
int Type { get; set; }
List<BusinessEntityData> GetChildren(string number);
void AddBusinessEntity(IBusinessEntity entity);
void Remove(IBusinessEntity entity);
void Validate(IValidationVisitor visitor, BusinessEntityData data);
}
public interface IValidationVisitor
{
void VisitCompany(BusinessEntityData data);
void VisitFacility(BusinessEntityData data);
void VisitCorporation(BusinessEntityData data);
void VisitStorage(BusinessEntityData data);
}
</code></pre>
<p>This are both interfaces which I use for the VisitorPattern and Composite.</p>
<p>Here I implement the interface. Let's assume that the numbers are unique between all objects.</p>
<pre><code>public abstract class AbstractBusinessEntity : IBusinessEntity
{
public string Title { get; set; }
public string Number { get; set; }
public int Type { get; set; }
public AbstractBusinessEntity(string number, string title)
{
Title = title;
Number = number;
}
public void AddBusinessEntity(IBusinessEntity entity)
{
var currentElement = Context.BusinessEntityList.FirstOrDefault(x => x.Number == this.Number);
var visitor = new ParentValidationVisitor();
var data = new BusinessEntityData()
{
ID = Guid.NewGuid(),
Title = entity.Title,
Number = entity.Number,
Type = entity.Type,
ParentID = currentElement == null ? Guid.Empty : currentElement.ID
};
Validate(visitor, data);
Context.BusinessEntityList.Add(data);
}
public List<BusinessEntityData> GetChildren(string number = null)
{
if (number == null)
number = this.Number;
List<BusinessEntityData> list = new List<BusinessEntityData>();
var currentElement = Context.BusinessEntityList.FirstOrDefault(x => x.Number == number);
if (currentElement == null)
return new List<BusinessEntityData>();
var children = Context.BusinessEntityList.Where(x => x.ParentID == currentElement.ID);
foreach(var item in children)
{
list.Add(item);
list.AddRange(GetChildren(item.Number));
}
return list;
}
public void Remove(IBusinessEntity entity)
{
var result = Context.BusinessEntityList.FirstOrDefault(x => x.Number == entity.Number);
if (result == null)
return;
Context.BusinessEntityList.Remove(result);
}
public abstract void Validate(IValidationVisitor visitor, BusinessEntityData data);
}
</code></pre>
<p>My classes <code>Facility</code>, <code>Corporation</code>, <code>Company</code> and <code>Storage</code> are inheriting this <code>AbstractBusinessEntity</code> and only implement the Validate method in which I call separate visitor method.</p>
<p>This is how the visitor is looks like:</p>
<pre><code>public class ValidationVisitor : IValidationVisitor
{
public void VisitCorporation(BusinessEntityData data)
{
if (data.Type == (int)Helper.BusinessEntityType.Corporation)
return;
if (data.Type == (int)Helper.BusinessEntityType.Company)
return;
throw new BusinessEntityValidationException("You can add only Companies to Corporation");
}
public void VisitCompany(BusinessEntityData data)
{
if (data.Type == (int)Helper.BusinessEntityType.Facility)
return;
throw new BusinessEntityValidationException("You can add only Facility to Companies");
}
public void VisitFacility(BusinessEntityData data)
{
if (data.Type == (int)Helper.BusinessEntityType.Storage)
return;
throw new BusinessEntityValidationException("You can add only Storage to Facility");
}
public void VisitStorage(BusinessEntityData data)
{
throw new BusinessEntityValidationException("You can't add any business entity to Storage");
}
}
</code></pre>
<p><strong>Should the validation be in the visitor patter ?</strong> </p>
<p><strong>Really strange to me is that when I run the program for this code to work properly I need to add Corporation to itself, to add the first element in the collection.</strong></p>
<pre><code> Corporation corporation = new Corporation("Corporation", "Corporation TEst");
corporation.AddBusinessEntity(corporation);
var company1 = new Company("Company1", "Company1");
var company2 = new Company("Company2", "Company2");
var company3 = new Company("Company3", "Company3");
corporation.AddBusinessEntity(company1);
corporation.AddBusinessEntity(company2);
corporation.AddBusinessEntity(company3);
</code></pre>
<p>I'm not sure if this is the proper way of doing it. Another way is the corporation to be out of the tree structure, but I'm not sure if this is correct as business logic. What could be a better approach ?</p>
<p>Here <a href="https://github.com/mybirthname/CompositePattern" rel="nofollow noreferrer">Github demo</a> for full code of the example.</p>
<p>Here <a href="https://dotnetfiddle.net/4GyleS" rel="nofollow noreferrer">DotNetFiddle</a> for full example. (not really good readability)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:05:14.240",
"Id": "451456",
"Score": "0",
"body": "What's the point of having both `BusinessEntityData` and `AbstractBusinessEntity `?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:13:42.703",
"Id": "451458",
"Score": "0",
"body": "@BohdanStupak I made it look like close to entity framework. BusinessEntityData will be the entity which will be saved into the database. The Abstract class defines how the logic will work in every class which is part of the tree structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:21:23.060",
"Id": "451459",
"Score": "0",
"body": "So if `BusinessEntityData` is solely for persistence this means that you `Validate` method is concerned with persistence rather than business logic."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T07:38:06.207",
"Id": "231445",
"Score": "1",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Tree Structure using Composite and Visitor Pattern"
}
|
231445
|
<p>I want to manage the Excel Styles in a more flexible way with bulk actions and at the same time improve my newly acquired OOP concepts.</p>
<p>Objectives:</p>
<ul>
<li><p>Load the current Styles list (name and type=builtin or custom) in an Excel Structured Table (ListObject)</p></li>
<li><p>Allow users to:</p>
<ol>
<li><p>Delete</p></li>
<li><p>Duplicate (create a new style based on another)</p></li>
<li><p>Replace (one style with another)</p></li>
</ol></li>
</ul>
<p><a href="https://i.stack.imgur.com/HOxVe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HOxVe.png" alt="enter image description here"></a></p>
<p>Main events:</p>
<p>1) Press "Load" button -> Load the workbook (thisworkbook) styles list into the Excel structured table</p>
<p>2) Press "Process" button -> Review each cell of the Source column in the Excel Table and run the selected action</p>
<p>Actions:</p>
<ul>
<li><p>When user selects "Delete" -> The Excel Style based on the source column will be deleted</p></li>
<li><p>When user selects "Duplicate" -> A new Excel Style should be created with the name defined in the table column "Duplicated new style name | replace with"</p></li>
<li><p>When user selects "Replace" -> All instances where the Style is found in the workbook should be replaced with the one defined in the table column "Duplicated new style name | replace with"</p></li>
</ul>
<p>Question: How can I structure this classes to add more Actions based on Composition?</p>
<p>Question: Would the Factory Pattern help to make this classes easier to maintain?</p>
<p><strike>Maybe</strike> this is <strike>an overkill</strike> the best way to manage styles, <strike>but</strike> and I want to do it <strike>as a proof of concept too and</strike> to learn more about OOP.</p>
<p>Any help reviewing the code I'd appreciate.</p>
<p>Module: mStyles</p>
<pre><code>'@Folder("Styles")
Option Explicit
Sub LoadStyles()
Dim myStyles As cStyles
Set myStyles = New cStyles
myStyles.LoadToTable
End Sub
Sub ProcessStyles()
Dim myStyles As cStyles
Set myStyles = New cStyles
myStyles.LoadFromTable
myStyles.ProcessStyles
myStyles.LoadToTable
End Sub
</code></pre>
<p>Class: cStyle</p>
<pre><code>'@Folder("Styles")
Option Explicit
Private Type TStyle
Style As Style
Name As String
Action As String
Target As String
Exists As Boolean
End Type
Private this As TStyle
Public Property Let Name(value As String)
this.Name = value
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Action(value As String)
this.Action = value
End Property
Public Property Get Action() As String
Action = this.Action
End Property
Public Property Let Target(value As String)
this.Target = value
End Property
Public Property Get Target() As String
Target = this.Target
End Property
Public Property Set Style(ByRef Style As Style)
Set this.Style = Style
End Property
Public Property Get Style() As Style
Set Style = this.Style
End Property
Public Sub Init(Name, Action, Target)
this.Name = Name
this.Action = Action
this.Target = Target
If Exists Then
Set this.Style = ThisWorkbook.Styles(this.Name)
End If
End Sub
Public Function Exists() As Boolean
' Returns TRUE if the named style exists in the target workbook.
On Error Resume Next
Exists = Len(ThisWorkbook.Styles(this.Name).Name) > 0
On Error GoTo 0
End Function
Public Function Duplicate() As Style
Dim styleCell As Range
Dim newName As String
Set styleCell = MStyles.Range("E1")
styleCell.Style = this.Name
newName = this.Target
Set Duplicate = ThisWorkbook.Styles.Add(newName, styleCell)
styleCell.Clear
End Function
Public Sub Delete()
If Exists Then this.Style.Delete
End Sub
Public Sub Replace()
Dim evalCell As Range
Dim newStyle As Style
Dim replaceSheet As Worksheet
Set newStyle = ThisWorkbook.Styles(this.Target)
For Each replaceSheet In ThisWorkbook.Worksheets
For Each evalCell In replaceSheet.UsedRange.Cells
If evalCell.Style = this.Style And evalCell.MergeCells = False Then evalCell.Style = newStyle
Next evalCell
Next replaceSheet
End Sub
</code></pre>
<p>Class: cStyles</p>
<pre><code>'@Folder("Styles")
Option Explicit
Private Type TStyles
Styles As Collection
End Type
Private this As TStyles
Private Sub Class_Initialize()
Set this.Styles = New Collection
End Sub
Private Sub Class_Terminate()
Set this.Styles = Nothing
End Sub
Public Sub Add(obj As cStyle)
this.Styles.Add obj
End Sub
Public Sub Remove(Index As Variant)
this.Styles.Remove Index
End Sub
Public Property Get Item(Index As Variant) As cStyle
Set Item = this.Styles.Item(Index)
End Property
Property Get Count() As Long
Count = this.Styles.Count
End Property
Public Sub Clear()
Set this.Styles = New Collection
End Sub
Public Sub LoadToTable()
Dim stylesTable As ListObject
Dim curStyle As Style
Dim tempStyleInfo() As Variant
Dim counter As Integer
Dim counterStyles As Integer
counterStyles = ThisWorkbook.Styles.Count
ReDim tempStyleInfo(counterStyles, 3)
Set stylesTable = MStyles.ListObjects("TableStyles")
If Not stylesTable.DataBodyRange Is Nothing Then stylesTable.DataBodyRange.Delete
For Each curStyle In ThisWorkbook.Styles
tempStyleInfo(counter, 0) = curStyle.Name
tempStyleInfo(counter, 1) = IIf(curStyle.BuiltIn, "BuiltIn", "Custom")
counter = counter + 1
Next curStyle
stylesTable.Resize stylesTable.Range.Resize(RowSize:=UBound(tempStyleInfo, 1))
stylesTable.DataBodyRange = tempStyleInfo
End Sub
Public Sub LoadFromTable()
Dim stylesTable As ListObject
Dim styleCell As cStyle
Dim cellStyle As Range
Set stylesTable = MStyles.ListObjects("TableStyles")
For Each cellStyle In stylesTable.DataBodyRange.Columns(1).Cells
If cellStyle.Offset(ColumnOffset:=2) <> "" Then
Set styleCell = New cStyle
styleCell.Init cellStyle.Value2, cellStyle.Offset(ColumnOffset:=2).Value2, cellStyle.Offset(ColumnOffset:=3).Value2
this.Styles.Add styleCell
End If
Next cellStyle
End Sub
Public Sub ProcessStyles()
Dim styleCell As cStyle
For Each styleCell In this.Styles
Select Case styleCell.Action
Case "Delete"
styleCell.Delete
Case "Duplicate"
styleCell.Duplicate
Case "Replace"
styleCell.Replace
End Select
Next styleCell
End Sub
</code></pre>
<p><a href="https://1drv.ms/x/s!ArAKssDW3T7wnK5dMeiQoorsWRBQtA" rel="nofollow noreferrer">Link to the current file</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:42:27.640",
"Id": "451467",
"Score": "0",
"body": "*Maybe this is an overkill way to manage styles* - only if you consider VBA a \"toy language\" that doesn't do OOP ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:39:06.740",
"Id": "451500",
"Score": "0",
"body": "You're right @MathieuGuindon question updated ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T00:13:37.963",
"Id": "451565",
"Score": "0",
"body": "Posted a follow up question [here](https://codereview.stackexchange.com/questions/231499/manage-excel-styles-with-vba-oop-approach-follow-up)"
}
] |
[
{
"body": "<p>Code is generally very clean, although I do have a number of reservations with some of the naming: <code>c</code> prefix for class modules, <code>M</code> for standard ones, is pure noise; <code>Cell</code> as a suffix for something that isn't a <em>cell</em>, is confusing. That kind of thing.</p>\n\n<p>I would have named <code>cStyles</code> as <code>Styles</code>, or perhaps <code>StyleProcessor</code> since we don't want to hide <code>Excel.Styles</code>; anything that makes it sound like it's more than just a custom collection of styles would probably be a good name. <code>MStyles</code> is confusing - I'd just call it <code>Macros</code>, since all it contains is, well, macros (/entry-point procedures), and too many things are \"styles\" here.</p>\n\n<p>The internal <code>Private Type</code> isn't being useful here. If there was a <code>Styles</code> property, it would be. But there isn't, so it's not helping with any name-clashing properties/private fields.</p>\n\n<p>The <code>cStyle</code> class, I'd probably name it <code>StyleConfig</code>, or <code>StyleInfo</code> - plain <code>Style</code> would be hiding <code>Excel.Style</code>, and we would rather avoid doing that. If we go with <code>StyleInfo</code>, then <code>infos</code> makes a reasonably sensible name for it:</p>\n\n<pre><code>Private infos As Collection\n</code></pre>\n\n<hr>\n\n<p>A <em>Factory Pattern</em> doesn't directly make code easier to maintain. In fact it could be argued that it makes things more complicated! <a href=\"http://rubberduckvba.wordpress.com/?p=7256\" rel=\"nofollow noreferrer\">Dependency Injection in VBA</a> explains where and why you would want to use a <em>factory pattern</em>: it's a tool to help reduce <em>coupling</em>. In itself, a factory method is little more than an <code>Init</code> method that, instead of initializing the current instance, creates, initializes, and returns a new one - effectively allowing parameterized initialization of objects, like constructors do in other languages.</p>\n\n<p>Having a <em>factory method</em> on <code>cStyle</code> (with a default instance / predeclared ID) would remove the need to have an <code>Init</code> method, so you could do this:</p>\n\n<pre><code>this.Styles.Add cStyle.Create(...)\n</code></pre>\n\n<p>A <em>factory method</em> can't really hurt, but a <em>factory pattern</em> would indeed be overkill: you don't need to decouple <code>cStyle</code> from <code>cStyles</code>, the two classes are <em>tightly coupled</em>, but unless you're looking to decouple the <code>Excel.Style</code> dependency, there's little to gain here IMO.</p>\n\n<blockquote>\n <p><em>Question: How can I structure this classes to add more Actions based on Composition?</em></p>\n</blockquote>\n\n<p>You'd have to extract an <code>IAction</code> (or <code>IStyleAction</code>) class/interface, and implement it with some <code>DeleteStyleAction</code>, <code>DuplicateStyleAction</code>, and <code>ReplaceStyleAction</code> classes, and then <code>ProcessStyles</code> (I'd trim it to just <code>Process</code>) starts looking very much like a <em>strategy pattern</em>:</p>\n\n<pre><code>Public Sub Process()\n Dim info As StyleInfo\n For Each info In infos\n Dim strategy As IStyleAction\n Set strategy = styleActions(info.Action)\n strategy.Run\n Next\nEnd Sub\n</code></pre>\n\n<p>Where <code>IStyleAction</code> is a class/interface stub exposing a simple <code>Run</code> method, and <code>styleActions</code> could be a simple keyed collection:</p>\n\n<pre><code>Private Sub Class_Initialize()\n Set infos = New Collection\n Set styleActions = New Collection\n styleActions.Add New DeleteStyleAction, \"Delete\"\n styleActions.Add New DuplicateStyleAction, \"Duplicate\"\n styleActions.Add New ReplaceStyleAction, \"Replace\"\n '...\nEnd Sub\n</code></pre>\n\n<p>Notice how every single one of these <code>New</code> statements increases the number of classes that are <em>coupled</em> with this <code>StyleProcessor</code> (<code>cStyles</code>) class? That's because the <code>StyleProcessor</code> is responsible for knowing what actions are available and what string value refers to what action - if we removed that responsibility, we would also remove that coupling. We can remove responsibilities from a class by <em>injecting</em> components instead of <code>New</code>ing them up. See <a href=\"https://rubberduckvba.wordpress.com/2019/09/19/dependency-injection-in-vba/\" rel=\"nofollow noreferrer\">Dependency Injection in VBA</a> if that's something you want to explore.</p>\n\n<hr>\n\n<p>Other observations, in no particular order:</p>\n\n<ul>\n<li><code>cStyle.Init</code> needs explicit declared types for the parameters, and <code>ByVal</code> modifiers.</li>\n<li>Lots of parameters are implicitly passed <code>ByRef</code>, some are implicitly passed <code>ByVal</code>. Consistency! You want everything passed <code>ByVal</code> unless the compiler says otherwise, or unless you're using <code>ByRef</code> to return values to the caller.</li>\n<li><code>Public Property Set Style(ByRef Style As Style)</code> is a lie. <code>Property Set</code> and <code>Property Let</code> procedures always receive their value argument <code>ByVal</code>: the modifier is not only not needed, it's outright lying. And since the default/implicit modifier is <code>ByRef</code> anyway, I'm worried this one was added \"because it's an object and so it must be passed by reference\" (not true), which denotes a misunderstanding of how <code>ByRef</code>/<code>ByVal</code> work.</li>\n<li>Vertical whitespace in <code>Duplicate</code> is distracting.</li>\n<li><code>cStyles.Item</code> wants a <code>@DefaultMember</code> annotation (/<code>VB_UserMemId = 0</code> attribute).</li>\n<li>The <code>LoadStyles</code> and <code>ProcessStyles</code> macros don't need a local variable; just go <code>With New cStyles</code> and perform the member calls against the <code>With</code> block variable.</li>\n<li>Both <code>LoadStyles</code> and <code>ProcessStyles</code> are implicitly <code>Public</code>.</li>\n<li>Not sure <code>Clear</code> has any business being exposed; feels like YAGNI (You Ain't Gonna Need It).</li>\n</ul>\n\n<p>Rubberduck inspections should be warning you about the implicit modifiers and unused members.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:26:32.800",
"Id": "451560",
"Score": "0",
"body": "Absolutely amazing. Whole day spent trying to put in practice your reviews. Thank you Mathieu! Just one question: if I want to review the results that incorporate your comments and suggestions should I post another question or edit this one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:30:32.393",
"Id": "451561",
"Score": "0",
"body": "@RicardoDiaz you can absolutely [post a follow-up question](https://codereview.stackexchange.com/help/someone-answers); please avoid editing code in answered questions, such (answer-invalidating) edits are monitored and will be rolled back =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T16:50:18.893",
"Id": "231478",
"ParentId": "231453",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "231478",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:13:58.187",
"Id": "231453",
"Score": "5",
"Tags": [
"object-oriented",
"vba",
"excel",
"interface",
"polymorphism"
],
"Title": "Manage Excel Styles with VBA OOP Approach"
}
|
231453
|
<p>I am currently learning Java programing by building real life business application for repair shops. I am posting this code so I can get critical review, and change my application architecture if necessary. I would like your opinion on my approach to MVC pattern.</p>
<p>This is a GUI swing class for one of the dialogs.</p>
<pre><code>public class ClientRegistrationWindow
{ public JDialog window;
public JPanel contentPane = new JPanel();
public JLabel lablelIDValue = new JLabel();
public JLabel labelFirstName = new JLabel();
public JTextField textFieldFirstName = new JTextField();
public JLabel labelLastName = new JLabel();
public JTextField textFieldLastName = new JTextField();
public JLabel labelPrimePhoneNum = new JLabel();
public JTextField textFieldPrimePhoneNum = new JTextField();
public JTextField textFieldAlternativePhoneNum = new JTextField();
public JTextField textFieldEmail = new JTextField();
public JTextField textFieldAddress = new JTextField();
public JLabel labelMarketing = new JLabel();
public JComboBox<Property> comboBoxMarketing = new JComboBox<Property>();
public JButton buttonAdd = new JButton();
public JButton buttonCancel = new JButton();
/**
* Creates JDialog "Customer Registration Form".
*/
public ClientRegistrationWindow(Window owner)
{
createWindow(owner);
createIDView();
createFirstNameView();
createLastNameView();
createPrimePhoneNumView();
createAlternativePhoneNumView();
createEmailView();
createAddressView();
createMarketingView();
createButtonsView();
}
private void createWindow(Window owner)
{
window = new JDialog(owner);
window.setTitle(ClientGUITextUtils.TITLE);
window.setResizable(false);
window.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
window.setBounds(100, 100, 460, 440);
window.setContentPane(contentPane);
window.setVisible(true);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
}
private void createIDView()
{
JLabel labelID = new JLabel();
labelID.setText(ClientGUITextUtils.CLIENT_ID_LABEL);
labelID.setBounds(35, 25, 110, 25);
contentPane.add(labelID);
lablelIDValue.setText("X-XXXXX");
lablelIDValue.setHorizontalAlignment(SwingConstants.CENTER);
lablelIDValue.setFont(new Font("Tahoma", Font.BOLD, 15));
lablelIDValue.setBounds(150, 25, 160, 25);
contentPane.add(lablelIDValue);
}
private void createFirstNameView()
{
labelFirstName.setText(ClientGUITextUtils.FIRST_NAME_LABEL);
labelFirstName.setBounds(35, 90, 185, 15);
contentPane.add(labelFirstName);
textFieldFirstName.setColumns(10);
textFieldFirstName.setBounds(35, 105, 185, 25);
contentPane.add(textFieldFirstName);
}
private void createLastNameView()
{
labelLastName.setText(ClientGUITextUtils.LAST_NAME_LABEL);
labelLastName.setBounds(235, 90, 185, 15);
contentPane.add(labelLastName);
textFieldLastName.setColumns(10);
textFieldLastName.setBounds(235, 105, 185, 25);
contentPane.add(textFieldLastName);
}
private void createPrimePhoneNumView()
{
labelPrimePhoneNum.setText(ClientGUITextUtils.PRIME_PHONE_NUMBER_LABEL);
labelPrimePhoneNum.setBounds(35, 140, 185, 15);
contentPane.add(labelPrimePhoneNum);
textFieldPrimePhoneNum.setColumns(10);
textFieldPrimePhoneNum.setBounds(35, 155, 185, 25);
contentPane.add(textFieldPrimePhoneNum);
}
private void createAlternativePhoneNumView()
{
JLabel labelAlternativePhoneNum =new JLabel(ClientGUITextUtils.SECOND_NUMBER_LABEL);
labelAlternativePhoneNum.setBounds(235, 140, 185, 15);
contentPane.add(labelAlternativePhoneNum);
textFieldAlternativePhoneNum.setColumns(10);
textFieldAlternativePhoneNum.setBounds(235, 155, 185, 25);
contentPane.add(textFieldAlternativePhoneNum);
}
private void createEmailView()
{
JLabel labelEmail = new JLabel(ClientGUITextUtils.EMAIL_LABEL);
labelEmail.setBounds(35, 190, 385, 15);
contentPane.add(labelEmail);
textFieldEmail.setColumns(10);
textFieldEmail.setBounds(35, 205, 385, 25);
contentPane.add(textFieldEmail);
}
private void createAddressView()
{
JLabel labelAddress = new JLabel(ClientGUITextUtils.ADDRESS_LABEL);
labelAddress.setBounds(35, 240, 385, 15);
contentPane.add(labelAddress);
textFieldAddress.setColumns(10);
textFieldAddress.setBounds(35, 255, 385, 25);
contentPane.add(textFieldAddress);
}
private void createMarketingView()
{
labelMarketing.setText(ClientGUITextUtils.MARKETING_LABEL);
labelMarketing.setBounds(235, 290, 185, 15);
contentPane.add(labelMarketing);
comboBoxMarketing.setSize(185, 25);
comboBoxMarketing.setLocation(235, 305);
contentPane.add(comboBoxMarketing);
}
private void createButtonsView()
{
buttonAdd.setText(ClientGUITextUtils.ADD_CLIENT_BUTTON);
buttonAdd.setFont(new Font("Dialog", Font.PLAIN, 15));
buttonAdd.setBounds(35, 365, 110, 25);
contentPane.add(buttonAdd);
buttonCancel.setText(ClientGUITextUtils.CANCEL_BUTTON);
buttonCancel.setFont(new Font("Dialog", Font.PLAIN, 15));
buttonCancel.setBounds(310, 365, 110, 25);
contentPane.add(buttonCancel);
}
}
</code></pre>
<p>This is the controller class for that window.</p>
<pre><code>public class ClientRegistrationController implements InputDialogController
{
private int clientID;
private ClientRegistrationWindow clientRegistration;
public ClientRegistrationController(Window owner)
{
clientID = IDGeneratorUtils.getNewClientID();
clientRegistration = new ClientRegistrationWindow(owner);
clientRegistration.lablelIDValue.setText(String.valueOf(clientID));
clientRegistration.buttonAdd.addActionListener(new AddDataElement(this));
clientRegistration.buttonCancel.addActionListener(new CloseWindow(this));
}
private Client scanWindowInput()
{
Client newClient = new Client();
newClient.setID(clientID);
newClient.setFirstName(clientRegistration.textFieldFirstName.getText());
newClient.setLastName(clientRegistration.textFieldLastName.getText());
newClient.setPrimePhoneNumber(clientRegistration.textFieldPrimePhoneNum.getText());
newClient.setAlternativePhoneNumber(clientRegistration.textFieldAlternativePhoneNum.getText());
newClient.setEmail(clientRegistration.textFieldEmail.getText());
newClient.setAddress(clientRegistration.textFieldAddress.getText());
newClient.setMarketing((Property) clientRegistration.comboBoxMarketing.getSelectedItem());
return newClient;
}
@Override
public void trySavingDataElement()
{
if(ClientValidatorUtils.isValid(clientRegistration))
{
DataStructure.clientsDataTable.save(scanWindowInput());
IDGeneratorUtils.incrementClientCounter();
closeWindow();
}
else
{
new ShowClientInputErrors(clientRegistration);
}
}
@Override
public void closeWindow()
{
clientRegistration.window.dispose();
}
}
</code></pre>
<p>This is Client registration input validation class.</p>
<pre><code>public class ClientValidatorUtils
{
public static boolean isValid(ClientRegistrationWindow clientRegistration)
{
return isFirstNameEntered(clientRegistration)
&& isLastNameEntered(clientRegistration)
&& isPhoneNumberEntered(clientRegistration)
&& isPhoneNumberUnique(clientRegistration)
&& isMarketingNotSelected(clientRegistration);
}
public static boolean isFirstNameEntered(ClientRegistrationWindow clientRegistration)
{
return !("".equals(clientRegistration.textFieldFirstName.getText()));
}
public static boolean isLastNameEntered(ClientRegistrationWindow clientRegistration)
{
return !("".equals(clientRegistration.textFieldLastName.getText()));
}
public static boolean isPhoneNumberEntered(ClientRegistrationWindow clientRegistration)
{
return !("".equals(clientRegistration.textFieldPrimePhoneNum.getText()));
}
public static boolean isPhoneNumberUnique(ClientRegistrationWindow clientRegistration)
{
return !(DataStructure.clientsDataTable
.uniqueStringCollision(clientRegistration.textFieldPrimePhoneNum.getText()));
}
public static boolean isMarketingNotSelected(ClientRegistrationWindow clientRegistration)
{
return clientRegistration.comboBoxMarketing.getSelectedItem() != null;
}
}
</code></pre>
<p>This is the input error handler.</p>
<pre><code>public class ShowClientInputErrors
{
private ClientRegistrationWindow clientRegistration;
public ShowClientInputErrors(ClientRegistrationWindow clientRegistration)
{
this.clientRegistration = clientRegistration;
showPhomeNumberNotUniqueError();
showPhomeNumberNotEnterdError();
showFirstNameNotEnteredError();
showLastNameNotEnteredError();
showMarketingNotSelectedError();
}
private void showPhomeNumberNotUniqueError()
{
if(ClientValidatorUtils.isPhoneNumberUnique(clientRegistration))
{
displayDefaultPhoneNumber();
}
else
{
displayPhoneNumberDuplicateError();
}
}
private void showPhomeNumberNotEnterdError()
{
if(ClientValidatorUtils.isPhoneNumberEntered(clientRegistration))
{
displayDefaultPhoneNumber();
}
else
{
displayPhoneNumberNotEnteredError();
}
}
private void displayDefaultPhoneNumber()
{
clientRegistration.labelPrimePhoneNum
.setText(ClientGUITextUtils.PRIME_PHONE_NUMBER_LABEL);
clientRegistration.textFieldPrimePhoneNum.setBackground(Color.WHITE);
}
private void displayPhoneNumberNotEnteredError()
{
clientRegistration.labelPrimePhoneNum
.setText(ClientGUITextUtils.PHONE_NUMBER_NOT_ENTERED_ERROR_MESSAGE);
clientRegistration.textFieldPrimePhoneNum.setBackground(Color.YELLOW);
}
private void displayPhoneNumberDuplicateError()
{
clientRegistration.labelPrimePhoneNum
.setText(ClientGUITextUtils.PHONE_NUMBER_NOT_UNIQUE_ERROR_MESSAGE);
clientRegistration.textFieldPrimePhoneNum.setBackground(Color.YELLOW);
}
private void showFirstNameNotEnteredError()
{
if(ClientValidatorUtils.isFirstNameEntered(clientRegistration))
{
clientRegistration.labelFirstName
.setText(ClientGUITextUtils.FIRST_NAME_LABEL);
clientRegistration.textFieldFirstName.setBackground(Color.WHITE);
}
else
{
clientRegistration.labelFirstName
.setText(ClientGUITextUtils.FIRST_NAME_NOT_ENTERED_ERROR_MESSAGE);
clientRegistration.textFieldFirstName.setBackground(Color.YELLOW);
}
}
private void showLastNameNotEnteredError()
{
if(ClientValidatorUtils.isLastNameEntered(clientRegistration))
{
clientRegistration.labelLastName
.setText(ClientGUITextUtils.LAST_NAME_LABEL);
clientRegistration.textFieldLastName.setBackground(Color.WHITE);
}
else
{
clientRegistration.labelLastName
.setText(ClientGUITextUtils.LAST_NAME_NOT_ENTERED_ERROR_MESSAGE);
clientRegistration.textFieldLastName.setBackground(Color.YELLOW);
}
}
private void showMarketingNotSelectedError()
{
if(ClientValidatorUtils.isMarketingNotSelected(clientRegistration))
{
clientRegistration.labelMarketing
.setText(ClientGUITextUtils.MARKETING_LABEL);
clientRegistration.comboBoxMarketing.setBackground(Color.WHITE);
}
else
{
clientRegistration.labelMarketing
.setText(ClientGUITextUtils.MARKETING_NOT_SELECTED_ERROR_MESSAGE);
clientRegistration.comboBoxMarketing.setBackground(Color.YELLOW);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think I found even better MVC architecture for my application. I have used inheritance for my input dialog controller classes , and composition of Jpanels in my Swing dialog classes, to avoid code duplication, and to get more clear code. Or I hope so..</p>\n\n<p>This is my abstract input dialog controller class that is a super class for all input dialog controllers. It is responsible for setting the ID label value, setting Add and Cancel buttons ActionListeners, and has the main function of input controllers, saving data.</p>\n\n<pre><code>public abstract class InputDialogController implements WindowController\n{\n protected DataType dataType;\n protected int id;\n protected InputDialog gui;\n\n protected InputDialogController(WindowController owner, DataType dataType)\n {\n this.dataType = dataType;\n gui = InputDialogFactory.getWindow(owner.getWindow(), dataType);\n id = IDGenerator.getNewID(dataType);\n gui.getIdPanel().setIdValue(IDGenerator.formatRegularID(id));\n gui.getInputButtonPanel().setBtnAddActionListener(ActionListenerFactory.saveData(this));\n gui.getInputButtonPanel().setBtnCancelActionListener(ActionListenerFactory.closeWindow(this));\n }\n\n @Override\n public Window getWindow()\n {\n return (Window) gui;\n }\n\n public void trySavingDataElement()\n {\n if(isInputValid())\n {\n DataManager.save(createDataElement());\n getWindow().dispose();\n }\n else\n {\n showInputErrors();\n }\n }\n\n protected abstract boolean isInputValid();\n\n protected abstract DataElement createDataElement();\n\n protected abstract void showInputErrors();\n}\n</code></pre>\n\n<p>This is one of mine concrete input dialog controllers, the ClientRegistrationController class.</p>\n\n<pre><code>public class ClientRegistrationController extends InputDialogController\n{\n private ClientRegistrationDialog clientGUI;\n\n public ClientRegistrationController(WindowController owner, DataType dataType)\n {\n super(owner, dataType);\n clientGUI = (ClientRegistrationDialog) super.gui;\n clientGUI.getMarketingPanel().setMarketingCmbModel(CmbModelFactory.getModel(dataType));\n clientGUI.getMarketingPanel()\n .setBtnMarketingActionListener(ActionListenerFactory\n .openNewWindow(this, DataType.MARKETING_TYPE));\n\n }\n\n public void updateComboBoxes(String item)\n {\n clientGUI.getMarketingPanel().setMarketing(item);\n }\n\n @Override\n protected boolean isInputValid()\n {\n return isNameValid()\n && isPhoneNumberValid()\n && isMarketingSelected();\n }\n\n private boolean isNameValid( )\n {\n return !(\"\".equals(clientGUI.getPersonalInfoPanel().getName()));\n }\n\n private boolean isPhoneNumberValid()\n {\n String phoneNumber = clientGUI.getPersonalInfoPanel().getPrimePhoneNumber();\n\n return !(DataManager.clientsDataTable.uniqueStringCollision(phoneNumber)\n || (\"\".equals(phoneNumber)));\n }\n\n private boolean isMarketingSelected()\n {\n return clientGUI.getMarketingPanel().getMarketing() != \"\";\n }\n\n @Override\n protected Client createDataElement()\n {\n Client newClient= new Client();\n\n newClient.setId(id);\n newClient.setName(clientGUI.getPersonalInfoPanel().getName());\n newClient.setPrimePhoneNumber(clientGUI.getPersonalInfoPanel().getPrimePhoneNumber());\n newClient.setAlternativePhoneNumber(clientGUI.getPersonalInfoPanel().getAltPoneNumber());\n newClient.setEmail(clientGUI.getPersonalInfoPanel().getEmail());\n newClient.setAddress(clientGUI.getPersonalInfoPanel().getAddress());\n newClient.setMarketing(DataElementGetter.getMarketing(clientGUI.getMarketingPanel().getMarketing()));\n\n return newClient;\n }\n\n @Override\n protected void showInputErrors()\n {\n checkName();\n checkPhoneNumber();\n checkMarketing();\n }\n\n private void checkName()\n {\n if(isNameValid())\n {\n clientGUI.getPersonalInfoPanel().showNameDefault();\n }\n else\n {\n clientGUI.getPersonalInfoPanel().showNameError();\n }\n }\n\n\n private void checkPhoneNumber()\n {\n\n if(isPhoneNumberValid())\n {\n clientGUI.getPersonalInfoPanel().showPhoneDefault();\n }\n else\n {\n clientGUI.getPersonalInfoPanel().showPhoneError();\n }\n }\n\n private void checkMarketing()\n {\n if(isMarketingSelected())\n {\n clientGUI.getMarketingPanel().showMarketingDefault();\n }\n else\n {\n clientGUI.getMarketingPanel().showMarketingError();\n }\n }\n}\n</code></pre>\n\n<p>This is the swing class for client registration:</p>\n\n<pre><code>public class ClientRegistrationDialog extends JDialog implements InputDialog\n{\n private static final long serialVersionUID = -394107433140693140L;\n private IdPanel idPanel = new IdPanel();\n private PersonalInfoPanel personalInfoPanel = new PersonalInfoPanel();\n private MarketingPanel marketingPanel = new MarketingPanel();\n private InputButtonPanel buttonPanel = new InputButtonPanel();\n\n public ClientRegistrationDialog(Window owner)\n {\n super(owner);\n getContentPane().setLayout(new MigLayout(\"\", \"[434px]\", \"[25px:n][][][]\"));\n getContentPane().add(idPanel, \"cell 0 0,grow\");\n getContentPane().add(personalInfoPanel, \"cell 0 1,grow\");\n getContentPane().add(marketingPanel, \"cell 0 2,grow\");\n getContentPane().add(buttonPanel, \"cell 0 3,grow\");\n }\n\n @Override\n public IdPanel getIdPanel()\n {\n return idPanel;\n }\n\n public PersonalInfoPanel getPersonalInfoPanel()\n {\n return personalInfoPanel;\n }\n\n public MarketingPanel getMarketingPanel()\n {\n return marketingPanel;\n }\n\n @Override\n public InputButtonPanel getInputButtonPanel()\n {\n return buttonPanel;\n }\n}\n</code></pre>\n\n<p>And this is one of it's panels, the PersonalInfoPanel.</p>\n\n<pre><code>public class PersonalInfoPanel extends JPanel\n{\n private static final long serialVersionUID = -1636004925810635460L;\n private JTextField txtName;\n private JTextField txtPrimePhone;\n private JTextField txtAltPhone;\n private JTextField txtEmail;\n private JTextField txtAddress;\n\n public PersonalInfoPanel()\n {\n setLayout(new MigLayout(\"\", \"[][5.00][grow]\", \"[20px:n,fill][20px:n,fill][20px:n,fill][][20px:n]\"));\n\n JLabel lblName = LabelFactory.createJLabel(\"First and Last Name\", new Font(\"Tahoma\", Font.PLAIN, 13));\n add(lblName, \"cell 0 0,growy\");\n\n txtName = TextFieldFactory.createJTextField(10);\n add(txtName, \"cell 2 0,grow\");\n\n JLabel lblPrimePhone = LabelFactory.createJLabel(\"Primary Phone Number\", new Font(\"Tahoma\", Font.PLAIN, 13));\n add(lblPrimePhone, \"cell 0 1,growy\");\n\n txtPrimePhone = TextFieldFactory.createJTextField(10);\n add(txtPrimePhone, \"cell 2 1,grow\");\n\n JLabel lblAltPhone = LabelFactory.createJLabel(\"Alternative Phone Number\", new Font(\"Tahoma\", Font.PLAIN, 13));\n add(lblAltPhone, \"cell 0 2,growy\");\n\n txtAltPhone = TextFieldFactory.createJTextField(10);\n add(txtAltPhone, \"cell 2 2,grow\");\n\n JLabel lblEmail = LabelFactory.createJLabel(\"Email Address\", new Font(\"Tahoma\", Font.PLAIN, 13));\n add(lblEmail, \"cell 0 3,growy\");\n\n txtEmail = TextFieldFactory.createJTextField(10);\n add(txtEmail, \"cell 2 3,growx\");\n\n JLabel lblHomeAddress = LabelFactory.createJLabel(\"Home Address\", new Font(\"Tahoma\", Font.PLAIN, 13));\n add(lblHomeAddress, \"cell 0 4,growy\");\n\n txtAddress = TextFieldFactory.createJTextField(10);\n add(txtAddress, \"cell 2 4,grow\");\n }\n\n public String getPersonName()\n {\n return txtName.getText();\n }\n\n public String getPrimePhoneNumber()\n {\n return txtPrimePhone.getText();\n }\n\n public String getAltPoneNumber()\n {\n return txtAltPhone.getText();\n }\n\n public String getEmail()\n {\n return txtAltPhone.getText();\n }\n\n public String getAddress()\n {\n return txtAddress.getText();\n }\n\n public void showNameDefault()\n {\n txtName.setBackground(Color.WHITE);\n }\n\n public void showNameError()\n {\n txtName.setBackground(Color.YELLOW);\n }\n\n public void showPhoneDefault()\n {\n txtName.setBackground(Color.WHITE);\n }\n\n public void showPhoneError()\n {\n txtName.setBackground(Color.YELLOW);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T05:06:39.933",
"Id": "455980",
"Score": "1",
"body": "Self-answers are perfectly fine, but this one reads like it's kind of just following-up on the OP.. If you would like feedback on this new updated code, it would be better to present it in a new question... but since there hasn't been any answers yet, you could simply [edit the OP](https://codereview.stackexchange.com/posts/231454/edit) with your latest bestest version! Do that and your post will be bumped onto the home page. Add additional context/explanations, screenshots, tell us about what the app does and where that code fits in, ..and I'll put up a nice bounty to draw more attention ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:43:29.140",
"Id": "233283",
"ParentId": "231454",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233283",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:20:11.403",
"Id": "231454",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"mvc",
"swing"
],
"Title": "MVC pattern in my Repair Shop application"
}
|
231454
|
<blockquote>
<p>Problem Link- <a href="https://www.hackerearth.com/challenges/competitive/october-circuits-19/algorithm/ap-1-f43562f4/" rel="nofollow noreferrer">https://www.hackerearth.com/challenges/competitive/october-circuits-19/algorithm/ap-1-f43562f4/</a></p>
<p>Problem Statement : </p>
<p>You are given an integer array of size A. You are also given queries Q. In each query, you are given three integers L, R, and D respectively.</p>
<p>You are required to determine the length of the largest contiguous segment in the indices range [L, R] of A that forms an arithmetic progression with a common difference of D</p>
<p>Note: The segment whose length is 1 always forms an arithmetic progression of a common difference D</p>
<p>Input format</p>
<pre><code> First line: Two space-separated integers N and Q respectively
Second line: N space-separated integers denoting elements of A
Next Q lines: Three space-separated integers L, R, and D (1<= L <= R <= N) respectively
</code></pre>
<p>Output format</p>
<p>Print Q lines representing the answer such as the ith line denotes the answer for the ith query.</p>
<p>Constraints</p>
<pre><code>1 <= N <= 200000
1 <= Ai <= 200000
-200000 <= D <= 200000
</code></pre>
<p>Sample Input </p>
<pre><code>5 2
1 2 3 5 5
1 5 1
4 4 3
Sample Output
3
1
</code></pre>
<p>Explanation</p>
<p>For the first query, [1,2,3] forms an AP with difference 1.</p>
<p>For the second query, [5] forms an AP.</p>
</blockquote>
<hr>
<p>I was attempting to solve this problem on hacker earth, however for large size N and Q the following code exceeds the time limit. Is there any way I can make this code run faster, other than changing the algorithm?</p>
<pre><code>N, Q = [int(x) for x in input().split()]
A = list(map(int, input().split()))
for testcase in range(Q):
L, R, D = [int(x) for x in input().split()]
if L == R:
print("1")
continue
count_length = 0
count_temp = 0
for index in range(L, R):
if A[index] == A[index-1] + D:
count_temp += 1
if index == R-1:
count_temp += 1
count_length = max(count_length, count_temp)
else:
count_temp += 1 # to include the first element of AP
count_length = max(count_length, count_temp)
count_temp = 0
print(count_length)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T20:57:07.400",
"Id": "451547",
"Score": "1",
"body": "*for large size N and Q the following code exceeds the time limit* - let's say `N` and `Q` equal to `200000` (fitting your constraints). What \"time limit\" is exceeded AND with that, why do you suspend the flow with `input()` on each iteration?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T23:56:01.510",
"Id": "451563",
"Score": "4",
"body": "@RomanPerekhrest [tag:time-limit-exceeded] is a rather common thing with programming challenges. I'd challenge OP's \"other than changing the algorithm\" though, because these challenges are often designed such that a naive algorithm fails the time constraint."
}
] |
[
{
"body": "<h2>Code Review</h2>\n\n<h3>PEP 8</h3>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> recommends <code>snake_case</code> for variable names, so <code>N</code>, <code>Q</code>, <code>A</code>, <code>L</code>, <code>R</code>, and <code>D</code> all violate the guidelines.</p>\n\n<p>A space should be used around operators: <code>index - 1</code> and <code>R - 1</code></p>\n\n<h3>Unused variables</h3>\n\n<p><code>N</code> and <code>testcase</code> are never used, so should be replaced with the throwaway <code>_</code> variable.</p>\n\n<h3>Variable naming</h3>\n\n<p><code>N</code>, <code>Q</code>, <code>A</code>, <code>L</code>, <code>R</code>, and <code>D</code> are all \"almost meaningless\". Yes, they are directly from the problem description, but you could do better naming them <code>array_size</code>, <code>num_queries</code>, <code>array</code>, <code>left</code>, <code>right</code> and <code>difference</code>.</p>\n\n<p>Is <code>count_length</code> a count of lengths? Doesn't seem to be; it is more like a <code>max_length</code>.</p>\n\n<p>Is <code>count_temp</code> a count of temporaries? Or is it more like a <code>segment_length</code>?</p>\n\n<pre><code>_, num_queries = [int(x) for x in input().split()]\n\narray = list(map(int, input().split()))\n\nfor _ in range(num_queries):\n left, right, difference = [int(x) for x in input().split()]\n\n if left == right:\n print(\"1\")\n continue\n\n max_length = 0\n segment_length = 0\n\n for index in range(left, right):\n if array[index] == array[index - 1] + difference:\n segment_length += 1\n if index == right - 1:\n segment_length += 1\n max_length = max(max_length, segment_length)\n\n else:\n segment_length += 1 # to include the first element of AP\n max_length = max(max_length, segment_length)\n segment_length = 0\n\n print(max_length)\n</code></pre>\n\n<h2>Optimization</h2>\n\n<h3>Without changing the Algorithm???</h3>\n\n<p>Ok, you're looking for just key-hole level optimizations. Let's see what we can do.</p>\n\n<pre><code> for index in range(left, right):\n if array[index] == array[index - 1] + difference:\n ...\n else:\n ...\n</code></pre>\n\n<p>The above is inefficient code. Indexing into a list takes time, and you are doing it twice. Moreover, subtraction by 1 takes time, and it was to get the value which was looked up on the previous iteration!</p>\n\n<p>Compare the above code with:</p>\n\n<pre><code> prev = array[left - 1]\n for curr in array[left:right]:\n if curr == prev + difference:\n ...\n else:\n ...\n prev = curr\n</code></pre>\n\n<p>The indexing has been replaced with iteration over an array slice, and the current value from one iteration is carried forward to as the previous value in the next iteration. That should be a win, performance wise.</p>\n\n<pre><code> segment_length = 0\n\n for ...:\n if ...:\n ...\n if ...:\n segment_length += 1\n max_length = max(max_length, segment_length)\n\n else:\n segment_length += 1 # to include the first element of AP\n max_length = ...\n segment_length = 0\n</code></pre>\n\n<p>Why are you starting the count from <code>0</code>? That means you need this <code>segment_length += 1</code> to account for that first element all the time. If you initialized <code>segment_length = 1</code>, you can skip that adjustment statement every time you reach the end of an arithmetic progression, saving another wee bit of time:</p>\n\n<pre><code> segment_length = 1\n\n for ...:\n if ...:\n ...\n if ...:\n max_length = max(max_length, segment_length)\n\n else:\n max_length = ...\n segment_length = 1\n</code></pre>\n\n<p>Finally, the code I hate the most:</p>\n\n<pre><code> for index in range(left, right):\n if ...:\n ...\n if index == right - 1:\n ...\n\n else:\n ...\n ...\n</code></pre>\n\n<p>When does the <code>for</code> loop end? After <code>index</code> loops the final time with <code>index = right - 1</code>, of course. So the only time this <code>if</code> condition will be true is during the last iteration of the loop. During all of the remaining loop iterations, you are wasting time, subtraction 1 from <code>right</code> and comparing the result to <code>index</code>, when it can't possibly ever be true. Simply move the code to follow the loop.</p>\n\n<pre><code>_, num_queries = [int(x) for x in input().split()]\n\narray = list(map(int, input().split()))\n\nfor _ in range(num_queries):\n left, right, difference = [int(x) for x in input().split()]\n\n if left == right:\n print(\"1\")\n continue\n\n max_length = 0\n segment_length = 1\n\n prev = array[left - 1]\n for curr in array[left:right]:\n if curr == prev + difference:\n segment_length += 1\n\n else:\n max_length = max(max_length, segment_length)\n segment_length = 1\n\n prev = curr\n\n max_length = max(max_length, segment_length)\n\n print(max_length)\n</code></pre>\n\n<h3>With changing the Algorithm</h3>\n\n<p>You explicitly requested optimization without changing the algorithm, so I'll leave you to discover where there is an algorithmic improvement to be made.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T09:08:02.950",
"Id": "451601",
"Score": "0",
"body": "Not sure if `for curr in array[left:right]` is actually faster here than iterating over the indices, since it creates a copy of the slice each time. If `right - left` is large, this might actually make it slower. Would need some timings to be sure though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T13:39:49.630",
"Id": "451644",
"Score": "1",
"body": "@Graipher It is subtle, but the OP is (an)using Python’s exclusive range end-point to “do the right thing”. The problem description’s 1-based addressing and Python’s `range(L, R)` excluding `R` result in `index - 1` going from `L-1` to `R-2` and `index` going from `L` to `R-1`, which is the proper Pythonic 0-based indices for comparing successive pairs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T15:14:30.333",
"Id": "451663",
"Score": "1",
"body": "@Graipher First test case returned `2` because I forgot the `prev = curr` line when transcribing code review changes into the final code-edit. My bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T02:53:11.093",
"Id": "231502",
"ParentId": "231456",
"Score": "6"
}
},
{
"body": "<p>Just for fun I tried implementing this using just generators and the <code>itertools</code>. Using this has the advantage that you don't have to pay the price for indexing multiple times (like in your code), but also not the price for copying the slices (like in <a href=\"https://codereview.stackexchange.com/users/100620/ajneufeld\">@AJNeufeld</a>'s <a href=\"https://codereview.stackexchange.com/a/231502/98493\">solution</a>). It also means that instead of using an array, this function can deal with <code>A</code> being a generator (but of course in that case you could not make multiple queries on the same array).</p>\n\n<ul>\n<li><p>To get the range from the array, we can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a>, which works similarly to normal slicing (but without indexing from the end, because generators can be infinite).</p></li>\n<li><p>Finding the difference between elements is straight-forward when iterating over pairs of elements, which you can get with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.tee\" rel=\"nofollow noreferrer\"><code>itertools.tee</code></a> and advancing one of the resulting iterators.</p></li>\n<li><p>Finally, we need to run-length-encode the result and find the largest one where the chain of differences is the given difference. For this we can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>.</p></li>\n</ul>\n\n\n\n<pre><code>def graipher(array, left, right, difference):\n if left == right:\n return 1\n it = islice(iter(array), left - 1, right + 1)\n it1, it2 = tee(it)\n next(it1)\n differences = (a - b for a, b in zip(it1, it2))\n rle = (len(list(g)) for d, g in groupby(differences) if d == difference)\n try:\n return max(rle) + 1\n except ValueError:\n # empty sequence, none of the differences is correct\n return 1\n</code></pre>\n\n<p>Note that I put this code into a function that returns the result, instead of printing it. This makes it reusable, and testable. When doing the same to the other solutions, we can even compare the performance using some random test data:</p>\n\n<p><a href=\"https://i.stack.imgur.com/B0LSM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B0LSM.png\" alt=\"enter image description here\"></a></p>\n\n<p>For small slices (<code>R - L</code> small) this generator approach is the slowest of the three approaches, whereas for larger slices it is the second fastest. AJNeufeld's approach is consistently the fastest, tested up to <span class=\"math-container\">\\$10^6\\$</span> in slice length, which is a magnitude larger than the constraints given in the problem description.</p>\n\n<p>Nevertheless, all three solutions use inherently the same algorithm, iterating through all elements in the slice, and therefore have the same asymptotic behavior.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T14:54:13.167",
"Id": "231609",
"ParentId": "231456",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231502",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T11:49:33.843",
"Id": "231456",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"time-limit-exceeded"
],
"Title": "Determine the length of the largest contiguous segment"
}
|
231456
|
<p>I had this S3Helper class before such that, every time I called a function to any of its methods (which I haven't shown here, but which do things like upload files to s3 or get temporary s3 links), it called the <code>getClient()</code> method and it would make a new client every time.</p>
<p>Now I don't know about the performance hit on that, if calling <code>new S3Client([])</code> makes http requests every time it's called, but I supposed it did so decided I'd rather just make the client once and then use the same client for future calls.</p>
<p>So I cached the result in a static variable, and now my <code>getClient</code> function checks if the cache exists first, and if it does it returns it, otherwise it makes a new client and sets the cache.</p>
<p>Is this a recommended PHP way of doing things? Can it be improved?</p>
<pre><code><?php // Code within app\Helpers\Helper.php
namespace App\Helpers;
use Aws\S3\S3Client;
class S3Helper {
protected static $client = null;
private static function getAuth() {
return [
'endpoint' => env('S3_ENDPOINT'),
'key' => env('S3_KEY'),
'secret' => env('S3_SECRET'),
'bucket' => env('S3_BUCKET')
];
}
private static function getClient() {
if (self::$client) return self::$client;
$auth = self::getAuth();
self::$client = new S3Client([
'region' => 'eu-west-2',
'version' => '2006-03-01',
'endpoint' => $auth['endpoint'],
'credentials' => [
'key' => $auth['key'],
'secret' => $auth['secret']
],
'use_path_style_endpoint' => true
]);
return self::$client;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Before going through advises just wanted to remind you can alternatively use <code>Aws\\Sdk</code> class as a client factory.<br>\nSample usage:</p>\n\n<pre><code>// The same options that can be provided to a specific client constructor can also be supplied to the Aws\\Sdk class.\n// Use the us-west-2 region and latest version of each client.\n$sharedConfig = [\n 'region' => 'us-west-2',\n 'version' => 'latest'\n];\n\n// Create an SDK class used to share configuration across clients.\n$sdk = new Aws\\Sdk($sharedConfig);\n\n// Create an Amazon S3 client using the shared configuration data.\n$client = $sdk->createS3();\n</code></pre>\n\n<p>Observe <a href=\"https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/getting-started_basic-usage.html\" rel=\"nofollow noreferrer\"><code>AWS SDK for PHP</code></a> guide, just in case you hadn't yet.<br>They give a notation there:</p>\n\n<blockquote>\n <p><strong>Note</strong></p>\n \n <p>We highly recommended that you use the Sdk class to create clients if\n you're using multiple client instances in your application. The Sdk\n class automatically uses the same HTTP client for each SDK client,\n allowing SDK clients for different services to perform nonblocking\n HTTP requests. If the SDK clients don't use the same HTTP client, then\n HTTP requests sent by the SDK client might block promise orchestration\n between services.</p>\n</blockquote>\n\n<hr>\n\n<p>But, proceeding with your approach, you have a variation of <code>Singleton</code> pattern (restricts the instantiation of a class to a single object, which can be useful when only one object is required across the system).<br>In your case <code>S3Helper</code> acting as a <em>factory</em> producing/returning the same <code>S3Client</code> instance.</p>\n\n<p>To prevent instantiation/cloning of <code>S3Helper</code> from the outer code you can <em>close</em> <code>__construct</code>, <code>__clone</code> (and even <code>__wakeup</code>) methods:</p>\n\n<pre><code>class S3Helper {\n ...\n private function __construct() { }\n private function __clone() { }\n</code></pre>\n\n<p>To eliminate multiple <code>return</code> statements in your static <code>getClient()</code> method use the following condition (set <code>client</code> if it's not set yet):</p>\n\n<pre><code>private static function getClient() {\n if (self::$client === null) { # use strict comparison here\n $auth = self::getAuth();\n self::$client = new S3Client([\n 'region' => 'eu-west-2',\n 'version' => '2006-03-01',\n 'endpoint' => $auth['endpoint'],\n 'credentials' => [\n 'key' => $auth['key'],\n 'secret' => $auth['secret']\n ],\n 'use_path_style_endpoint' => true\n ]);\n }\n return self::$client;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:19:22.667",
"Id": "231470",
"ParentId": "231461",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231470",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T12:47:42.303",
"Id": "231461",
"Score": "2",
"Tags": [
"php",
"cache",
"static"
],
"Title": "PHP - using static variables to store \"client\" for later use"
}
|
231461
|
<p>I wrote a <a href="https://github.com/listerone255/md5_speed" rel="noreferrer">minimal implementation of the MD5 algorithm</a>. Comparing to the <a href="https://crates.io/crates/md-5" rel="noreferrer">established MD5 crate</a>, the crate has a 35% better throughput than mine. I'd like to know why.</p>
<p>In reviewing the crate's code (<a href="https://docs.rs/crate/md-5/0.8.0/source/src/utils.rs" rel="noreferrer">relevant section here</a>), I see that it essentially does the same thing as I do. I don't see anything algorithm differences. I've avoided bounds checking. I've unrolled the loop. I've inlined calculations. </p>
<p>Running flamegraph on both algorithms, I see that essentially <em>all</em> time is spend in the iteration loop. Just that the crate's runs 35% faster (crate on left, mine on right):</p>
<p><a href="https://i.stack.imgur.com/dKnql.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dKnql.png" alt="enter image description here"></a></p>
<p>Running criterion gave me the 35% difference:</p>
<pre><code>MD5 comparison/mine time: [146.02 us 146.87 us 147.79 us]
thrpt: [422.91 MiB/s 425.54 MiB/s 428.02 MiB/s]
MD5 comparison/crate time: [107.65 us 108.28 us 109.01 us]
thrpt: [573.34 MiB/s 577.22 MiB/s 580.60 MiB/s]
</code></pre>
<p>That's 577 MB/s vs 425 MB/s.</p>
<p>Here is my code (<a href="https://github.com/listerone255/md5_speed" rel="noreferrer">project here</a>). To those familiar with the MD5 algorithm, can you comment on what could be causing the 35% performance difference?</p>
<pre class="lang-rust prettyprint-override"><code>#![allow(clippy::unreadable_literal)]
fn blockify(inp: &[u8], oup: &mut [u32; 16]) {
use std::convert::TryInto;
let inp = &inp[0..64]; // Avoid bounds checking
*oup = [
u32::from_le_bytes(inp[0..4].try_into().unwrap()),
u32::from_le_bytes(inp[4..8].try_into().unwrap()),
u32::from_le_bytes(inp[8..12].try_into().unwrap()),
u32::from_le_bytes(inp[12..16].try_into().unwrap()),
u32::from_le_bytes(inp[16..20].try_into().unwrap()),
u32::from_le_bytes(inp[20..24].try_into().unwrap()),
u32::from_le_bytes(inp[24..28].try_into().unwrap()),
u32::from_le_bytes(inp[28..32].try_into().unwrap()),
u32::from_le_bytes(inp[32..36].try_into().unwrap()),
u32::from_le_bytes(inp[36..40].try_into().unwrap()),
u32::from_le_bytes(inp[40..44].try_into().unwrap()),
u32::from_le_bytes(inp[44..48].try_into().unwrap()),
u32::from_le_bytes(inp[48..52].try_into().unwrap()),
u32::from_le_bytes(inp[52..56].try_into().unwrap()),
u32::from_le_bytes(inp[56..60].try_into().unwrap()),
u32::from_le_bytes(inp[60..64].try_into().unwrap()),
]
}
#[allow(clippy::cognitive_complexity)]
fn iteration(hs: &mut [u32; 4], xs: &[u8]) {
macro_rules! round_a {
($ms:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $g:expr, $s:expr) => {{
unsafe {
$a = (($b & $c) | (!$b & $d))
.wrapping_add($a)
.wrapping_add($k)
.wrapping_add(*$ms.get_unchecked($g))
.rotate_left($s)
.wrapping_add($b);
}
// println!("{:02}: {:08x} {:08x} {:08x} {:08x}", $i, $a, $b, $c, $d);
}};
}
macro_rules! round_b {
($ms:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $g:expr, $s:expr) => {{
unsafe {
$a = (($d & $b) | (!$d & $c))
.wrapping_add($a)
.wrapping_add($k)
.wrapping_add(*$ms.get_unchecked($g))
.rotate_left($s)
.wrapping_add($b);
}
// println!("{:02}: {:08x} {:08x} {:08x} {:08x}", $i, $a, $b, $c, $d);
}};
}
macro_rules! round_c {
($ms:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $g:expr, $s:expr) => {{
unsafe {
$a = ($b ^ $c ^ $d)
.wrapping_add($a)
.wrapping_add($k)
.wrapping_add(*$ms.get_unchecked($g))
.rotate_left($s)
.wrapping_add($b);
}
// println!("{:02}: {:08x} {:08x} {:08x} {:08x}", $i, $a, $b, $c, $d);
}};
}
macro_rules! round_d {
($ms:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $g:expr, $s:expr) => {{
unsafe {
$a = ($c ^ ($b | !$d))
.wrapping_add($a)
.wrapping_add($k)
.wrapping_add(*$ms.get_unchecked($g))
.rotate_left($s)
.wrapping_add($b);
}
// println!("{:02}: {:08x} {:08x} {:08x} {:08x}", $i, $a, $b, $c, $d);
}};
}
let mut ms = [0; 16];
blockify(xs, &mut ms);
let mut r0 = hs[0];
let mut r1 = hs[1];
let mut r2 = hs[2];
let mut r3 = hs[3];
round_a!(ms, 0, r0, r1, r2, r3, 0xd76aa478, 0, 7);
round_a!(ms, 1, r3, r0, r1, r2, 0xe8c7b756, 1, 12);
round_a!(ms, 2, r2, r3, r0, r1, 0x242070db, 2, 17);
round_a!(ms, 3, r1, r2, r3, r0, 0xc1bdceee, 3, 22);
round_a!(ms, 4, r0, r1, r2, r3, 0xf57c0faf, 4, 7);
round_a!(ms, 5, r3, r0, r1, r2, 0x4787c62a, 5, 12);
round_a!(ms, 6, r2, r3, r0, r1, 0xa8304613, 6, 17);
round_a!(ms, 7, r1, r2, r3, r0, 0xfd469501, 7, 22);
round_a!(ms, 8, r0, r1, r2, r3, 0x698098d8, 8, 7);
round_a!(ms, 9, r3, r0, r1, r2, 0x8b44f7af, 9, 12);
round_a!(ms, 10, r2, r3, r0, r1, 0xffff5bb1, 10, 17);
round_a!(ms, 11, r1, r2, r3, r0, 0x895cd7be, 11, 22);
round_a!(ms, 12, r0, r1, r2, r3, 0x6b901122, 12, 7);
round_a!(ms, 13, r3, r0, r1, r2, 0xfd987193, 13, 12);
round_a!(ms, 14, r2, r3, r0, r1, 0xa679438e, 14, 17);
round_a!(ms, 15, r1, r2, r3, r0, 0x49b40821, 15, 22);
round_b!(ms, 16, r0, r1, r2, r3, 0xf61e2562, 1, 5);
round_b!(ms, 17, r3, r0, r1, r2, 0xc040b340, 6, 9);
round_b!(ms, 18, r2, r3, r0, r1, 0x265e5a51, 11, 14);
round_b!(ms, 19, r1, r2, r3, r0, 0xe9b6c7aa, 0, 20);
round_b!(ms, 20, r0, r1, r2, r3, 0xd62f105d, 5, 5);
round_b!(ms, 21, r3, r0, r1, r2, 0x02441453, 10, 9);
round_b!(ms, 22, r2, r3, r0, r1, 0xd8a1e681, 15, 14);
round_b!(ms, 23, r1, r2, r3, r0, 0xe7d3fbc8, 4, 20);
round_b!(ms, 24, r0, r1, r2, r3, 0x21e1cde6, 9, 5);
round_b!(ms, 25, r3, r0, r1, r2, 0xc33707d6, 14, 9);
round_b!(ms, 26, r2, r3, r0, r1, 0xf4d50d87, 3, 14);
round_b!(ms, 27, r1, r2, r3, r0, 0x455a14ed, 8, 20);
round_b!(ms, 28, r0, r1, r2, r3, 0xa9e3e905, 13, 5);
round_b!(ms, 29, r3, r0, r1, r2, 0xfcefa3f8, 2, 9);
round_b!(ms, 30, r2, r3, r0, r1, 0x676f02d9, 7, 14);
round_b!(ms, 31, r1, r2, r3, r0, 0x8d2a4c8a, 12, 20);
round_c!(ms, 32, r0, r1, r2, r3, 0xfffa3942, 5, 4);
round_c!(ms, 33, r3, r0, r1, r2, 0x8771f681, 8, 11);
round_c!(ms, 34, r2, r3, r0, r1, 0x6d9d6122, 11, 16);
round_c!(ms, 35, r1, r2, r3, r0, 0xfde5380c, 14, 23);
round_c!(ms, 36, r0, r1, r2, r3, 0xa4beea44, 1, 4);
round_c!(ms, 37, r3, r0, r1, r2, 0x4bdecfa9, 4, 11);
round_c!(ms, 38, r2, r3, r0, r1, 0xf6bb4b60, 7, 16);
round_c!(ms, 39, r1, r2, r3, r0, 0xbebfbc70, 10, 23);
round_c!(ms, 40, r0, r1, r2, r3, 0x289b7ec6, 13, 4);
round_c!(ms, 41, r3, r0, r1, r2, 0xeaa127fa, 0, 11);
round_c!(ms, 42, r2, r3, r0, r1, 0xd4ef3085, 3, 16);
round_c!(ms, 43, r1, r2, r3, r0, 0x04881d05, 6, 23);
round_c!(ms, 44, r0, r1, r2, r3, 0xd9d4d039, 9, 4);
round_c!(ms, 45, r3, r0, r1, r2, 0xe6db99e5, 12, 11);
round_c!(ms, 46, r2, r3, r0, r1, 0x1fa27cf8, 15, 16);
round_c!(ms, 47, r1, r2, r3, r0, 0xc4ac5665, 2, 23);
round_d!(ms, 48, r0, r1, r2, r3, 0xf4292244, 0, 6);
round_d!(ms, 49, r3, r0, r1, r2, 0x432aff97, 7, 10);
round_d!(ms, 50, r2, r3, r0, r1, 0xab9423a7, 14, 15);
round_d!(ms, 51, r1, r2, r3, r0, 0xfc93a039, 5, 21);
round_d!(ms, 52, r0, r1, r2, r3, 0x655b59c3, 12, 6);
round_d!(ms, 53, r3, r0, r1, r2, 0x8f0ccc92, 3, 10);
round_d!(ms, 54, r2, r3, r0, r1, 0xffeff47d, 10, 15);
round_d!(ms, 55, r1, r2, r3, r0, 0x85845dd1, 1, 21);
round_d!(ms, 56, r0, r1, r2, r3, 0x6fa87e4f, 8, 6);
round_d!(ms, 57, r3, r0, r1, r2, 0xfe2ce6e0, 15, 10);
round_d!(ms, 58, r2, r3, r0, r1, 0xa3014314, 6, 15);
round_d!(ms, 59, r1, r2, r3, r0, 0x4e0811a1, 13, 21);
round_d!(ms, 60, r0, r1, r2, r3, 0xf7537e82, 4, 6);
round_d!(ms, 61, r3, r0, r1, r2, 0xbd3af235, 11, 10);
round_d!(ms, 62, r2, r3, r0, r1, 0x2ad7d2bb, 2, 15);
round_d!(ms, 63, r1, r2, r3, r0, 0xeb86d391, 9, 21);
*hs = [
hs[0].wrapping_add(r0),
hs[1].wrapping_add(r1),
hs[2].wrapping_add(r2),
hs[3].wrapping_add(r3),
];
}
pub fn md5(input: &[u8]) -> String {
let mut hs = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
let mut iter = input.chunks_exact(64);
for chunk in &mut iter {
iteration(&mut hs, &chunk);
}
let mut buf = [0; 64];
buf[0] = 128;
buf[56..64].copy_from_slice(&((input.len() * 8) as u64).to_le_bytes());
iteration(&mut hs, &buf);
// format!(
// "{:08x}{:08x}{:08x}{:08x}",
// hs[0].swap_bytes(),
// hs[1].swap_bytes(),
// hs[2].swap_bytes(),
// hs[3].swap_bytes()
// )
String::new() // Avoid format! for benchmarking
}
</code></pre>
<hr>
<p>As an aside, because it has been suspected that the <code>blockify</code> function is the bottleneck, I note that I have already tried inlining <code>unsafe { &*(inp.as_ptr() as *const [u32; 16]) }</code> to directly convert <code>&[u8]</code> to <code>&[u32;16]</code> without creating a new array. This is highly non-portable, but regardless made no difference whatsoever to the performance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:08:53.213",
"Id": "451490",
"Score": "0",
"body": "FYI, when I say _minimal_, I mean that it only deals with input that is multiples of 64 bytes in size. I have not implemented block buffering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:10:10.757",
"Id": "451491",
"Score": "0",
"body": "Not entirely sure this has anything to do with MD5 itself, as it looks like the reference implementation is designed to take advantage of inlining, for example. Yours explicitly prevents this due to your choice of code structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:12:30.340",
"Id": "451492",
"Score": "0",
"body": "@SébastienRenauld How does mine prevent inlining? I've actually inlined all the calculations via macros. How does the crate take advantage of inlining?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:16:24.960",
"Id": "451493",
"Score": "0",
"body": "So did the [reference crate](https://docs.rs/crate/md-5/0.8.0/source/src/utils.rs), and your macros work out to pretty much the same thing after expansion. However, their variant is more efficient on the block generation **and** allows them to inline the *entire* function, whereas yours does not. I strongly suspect this is where the performance loss is coming from. On top of that, their block layout is, frankly, better due to their assumption that the original variables *are* defined, something you cannot do (and therefore have a `get_unchecked` call at every round)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:20:07.537",
"Id": "451496",
"Score": "0",
"body": "@SébastienRenauld Block generation is not significant. I've separately tested this. Even with `unsafe { &*(xs.as_ptr() as *const [u32; 16]) }` to convert the block without actually generating it, the throughput is the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:21:07.617",
"Id": "451497",
"Score": "0",
"body": "@SébastienRenauld And I don't understand what you mean by block layout. Please elaborate by pointing out the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:53:21.813",
"Id": "451516",
"Score": "0",
"body": "It’s got nothing to do with inlining as the comments incorrectly point out. The crate uses md5_asm when compiling on x64 and x86, which implements the loop in assembly, optimizing register pressure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T02:04:27.640",
"Id": "451570",
"Score": "0",
"body": "@OneTwoMany, that appears to only be the case if you turn on the asm feature."
}
] |
[
{
"body": "<p>After some experimentation, the issue does not appear to be your code.</p>\n\n<p>In fact, if you copy the MD5 implementation from the other crate into your crate that copy will still run slower than the version in the other crate. Instead, it runs about the same speed as your code.</p>\n\n<p>I'm not sure what's going on, but it probably has to do with the limitations of optimizations crossing a crate boundary. Probably, some optimization that the rust compiler thinks is a good idea actually degrades performance and this optimization happens to not be possible if the code is split into two crates.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T02:04:09.773",
"Id": "231501",
"ParentId": "231463",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T14:02:17.683",
"Id": "231463",
"Score": "5",
"Tags": [
"rust"
],
"Title": "Why is my MD5 implementation 35% slower than the md-5 crate?"
}
|
231463
|
<p>I have to write a code which takes (integers) numbers from Command-line and keeps reading the terminal until it gets a word <code>END</code></p>
<p>So I wrote the following; I feel its really bad. Is there any way I can improve below code</p>
<p>I updated my code from <a href="https://play.golang.org/p/FfIuuZ26QtX" rel="nofollow noreferrer">previously</a> to below</p>
<pre><code>func main() {
buf := bufio.NewReader(os.Stdin)
lines, err := buf.ReadBytes('\n')
if err != nil {
return
}
fmt.Printf(" %q \n", string(lines))
line := strings.Replace(string(lines), "\n", "", -1)
numbers := strings.Split(line, " ")
fmt.Printf("numbers %q ", numbers)
var sum int64
for _, num := range numbers {
num, err := strconv.ParseInt(num, 10, 0)
if err != nil {
fmt.Println(err)
break
}
sum += num
}
fmt.Println("Sum of all numbers :", sum)
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>takes (integers) numbers from Command-line and keeps reading the\n terminal until it gets a word END.</p>\n</blockquote>\n\n<hr>\n\n<p>For example,</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\nfunc main() {\n sum := int64(0)\n s := bufio.NewScanner(os.Stdin)\n s.Split(bufio.ScanWords)\n for s.Scan() {\n word := s.Text()\n num, err := strconv.ParseInt(word, 10, 64)\n if err != nil {\n if strings.ToUpper(word) == \"END\" {\n break\n }\n fmt.Fprintln(os.Stderr, err)\n continue\n }\n sum += num\n }\n if err := s.Err(); err != nil {\n fmt.Fprintln(os.Stderr, err)\n }\n fmt.Println(\"Sum of all numbers:\", sum)\n}\n</code></pre>\n\n<p>Terminal:</p>\n\n<pre><code>12 24 \n36 \n6\n6\n END\nSum of all numbers: 84\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T21:33:58.553",
"Id": "231493",
"ParentId": "231471",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231493",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T15:21:39.940",
"Id": "231471",
"Score": "1",
"Tags": [
"beginner",
"go",
"io"
],
"Title": "Keep reading Command-line until you get the word END"
}
|
231471
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.